text:
package com.thebluealliance.androidclient.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;

import androidx.appcompat.widget.Toolbar;
import androidx.core.view.ViewCompat;
import androidx.viewpager.widget.ViewPager;

import com.thebluealliance.androidclient.NfcUris;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.ShareUris;
import com.thebluealliance.androidclient.TbaLogger;
import com.thebluealliance.androidclient.Utilities;
import com.thebluealliance.androidclient.adapters.ViewEventFragmentPagerAdapter;
import com.thebluealliance.androidclient.eventbus.ActionBarTitleEvent;
import com.thebluealliance.androidclient.helpers.ConnectionDetector;
import com.thebluealliance.androidclient.helpers.EventHelper;
import com.thebluealliance.androidclient.models.ApiStatus;
import com.thebluealliance.androidclient.types.ModelType;
import com.thebluealliance.androidclient.views.SlidingTabs;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class ViewEventActivity extends MyTBASettingsActivity
        implements ViewPager.OnPageChangeListener {

    public static final String EVENTKEY = "eventKey";
    public static final String TAB = "tab";

    private String mEventKey;
    private int mSelectedTab;
    private ViewPager pager;
    private ViewEventFragmentPagerAdapter adapter;
    private boolean isDistrict;

    /**
     * Will be run in {@code onResume()}; used to perform UI setup that can't happen before the
     * activity is resumed
     */
    private Runnable mOnNewIntentRunnable;

    /**
     * Create new intent for ViewEventActivity
     *
     * @param c        context
     * @param eventKey Key of the event to show
     * @param tab      The tab number from ViewEventFragmentPagerAdapter.
     * @return Intent you can launch
     */
    public static Intent newInstance(Context c, String eventKey, int tab) {
        Intent intent = new Intent(c, ViewEventActivity.class);
        intent.putExtra(EVENTKEY, eventKey);
        intent.putExtra(TAB, tab);
        return intent;
    }

    public static Intent newInstance(Context c, String eventKey) {
        return newInstance(c, eventKey, ViewEventFragmentPagerAdapter.TAB_INFO);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle extras = getIntent().getExtras() == null ? new Bundle() : getIntent().getExtras();

        mEventKey = extras.getString(EVENTKEY, "");
        if (!EventHelper.validateEventKey(mEventKey)) {
            throw new IllegalArgumentException("ViewEventActivity must be given a valid event key");
        }

        mSelectedTab = extras.getInt(TAB, ViewEventFragmentPagerAdapter.TAB_INFO);

        setModelKey(mEventKey, ModelType.EVENT);
        setShareEnabled(true);
        setContentView(R.layout.activity_view_event);

        pager = (ViewPager) findViewById(R.id.view_pager);
        adapter = new ViewEventFragmentPagerAdapter(getSupportFragmentManager(), mEventKey);
        pager.setAdapter(adapter);
        // To support refreshing, all pages must be held in memory at once
        // This should be increased if we ever add more pages
        pager.setOffscreenPageLimit(10);
        pager.setPageMargin(Utilities.getPixelsFromDp(this, 16));

        SlidingTabs tabs = (SlidingTabs) findViewById(R.id.tabs);
        tabs.setOnPageChangeListener(this);
        tabs.setViewPager(pager);
        ViewCompat.setElevation(tabs, getResources().getDimension(R.dimen.toolbar_elevation));

        pager.setCurrentItem(mSelectedTab);  // Do this after we set onPageChangeListener, so that FAB gets hidden, if needed

        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        setupActionBar();

        if (!ConnectionDetector.isConnectedToInternet(this)) {
            showWarningMessage(BaseActivity.WARNING_OFFLINE);
        }

        isDistrict = true;

        setSettingsToolbarTitle("Event Settings");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        TbaLogger.d("onNewIntent called");
        setIntent(intent);
        String newEventKey;

        Bundle extras = intent.getExtras() == null ? new Bundle() : intent.getExtras();

        newEventKey = extras.getString(EVENTKEY, "");
        if (!EventHelper.validateEventKey(newEventKey)) {
            throw new IllegalArgumentException("ViewEventActivity must be constructed with a key");
        }

        mSelectedTab = extras.getInt(TAB, ViewEventFragmentPagerAdapter.TAB_INFO);

        if (mEventKey != null && newEventKey.equals(mEventKey)) {
            // The event keys are the same; don't recreate anything
            return;
        } else {
            mEventKey = newEventKey;
        }
        setModelKey(mEventKey, ModelType.EVENT);

        mOnNewIntentRunnable = () -> {
            // If the settings panel was open before, close it
            closeSettingsPanel(false);

            // Reset the title; this will be set from the EventInfoFragment
            setActionBarTitle("");

            adapter.removeAllFragments();
            adapter = new ViewEventFragmentPagerAdapter(getSupportFragmentManager(), mEventKey);
            pager.setAdapter(adapter);
            pager.setCurrentItem(mSelectedTab);
        };

        TbaLogger.d("Got new ViewEvent intent with key: " + mEventKey);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setBeamUri(String.format(NfcUris.URI_EVENT, mEventKey));
        setShareUri(String.format(ShareUris.URI_EVENT, mEventKey));

        if (mOnNewIntentRunnable != null) {
            mOnNewIntentRunnable.run();
            mOnNewIntentRunnable = null;
        }
    }

    @Override
    public void onCreateNavigationDrawer() {
        useActionBarToggle(false);
        encourageLearning(false);
    }

    private void setupActionBar() {
        if (getSupportActionBar() == null) {
            return;
        }
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // The title is empty now; the EventInfoFragment will set the appropriate title
        // once it is loaded.
        setActionBarTitle("");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                if (isDrawerOpen()) {
                    closeDrawer();
                    return true;
                }
                // If this tasks exists in the back stack, it will be brought to the front and all other activities
                // will be destroyed. HomeActivity will be delivered this intent via onNewIntent().
                startActivity(HomeActivity.newInstance(this, R.id.nav_item_events).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                return true;
            case R.id.stats_help:
                Utilities.showHelpDialog(this, R.raw.stats_help, getString(R.string.stats_help_title));
                return true;
            case R.id.points_help:
                Utilities.showHelpDialog(this, R.raw.district_points_help, getString(R.string.district_points_help));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public ViewPager getPager() {
        return pager;
    }

    public void scrollToTab(int tab) {
        if (pager != null) {
            pager.setCurrentItem(tab);
        }
    }

    @Override
    protected void onTbaStatusUpdate(ApiStatus newStatus) {
        super.onTbaStatusUpdate(newStatus);
        if (newStatus.getDownEvents().contains(mEventKey)) {
            // This event is down
            showWarningMessage(BaseActivity.WARNING_EVENT_DOWN);
        } else {
            // This event is not down! Hide the message if it was previously displayed
            dismissWarningMessage(BaseActivity.WARNING_EVENT_DOWN);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mSelectedTab = position;

        // hide the FAB if we aren't on the first page
        if (position != ViewEventFragmentPagerAdapter.TAB_INFO) {
            hideFab(true);
        } else {
            syncFabVisibilityWithMyTbaEnabled(true);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onActionBarTitleUpdated(ActionBarTitleEvent event) {
        setActionBarTitle(event.getTitle());
        setActionBarSubtitle(event.getSubtitle());
    }
}


text:
@interface UnitTests : XCTestCase
@end

@implementation UnitTests

- (void)testTeardownRemovesHTTPStubs
{
    XCTAssertTrue([OHHTTPStubs allStubs].count == 0, @"Initial number of stubs should be zero.");

    [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
        return YES;
    } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
        return [OHHTTPStubsResponse responseWithData:nil statusCode:400 headers:nil];
    }];

    XCTAssertTrue([OHHTTPStubs allStubs].count == 1, @"There should be one stubbed request.");

    [self tearDown];

    XCTAssertTrue([OHHTTPStubs allStubs].count == 0, @"Teardown should remove all stubs.");
}

@end

redpajama_set_name: RedPajamaGithub


text:
#import "ConversationItemView.h"
#import "InterfaceLayoutDefinitions.h"

@implementation ConversationItemView

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(!self)
        return nil;

    [self.textLabel removeFromSuperview];
    self.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];

    _nameLabel              = [[UILabel alloc] initWithFrame:CGRectZero];
    _nameLabel.font         = [InterfaceLayoutDefinitions largeLabelFont];
    _nameLabel.textColor    = [InterfaceLayoutDefinitions largeLabelTextColour];

    _firstDetailLabel           = [[UILabel alloc] initWithFrame:CGRectZero];
    _firstDetailLabel.font      = [InterfaceLayoutDefinitions standardLabelFont];
    _firstDetailLabel.textColor = [InterfaceLayoutDefinitions labelTextColour];

    _secondDetailLabel              = [[UILabel alloc] initWithFrame:CGRectZero];
    _secondDetailLabel.font         = [InterfaceLayoutDefinitions standardLabelFont];
    _secondDetailLabel.textColor    = [InterfaceLayoutDefinitions labelTextColour];

    _unreadCountLabel               = [[UILabel alloc] initWithFrame:CGRectZero];
    _unreadCountLabel.font          = [InterfaceLayoutDefinitions standardLabelFont];
    _unreadCountLabel.textColor     = [InterfaceLayoutDefinitions labelTextColour];

    _overlayView = [[UIView alloc] initWithFrame:CGRectZero];
    _overlayView.backgroundColor = self.backgroundColor;

    [self.contentView addSubview:_nameLabel];
    [self.contentView addSubview:_firstDetailLabel];
    [self.contentView addSubview:_secondDetailLabel];
    [self.contentView addSubview:_unreadCountLabel];
    [self.contentView addSubview:_overlayView];

    _isChannel = YES;
    _isConsole = NO;
    _enabled = NO;

    self.imageView.image = [UIImage imageNamed:@"ChannelIcon"];
    _previewMessages = [[NSMutableArray alloc] init];
    _unreadCount = 0;

    return self;
}

-(void)layoutSubviews
{

    [super layoutSubviews];

    if (_isConsole)
        self.imageView.image = [UIImage imageNamed:@"Console"];
    else if (!_isChannel)
        self.imageView.image = [UIImage imageNamed:@"QueryIcon"];
    else
        self.imageView.image = [UIImage imageNamed:@"ChannelIcon"];

    CGRect frame = self.contentView.frame;
    frame.size.width += 30.0f;

    _overlayView.frame = frame;

    if (!_enabled) {
        _overlayView.alpha = DISABLED_OPACITY_LEVEL;
        self.imageView.alpha = DISABLED_OPACITY_LEVEL;
    } else {
        _overlayView.alpha = HIDDEN_OPACITY_LEVEL;
        self.imageView.alpha = ENABLED_OPACITY_LEVEL;
    }

    CGSize size = [_name sizeWithAttributes:@{NSFontAttributeName: _nameLabel.font}];

    frame = self.imageView.frame;
    frame.origin.y -= 4;
    frame.origin.x = frame.origin.x*2+frame.size.width;
    frame.size = size;

    _nameLabel.text = self.name;
    _nameLabel.frame = frame;

    NSAttributedString *firstdetail;
    NSAttributedString *seconddetail;

    if(_previewMessages.count > 0)
        firstdetail = _previewMessages[0];

    if(_previewMessages.count > 1)
        seconddetail = _previewMessages[1];

    frame.origin.y = round(self.imageView.frame.size.height / 2) + self.imageView.frame.origin.y - 5;

    frame.size = firstdetail.size;
    frame.size.width = self.contentView.frame.size.width - self.imageView.frame.size.width;
    frame.size.height += 1;

    _firstDetailLabel.attributedText = firstdetail;
    _firstDetailLabel.frame = frame;

    frame.origin.y += 15;
    frame.size = seconddetail.size;
    frame.size.width = self.contentView.frame.size.width - self.imageView.frame.size.width;
    frame.size.height += 1;

    _secondDetailLabel.attributedText = seconddetail;
    _secondDetailLabel.frame = frame;

    NSArray *subviews;
    NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    if ([[vComp objectAtIndex:0] intValue] >= 8) {
        // iOS 8 and newer
        subviews = self.subviews;
    } else {
        // iOS 7
        subviews = [self.subviews[0] subviews];
    }

    NSString *value = [NSString stringWithFormat:@"%li", (long)_unreadCount];

    if(_unreadCount > 0)
        _unreadCountLabel.text = value;
    else
        _unreadCountLabel.text = @"";

    for (UIView *subview in subviews) {
        if([NSStringFromClass(subview.class) isEqualToString:@"DisclosureView"]) {
            // This subview should be the accessory view, change its frame
            CGRect frame = subview.frame;
            frame.origin.y -= 15;
            subview.frame = frame;

                // Calculate frame size
            CGSize size = [value sizeWithAttributes:@{NSFontAttributeName: _unreadCountLabel.font }];
            _unreadCountLabel.frame = CGRectMake(frame.origin.x-size.width-5, frame.origin.y-2, size.width, size.height);

            break;
        }
    }

}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace SwqlStudio
{
    static class Utility
    {
        public static string GetFqdn()
        {
            string domainName = string.Empty;
            try
            {
                domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            }
            catch
            {
            }
            string fqdn = "localhost";
            try
            {
                fqdn = Dns.GetHostName();
                if (!string.IsNullOrEmpty(domainName))
                {
                    if (!fqdn.ToLowerInvariant().EndsWith("." + domainName.ToLowerInvariant()))
                    {
                        fqdn += "." + domainName;
                    }
                }
            }
            catch
            {
            }
            return fqdn;
        }
    }
}


text:
enum {
    kTagLabel1,
    kTagLabel2,
    kTagLabel3,
    kTagLabel4,

    kTagColor1,
    kTagColor2,
    kTagColor3,
};

static int fontIdx = 0;

static std::string fontList[] =
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    // custom ttf files are defined in Test-info.plist
    "American Typewriter",
    "Marker Felt",
#endif
    "fonts/A Damn Mess.ttf",
    "fonts/Abberancy.ttf",
    "fonts/Abduction.ttf",
    "fonts/Paint Boy.ttf",
    "fonts/Schwarzwald Regular.ttf",
    "fonts/Scissor Cuts.ttf",
};

static int fontCount = sizeof(fontList) / sizeof(*fontList);

static int vAlignIdx = 0;
static TextVAlignment verticalAlignment[] =
{
    TextVAlignment::TOP,
    TextVAlignment::CENTER,
    TextVAlignment::BOTTOM,
};
static int vAlignCount = sizeof(verticalAlignment) / sizeof(*verticalAlignment);

static const char* nextAction(void)
{
    fontIdx++;
    if(fontIdx >= fontCount) {
        fontIdx = 0;
        vAlignIdx = (vAlignIdx + 1) % vAlignCount;
    }
    return fontList[fontIdx].c_str();
}

static const char* backAction(void)
{
    fontIdx--;
    if( fontIdx < 0 ) {
        fontIdx = fontCount - 1;
        vAlignIdx--;
        if(vAlignIdx < 0)
            vAlignIdx = vAlignCount - 1;
    }

    return fontList[fontIdx].c_str();
}

static const char* restartAction(void)
{
    return fontList[fontIdx].c_str();
}

FontTest::FontTest()
: BaseTest()
{
    showFont(restartAction());
}

void FontTest::showFont(const char *pFont)
{
    auto s = Director::getInstance()->getWinSize();

    auto blockSize = Size(s.width/3, 200);
    float fontSize = 26;

    removeChildByTag(kTagLabel1, true);
    removeChildByTag(kTagLabel2, true);
    removeChildByTag(kTagLabel3, true);
    removeChildByTag(kTagLabel4, true);
    removeChildByTag(kTagColor1, true);
    removeChildByTag(kTagColor2, true);
    removeChildByTag(kTagColor3, true);

    auto top = LabelTTF::create(pFont, pFont, 24);
    auto left = LabelTTF::create("alignment left", pFont, fontSize,
                                          blockSize, TextHAlignment::LEFT, verticalAlignment[vAlignIdx]);
    auto center = LabelTTF::create("alignment center", pFont, fontSize,
                                            blockSize, TextHAlignment::CENTER, verticalAlignment[vAlignIdx]);
    auto right = LabelTTF::create("alignment right", pFont, fontSize,
                                           blockSize, TextHAlignment::RIGHT, verticalAlignment[vAlignIdx]);

    auto leftColor = LayerColor::create(Color4B(100, 100, 100, 255), blockSize.width, blockSize.height);
    auto centerColor = LayerColor::create(Color4B(200, 100, 100, 255), blockSize.width, blockSize.height);
    auto rightColor = LayerColor::create(Color4B(100, 100, 200, 255), blockSize.width, blockSize.height);

    leftColor->ignoreAnchorPointForPosition(false);
    centerColor->ignoreAnchorPointForPosition(false);
    rightColor->ignoreAnchorPointForPosition(false);

    top->setAnchorPoint(Point(0.5, 1));
    left->setAnchorPoint(Point(0,0.5));
    leftColor->setAnchorPoint(Point(0,0.5));
    center->setAnchorPoint(Point(0,0.5));
    centerColor->setAnchorPoint(Point(0,0.5));
    right->setAnchorPoint(Point(0,0.5));
    rightColor->setAnchorPoint(Point(0,0.5));

    top->setPosition(Point(s.width/2,s.height-20));
    left->setPosition(Point(0,s.height/2));
    leftColor->setPosition(left->getPosition());
    center->setPosition(Point(blockSize.width, s.height/2));
    centerColor->setPosition(center->getPosition());
    right->setPosition(Point(blockSize.width*2, s.height/2));
    rightColor->setPosition(right->getPosition());

    this->addChild(leftColor, -1, kTagColor1);
    this->addChild(left, 0, kTagLabel1);
    this->addChild(rightColor, -1, kTagColor2);
    this->addChild(right, 0, kTagLabel2);
    this->addChild(centerColor, -1, kTagColor3);
    this->addChild(center, 0, kTagLabel3);
    this->addChild(top, 0, kTagLabel4);
}

void FontTest::backCallback(Object* sender)
{
    showFont(backAction());
}

void FontTest::nextCallback(Object* sender)
{
    showFont(nextAction());
}

std::string FontTest::title()
{
    return "Font test";
}

void FontTest::restartCallback(Object* sender)
{
    showFont(restartAction());
}

///---------------------------------------
//
// DirectorTestScene
//
///---------------------------------------
void FontTestScene::runThisTest()
{
    auto layer = FontTest::create();
    addChild(layer);

    Director::getInstance()->replaceScene(this);
}


text:
(function (w) {
    var Handler = function (pattern, func) {
        this.pattern = pattern;
        this.func = func;
    };
    Handler.prototype = {
        test: function (str) {
            return this.pattern.test(str);
        },
        exec: function (obj) {
            return this.func(obj);
        }
    };
    var Listener = function () {
        this.chain = [];
        this.listening = false;
    };
    Listener.prototype = {
        /**
         * 待ち受け開始
         */
        listen: function () {
            if (this.listening)return;
            var _self = this;
            chrome.devtools.network.onRequestFinished.addListener(function (request) {
                var url = request.request.url.replace(/https?:\/\/.+?\//, "/");
                _self.chain.first(function (e) {
                    return e.test(url);
                }).ifPresent(function (e) {
                    request.getContent(function (content, encoding) {
                        var json = JSON.parse(content.replace('svdata=', ''));
                        //console.log('handle url : '+url);
                        e.exec(json);
                    });
                });
            });
            console.log('listen started');
            this.listening = true;
        },
        /**
         * 任意のURLに関数をハンドリングする
         *
         * @param pattern パスの正規表現
         * @param func 関数
         */
        handle: function (pattern, func) {
            this.chain.push(new Handler(pattern, func));
            return this;
        }
    };
    w.devtoolsResponceListener = new Listener();
})(window);


text:
inline char M2TagToNumeric (Numeric_e tag)
{
  char c;
  switch (tag) {
  case M2_BYTE: c='1'; break;
  case M2_UBYTE: c='b'; break;
  case M2_INTEGER: c='s'; break;
  case M2_UINTEGER: c='w'; break;
  case M2_LONG: c='i'; break;
  case M2_ULONG: c='u'; break;
  case M2_XLONG: c='l'; break;
  case M2_UXLONG: c='l'; break;
    //case M2_BOOL: c='b'; break;
  case M2_FLOAT: c='f'; break;
  case M2_DOUBLE: c='d'; break;
  case M2_CX_FLOAT: c='F'; break;
  case M2_CX_DOUBLE: c='D'; break;
  default: throw MidasException("No corresponding Numeric type for Number type");
  }
  return c;
}

// Convert from Numeric tag to M2 Tag
inline Numeric_e NumericTagToM2 (char tag)
{
  Numeric_e c;
  switch (tag) {
  case '1': c=M2_BYTE; break;
  case 'b': c=M2_UBYTE; break;
  case 's': c=M2_INTEGER; break;
  case 'w': c=M2_UINTEGER; break;
  case 'i': c=M2_LONG; break;
  case 'u': c=M2_ULONG; break;
  case 'l': c=M2_XLONG; break;
    //case 'l': c=M2_UXLONG; break;
    //case 'b': c='b'; break;
  case 'f': c=M2_FLOAT; break;
  case 'd': c=M2_DOUBLE; break;
  case 'F': c=M2_CX_FLOAT; break;
  case 'D': c=M2_CX_DOUBLE; break;
  default: throw MidasException("No corresponding Numeric type for OpalValue type");
  }
  return c;
}

// Convert low-level bytes to another type: this assumes both input
// and output have the right number of elements
template <class IT, class OT>
inline void BufferConvert (const IT* in, OT* out, int len)
{
  for (int ii=0; ii<len; ii++) {
    out[ii] = OT(in[ii]);
  }
}

// Convert low-level bytes to another type: this assumes both input
// and output have the right number of elements
template <class IT, class OT>
inline void BufferCXConvert (const IT* in, OT* out, int len)
{
  for (int ii=0; ii<len; ii++) {
    out[ii] = OT(in[ii].re, in[ii].im);
  }
}

// helper function to convert from POD array to a different type of POD array
//#define OCCVTARRT(T) { result=Array<T>(len); Array<T>& c=result; c.expandTo(len); T* cdata=c.data(); BufferConvert(a,cdata,len); }
#define OCCVTARRT(T) { T*cdata=(T*)result.writeData(); BufferConvert(a,cdata,len); }
#define OCCVTCXARRT(T) { T*cdata=(T*)result.writeData(); BufferCXConvert(a,cdata,len); }

template <class T>
inline void ConvertArrayT_ (const T* a, const int len, Numeric_e to_type,
			    Vector& result, bool is_complex=false)
{
  switch (to_type) {
  case M2_BYTE: OCCVTARRT(int_1); break;
  case M2_UBYTE: OCCVTARRT(int_u1); break;
  case M2_INTEGER: OCCVTARRT(int_2 ); break;
  case M2_UINTEGER: OCCVTARRT(int_u2); break;
  case M2_LONG: OCCVTARRT(int_4); break;
  case M2_ULONG: OCCVTARRT(int_u4); break;
    // Take care with these ... longs and int_8s not necessarily the same
  case M2_XLONG: OCCVTARRT(int_8); break; // TODo exception?
  case M2_UXLONG: OCCVTARRT(int_u8); break;
    //case M2_BOOL: OCCVTARRT(bool); break;
  case M2_FLOAT: OCCVTARRT(real_4); break;
  case M2_DOUBLE: OCCVTARRT(real_8); break;
  case M2_CX_FLOAT: OCCVTARRT(complex_8); break;
  case M2_CX_DOUBLE: OCCVTARRT(complex_16); break;
  default: throw MidasException("Array not a POD type");
  }
}
template <class T>
inline void ConvertCXArrayT_ (const T* a, const int len, Numeric_e to_type,
			      Vector& result, bool is_complex=false)
{
  switch (to_type) {
  case M2_CX_FLOAT: OCCVTCXARRT(complex_8); break;
  case M2_CX_DOUBLE: OCCVTCXARRT(complex_16); break;
  default: throw MidasException("Cannot convert array of complex to anything but another complex: Use mag2? mag? re? im?"); break;
  }
}

// Convert a pre-existing array from one type to the given type: this
// completely installs the new converted array into a.
//#define OCCONVERTARRAY(T, A, TAG) { Array<T>& aa=A; ConvertArrayT_<T>(aa.data(), aa.length(), TAG, result); }
#define OCCONVERTARRAY(T, A, TAG) { T*data=(T*)a.readData(); ConvertArrayT_<T>(data, a.elements(), TAG, result); }

//#define OCCONVERTCXARRAY(T, A, TAG) { Array<T>& aa=A; ConvertCXArrayT_<T>(aa.data(), aa.length(), TAG, result); }
#define OCCONVERTCXARRAY(T, A, TAG) { T*data=(T*)a.readData(); ConvertCXArrayT_<T>(data, a.elements(), TAG, result); }
inline void ConvertArray (Vector& a, Numeric_e to_type)
{
  Numeric_e this_tag = a.type();
  if (this_tag == to_type) return;  // Both same, no work

  Vector result(to_type, a.elements());  // uninitialized vector

  switch (this_tag) {
  case M2_BYTE: OCCONVERTARRAY(int_1,  a, to_type); break;
  case M2_UBYTE: OCCONVERTARRAY(int_u1, a, to_type);; break;
  case M2_INTEGER: OCCONVERTARRAY(int_2,  a, to_type);; break;
  case M2_UINTEGER: OCCONVERTARRAY(int_u2, a, to_type);; break;
  case M2_LONG: OCCONVERTARRAY(int_4,  a, to_type);; break;
  case M2_ULONG: OCCONVERTARRAY(int_u4, a, to_type);; break;
  case M2_XLONG: OCCONVERTARRAY(int_8,  a, to_type);; break;
  case M2_UXLONG: OCCONVERTARRAY(int_u8, a, to_type);; break;
    //case M2_BOOL: OCCONVERTARRAY(bool,   a, to_type);; break;
  case M2_FLOAT: OCCONVERTARRAY(real_4, a, to_type);; break;
  case M2_DOUBLE: OCCONVERTARRAY(real_8, a, to_type);; break;
  case M2_CX_FLOAT: OCCONVERTCXARRAY(complex_8, a, to_type); break;
  case M2_CX_DOUBLE: OCCONVERTCXARRAY(complex_16, a,to_type); break;
  default: throw MidasException("Array not a POD type");
  }
  a=result; // Install new array
}

#endif //  M2_OC_NUMERIC_TOOLS_H_


text:
#include "config.h"
#include "core/html/HTMLLIElement.h"

#include "core/CSSPropertyNames.h"
#include "core/CSSValueKeywords.h"
#include "core/HTMLNames.h"
#include "core/dom/NodeRenderingTraversal.h"
#include "core/rendering/RenderListItem.h"

namespace blink {

using namespace HTMLNames;

inline HTMLLIElement::HTMLLIElement(Document& document)
    : HTMLElement(liTag, document)
{
}

DEFINE_NODE_FACTORY(HTMLLIElement)

bool HTMLLIElement::isPresentationAttribute(const QualifiedName& name) const
{
    if (name == typeAttr)
        return true;
    return HTMLElement::isPresentationAttribute(name);
}

void HTMLLIElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
    if (name == typeAttr) {
        if (value == "a")
            addPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType, CSSValueLowerAlpha);
        else if (value == "A")
            addPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType, CSSValueUpperAlpha);
        else if (value == "i")
            addPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType, CSSValueLowerRoman);
        else if (value == "I")
            addPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType, CSSValueUpperRoman);
        else if (value == "1")
            addPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType, CSSValueDecimal);
        else
            addPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType, value);
    } else
        HTMLElement::collectStyleForPresentationAttribute(name, value, style);
}

void HTMLLIElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    if (name == valueAttr) {
        if (renderer() && renderer()->isListItem())
            parseValue(value);
    } else
        HTMLElement::parseAttribute(name, value);
}

void HTMLLIElement::attach(const AttachContext& context)
{
    HTMLElement::attach(context);

    if (renderer() && renderer()->isListItem()) {
        RenderListItem* listItemRenderer = toRenderListItem(renderer());

        ASSERT(!document().childNeedsDistributionRecalc());

        // Find the enclosing list node.
        Element* listNode = 0;
        Element* current = this;
        while (!listNode) {
            current = NodeRenderingTraversal::parentElement(*current);
            if (!current)
                break;
            if (isHTMLUListElement(*current) || isHTMLOListElement(*current))
                listNode = current;
        }

        // If we are not in a list, tell the renderer so it can position us inside.
        // We don't want to change our style to say "inside" since that would affect nested nodes.
        if (!listNode)
            listItemRenderer->setNotInList(true);

        parseValue(fastGetAttribute(valueAttr));
    }
}

inline void HTMLLIElement::parseValue(const AtomicString& value)
{
    ASSERT(renderer() && renderer()->isListItem());

    bool valueOK;
    int requestedValue = value.toInt(&valueOK);
    if (valueOK)
        toRenderListItem(renderer())->setExplicitValue(requestedValue);
    else
        toRenderListItem(renderer())->clearExplicitValue();
}

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using Guardtime.KSI.Exceptions;
using Guardtime.KSI.Hashing;
using Guardtime.KSI.Parser;
using NLog;

namespace Guardtime.KSI.Service
{
    /// <summary>
    /// Protocol Data Unit
    /// </summary>
    public abstract class Pdu : CompositeTag
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        int _headerIndex;
        int _macIndex;

        /// <summary>
        /// List on payloads
        /// </summary>
        public List<PduPayload> Payloads { get; } = new List<PduPayload>();

        /// <summary>
        /// Error payload
        /// </summary>
        public ErrorPayload ErrorPayload { get; set; }

        /// <summary>
        ///     Get and set PDU header
        /// </summary>
        public PduHeader Header { get; private set; }

        /// <summary>
        ///     Create PDU from TLV element.
        /// </summary>
        /// <param name="tag">TLV element</param>
        protected Pdu(ITlvTag tag) : base(tag)
        {
        }

        /// <summary>
        /// Parse child tag
        /// </summary>
        protected override ITlvTag ParseChild(ITlvTag childTag)
        {
            foreach (uint tagType in Constants.AllPayloadTypes)
            {
                if (tagType == childTag.Type)
                {
                    return childTag;
                }
            }

            switch (childTag.Type)
            {
                case Constants.PduHeader.TagType:
                    _headerIndex = Count;
                    return Header = childTag as PduHeader ?? new PduHeader(childTag);
                case Constants.Pdu.MacTagType:
                    _macIndex = Count;
                    return Mac = GetImprintTag(childTag);
            }

            return base.ParseChild(childTag);
        }

        /// <summary>
        /// Validate the tag
        /// </summary>
        protected override void Validate(TagCounter tagCounter)
        {
            base.Validate(tagCounter);

            if (ErrorPayload == null)
            {
                if (Payloads.Count == 0)
                {
                    throw new TlvException("Payloads are missing in PDU.");
                }

                if (tagCounter[Constants.PduHeader.TagType] != 1)
                {
                    throw new TlvException("Exactly one header must exist in PDU.");
                }

                if (_headerIndex != 0)
                {
                    throw new TlvException("Header must be the first element in PDU.");
                }

                if (tagCounter[Constants.Pdu.MacTagType] != 1)
                {
                    throw new TlvException("Exactly one MAC must exist in PDU");
                }

                if (_macIndex != Count - 1)
                {
                    throw new TlvException("MAC must be the last element in PDU");
                }
            }
        }

        /// <summary>
        ///     Create aggregation pdu TLV element from KSI header and payload.
        /// </summary>
        /// <param name="tagType">PDU TLV tag type</param>
        /// <param name="header">PDU header</param>
        /// <param name="payload">aggregation payload</param>
        /// <param name="hmacAlgorithm">MAC algorithm</param>
        /// <param name="key">hmac key</param>
        protected Pdu(uint tagType, PduHeader header, PduPayload payload, HashAlgorithm hmacAlgorithm, byte[] key)
            : base(tagType, false, false, new ITlvTag[] { header, payload, GetEmptyMacTag(hmacAlgorithm) })
        {
            SetMacValue(hmacAlgorithm, key);
        }

        /// <summary>
        /// MAC
        /// </summary>
        public ImprintTag Mac { get; private set; }

        /// <summary>
        /// Set MAC tag value
        /// </summary>
        /// <param name="macAlgorithm"></param>
        /// <param name="key">HMAC key</param>
        protected void SetMacValue(HashAlgorithm macAlgorithm, byte[] key)
        {
            for (int i = 0; i < Count; i++)
            {
                ITlvTag childTag = this[i];

                if (childTag.Type == Constants.Pdu.MacTagType)
                {
                    this[i] = Mac = CreateMacTag(CalcMacValue(macAlgorithm, key));
                    break;
                }
            }
        }

        /// <summary>
        ///     Calculate MAC value.
        /// </summary>
        /// <param name="macAlgorithm">MAC algorithm</param>
        /// <param name="key">HMAC key</param>
        private DataHash CalcMacValue(HashAlgorithm macAlgorithm, byte[] key)
        {
            MemoryStream stream = new MemoryStream();
            using (TlvWriter writer = new TlvWriter(stream))
            {
                writer.WriteTag(this);

                return CalcMacValue(stream.ToArray(), macAlgorithm, key);
            }
        }

        /// <summary>
        ///     Calculate MAC value.
        /// </summary>
        /// <param name="pduBytes">PDU encoded as byte array</param>
        /// <param name="macAlgorithm">MAC algorithm</param>
        /// <param name="key">HMAC key</param>
        private static DataHash CalcMacValue(byte[] pduBytes, HashAlgorithm macAlgorithm, byte[] key)
        {
            byte[] target = pduBytes.Length < macAlgorithm.Length ? new byte[0] : new byte[pduBytes.Length - macAlgorithm.Length];
            Array.Copy(pduBytes, 0, target, 0, target.Length);

            IHmacHasher hasher = KsiProvider.CreateHmacHasher(macAlgorithm);
            return hasher.GetHash(key, target);
        }

        /// <summary>
        /// Returns MAC tag containing given data hash value
        /// </summary>
        /// <param name="dataHash">Data hash</param>
        /// <returns></returns>
        private static ImprintTag CreateMacTag(DataHash dataHash)
        {
            return new ImprintTag(Constants.Pdu.MacTagType, false, false, dataHash);
        }

        /// <summary>
        /// Get MAC tag that has hash algorithm set, but hash value is a byte array containing zeros.
        /// </summary>
        /// <param name="macAlgorithm">MAC algorithm</param>
        /// <returns></returns>
        protected static ImprintTag GetEmptyMacTag(HashAlgorithm macAlgorithm)
        {
            if (macAlgorithm == null)
            {
                throw new ArgumentNullException(nameof(macAlgorithm));
            }

            byte[] imprintBytes = new byte[macAlgorithm.Length + 1];
            imprintBytes[0] = macAlgorithm.Id;
            return CreateMacTag(new DataHash(imprintBytes));
        }

        /// <summary>
        ///     Validate PDU against given MAC.
        /// </summary>
        /// <param name="pduBytes">PDU encoded as byte array</param>
        /// <param name="mac">MAC</param>
        /// <param name="key">message key</param>
        /// <returns>true if MAC is valid</returns>
        public static bool ValidateMac(byte[] pduBytes, ImprintTag mac, byte[] key)
        {
            if (pduBytes == null)
            {
                throw new ArgumentNullException(nameof(pduBytes));
            }

            if (mac == null)
            {
                throw new ArgumentNullException(nameof(mac));
            }

            if (pduBytes.Length < mac.Value.Algorithm.Length)
            {
                Logger.Warn("PDU MAC validation failed. PDU bytes array is too short to contain given MAC.");
                return false;
            }

            DataHash calculatedMac = CalcMacValue(pduBytes, mac.Value.Algorithm, key);

            if (!calculatedMac.Equals(mac.Value))
            {
                Logger.Warn("PDU MAC validation failed. Calculated MAC and given MAC do not match.");
                return false;
            }

            return true;
        }
    }
}


text:
seneca-activemq-transport - a [Seneca](http://senecajs.org) plugin
=====================================================================

## Seneca ActiveMQ Transport Plugin

This plugin provides a message transport over [ActiveMQ](http://activemq.apache.org/).

For a gentle introduction to Seneca itself, see the [senecajs.org](http://senecajs.org) site.

This module uses [seneca-stomp-transport](https://www.npmjs.com/package/seneca-stomp-transport) to send messages to ActiveMQ.

Current Version: 0.1.0

Tested on: Seneca 0.5.21, Node 0.10.33, ActiveMQ 5.10.0

## Usage

Check the example directory.

## Acknowledgements

This project was kindly sponsored by the awesome people at
[nearForm](http://nearform.com)


text:
package com.plugin.commons.user;

import org.xinhua.analytics.analytics.AnalyticsAgent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import com.plugin.R;
import com.plugin.commons.ComApp;
import com.plugin.commons.helper.ComUtil;
import com.plugin.commons.helper.DialogUtil;
import com.plugin.commons.helper.FuncUtil;
import com.plugin.commons.helper.SituoHttpAjax;
import com.plugin.commons.helper.SituoHttpAjax.SituoAjaxCallBack;
import com.plugin.commons.helper.XHConstants;
import com.plugin.commons.helper.XHSDKUtil;
import com.plugin.commons.model.RspResultModel;
import com.plugin.commons.service.UserInfoServiceImpl;
import com.plugin.commons.ui.main.MainActivity;
import com.zq.types.StBaseType;

/**
 * @author zhang
 *	重置密码(忘记密码)
 */
public class ForgetPwdSetPwdActivity extends Activity{
	public final static String PARAMS_MOBILE = "mobile";
	public final static String PARAMS_SMSCODE = "smscode";
	EditText et_passwd;
	EditText et_ensure_passwd;
	Button btn_op_finish;
	private UserInfoServiceImpl userService;
	String phone = "";
	String smscode = "";

	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forgetpwd_setpwd);
		ComUtil.customeTitle(this, getResources().getString(R.string.zh_findpwd),true);

		if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(PARAMS_MOBILE)) {
			phone =getIntent().getExtras().getString(PARAMS_MOBILE);
		}
		if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(PARAMS_SMSCODE)) {
			smscode =getIntent().getExtras().getString(PARAMS_SMSCODE);
		}

		initProper();
		ensureUI();
	}

	private void initProper(){
		userService = new UserInfoServiceImpl();
		et_passwd = (EditText)findViewById(R.id.et_passwd);
		et_ensure_passwd = (EditText)findViewById(R.id.et_ensure_passwd);
		btn_op_finish = (Button)findViewById(R.id.btn_op_finish);
		btn_op_finish.setBackgroundResource(ComApp.getInstance().appStyle.btn_sign_selector);
	}

	private void ensureUI(){
		btn_op_finish.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				final String pwd = et_passwd.getText().toString();
				final String enSurePwd = et_ensure_passwd.getText().toString();

				if(FuncUtil.isEmpty(pwd)){
					DialogUtil.showToast(ForgetPwdSetPwdActivity.this, "请输入密码");
					return ;
				}
				if(FuncUtil.isEmpty(enSurePwd)){
					DialogUtil.showToast(ForgetPwdSetPwdActivity.this, "请输入确认密码");
					return ;
				}
				if(!enSurePwd.equals(pwd)){
					DialogUtil.showToast(ForgetPwdSetPwdActivity.this, "请输入两次密码不一致,请确认");
					return ;
				}

				DialogUtil.showProgressDialog(ForgetPwdSetPwdActivity.this);
				SituoHttpAjax.ajax(new SituoAjaxCallBack(){

					@Override
					public StBaseType requestApi() {
						// TODO Auto-generated method stub
						RspResultModel rsp = userService.findpwd(phone, pwd,smscode );
						return rsp;
					}

					@Override
					public void callBack(StBaseType baseType) {
						DialogUtil.closeProgress(ForgetPwdSetPwdActivity.this);
						// TODO Auto-generated method stub
						RspResultModel rsp = (RspResultModel)baseType;
						if(ComUtil.checkRsp(ForgetPwdSetPwdActivity.this, rsp)){
							setResult(RESULT_OK);
							//用户行为采集
							XHSDKUtil.addXHBehavior(ForgetPwdSetPwdActivity.this,phone, XHConstants.XHTOPIC_FINDPWD,phone +" Reset password success");
							Intent intent = new Intent(ForgetPwdSetPwdActivity.this,MainActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);
							finish();
						}
					}

				});
		 	}
			});

		}

	@Override
	public void onResume() {
		super.onResume();
		AnalyticsAgent.onResume(this);//新华sdk
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AnalyticsAgent.onPause(this);//新华sdk
	}
}


text:
<?php
session_start();
$access_type = $_GET['accesstype'];
$path = $_GET['relativepath'];

if($access_type == "F"){
	header("Location: https://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/elFinder-2.x/elfinder.php?folderpath=\\\\enas11\\" . $path . "&TB_iframe=true");
	exit;
}
else if($access_type == "R"){
	$newestfile = "";
	$newesttimestamp = 0;
	foreach (new DirectoryIterator('\\\\enas11\\test') as $fileInfo) {
    	if($fileInfo->isDot()) continue;
		if(($fileInfo->getMTime() > $newesttimestamp) & ($fileInfo->isFile()) & (($fileInfo->getExtension() == "xls") || ($fileInfo->getExtension() == "xlsx") || ($fileInfo->getExtension() == "doc") || ($fileInfo->getExtension() == "docx") || ($fileInfo->getExtension() == "pdf"))){
			$newesttimestamp = $fileInfo->getMTime();
			$newestfile = $fileInfo->getPathName();
		}
    	//echo $fileInfo->getFilename() . " " . $fileInfo->getMTime() . "
\n";
	}
	//echo $newestfile;
	header("Location: https://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/test_link.php?path=" . $newestfile);
}

?>


text:
'use strict'
import * as assert from 'assert';
import * as vscode from 'vscode';
import * as fspath from 'path'

import {FileSystemMock} from './mocks/fileSystemMock'
import {IndexStorageSettings} from '../src/indexing/indexStorageSettings'
import {IndexStorage} from '../src/indexing/indexStorage'
import {Tokenizer} from '../src/indexing/tokenizer'

suite("folder index search", function() {
    this.timeout(3600000)
    let testCount = 10

    let fileSystem: FileSystemMock
    let settings: IndexStorageSettings
    let index: IndexStorage

    setup(done => {
        fileSystem = new FileSystemMock()
        settings = new IndexStorageSettings()
        index = new IndexStorage(fileSystem.rootFolder, fileSystem, settings)
        index.rebuild().then(value => done())
    })

    teardown(() => {
        fileSystem.dispose()
        index.dispose()
    })

    for (let i = 0; i < testCount; i++)
    test(`should return non-empty result (${i})`, () => {
        let randomFile = fileSystem.getFile()
        let randomFilename = fspath.basename(randomFile)

        let result = index.provideWorkspaceSymbols(randomFilename)

        assert.ok(result.length > 0,
            `No result was returned for '${randomFilename}'. FS: ${fileSystem.size}. I: ${index.size}`)
    });

    for (let i = 0; i < testCount; i++)
    test(`should return empty result (${i})`, () => {
        let randomFile = fileSystem.getFile()
        let randomFilename = fspath.basename(randomFile) + "some_stuff"

        let result = index.provideWorkspaceSymbols(randomFilename)

        assert.ok(result.length == 0,
            `Some result was returned: '${result.length > 0 ? result[0].location.uri.fsPath : ""}'. FS: ${fileSystem.size}. I: ${index.size}`)
    });

    for (let i = 0; i < testCount; i++)
    test(`should return item matching exact query (${i}) `, () => {
        let randomFile = fileSystem.getFile()
        let randomFilename = fspath.basename(randomFile)

        let result = index.provideWorkspaceSymbols(randomFilename)

        assert.ok(result.length > 0, `No result was returned for '${randomFilename}'. FS: ${fileSystem.size}. I: ${index.size}`)
        assert.ok(result[0].location.uri.fsPath.toLowerCase() == randomFile.toLowerCase(),
            `Wrong result ${result[0].location.uri.fsPath} was returned for '${randomFilename}'. FS: ${fileSystem.size}. I: ${index.size}`)
    });

    for (let i = 0; i < testCount; i++)
    test(`should return items matching fuzzy query (${i}) `, () => {
        let tokenizer = new Tokenizer()
        let randomFile = fileSystem.getFile()
        let randomFilename = fspath.basename(randomFile)
        let queryParts = tokenizer.getJointTokens(randomFilename).split("|")
        for (let i = 0; i < queryParts.length; i += 2) {
            queryParts = queryParts.splice(i, 1)
        }
        let query = queryParts.join()

        let result = index.provideWorkspaceSymbols(query)

        assert.ok(result.length > 0, `No result was returned for '${randomFilename}'. FS: ${fileSystem.size}. I: ${index.size}`)
        assert.ok(result.filter(s => s.location.uri.fsPath.toLowerCase() == randomFile.toLowerCase()).length > 0,
            `Wrong result was returned for query '${query}' generate for '${randomFilename}'. FS: ${fileSystem.size}. I: ${index.size}`)
    });
});


text:
He optado por la instalacion de la maquina virtual de python dado que tambien trabajamos con este lenguage en la asignatura DAI.

Instalacion:

sudo apt-get install python-pip
pip install virtualenv

Ejecutamos:

<presudo pip virtualenv


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var t = require('tcomb-form-native');
var Form = t.form.Form;

// here we are: define your domain model
var Person = t.struct({
  name: t.Str,              // a required string
  surname: t.maybe(t.Str),  // an optional string
  age: t.Num,               // a required number
  rememberMe: t.Bool        // a boolean
});

var options = {}; // optional rendering options (see documentation)

var tcombExample = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Form
          ref="form"
          type={Person}
          options={options}
        />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('tcombExample', () => tcombExample);


text:
import * as React from 'react'
import { Trans } from "@lingui/react"

// OK - Default message is missing
/*i18n*/i18n._("msg")

// OK - Default message is empty
/*i18n*/i18n._("msg", {}, { message: "" })

// OK - Default message is defined for the first time
(<Trans id="msg" message="Hello World!" />)

// OK - Default message is still empty, so it doesn't overwrite existing one
/*i18n*/i18n._("msg", {}, {
  message: ""
})


text:
layout: post
date: '2016-02-20'
title: "Jasmine Bridal L174058 2015 Fall Sleeveless Floor-Length Aline/Princess"
category: Jasmine
tags: [Jasmine ,Jasmine,Aline/Princess ,Spaghetti Straps,Floor-Length,Sleeveless,2015,Fall]
---
### Jasmine Bridal L174058
Just **$239.99**
### 2015 Fall Sleeveless Floor-Length Aline/Princess

BRANDS	Jasmine

Silhouette	Aline/Princess

Neckline	Spaghetti Straps

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Years	2015

Season	Fall

Buy it: [https://www.readybrides.com/en/jasmine-/19443-jasmine-bridal-l174058.html](https://www.readybrides.com/en/jasmine-/19443-jasmine-bridal-l174058.html)


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <time.h>

#include <nuttx/arch.h>
#include <nuttx/power/pm.h>

#include "up_internal.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Private Data
 ****************************************************************************/

#ifdef CONFIG_SIM_X11FB
static int g_x11refresh = 0;
#endif

/****************************************************************************
 * Public Function Prototypes
 ****************************************************************************/

#if defined(CONFIG_SIM_WALLTIME) || defined(CONFIG_SIM_X11FB)
extern int up_hostusleep(unsigned int usec);
#ifdef CONFIG_SIM_X11FB
extern void up_x11update(void);
#endif
#endif

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: up_idle
 *
 * Description:
 *   up_idle() is the logic that will be executed when their
 *   is no other ready-to-run task.  This is processor idle
 *   time and will continue until some interrupt occurs to
 *   cause a context switch from the idle task.
 *
 *   Processing in this state may be processor-specific. e.g.,
 *   this is where power management operations might be
 *   performed.
 *
 ****************************************************************************/

void up_idle(void)
{
#ifdef CONFIG_SCHED_TICKLESS
  /* Driver the simulated interval timer */

  up_timer_update();
#else
  /* If the system is idle, then process "fake" timer interrupts.
   * Hopefully, something will wake up.
   */

  sched_process_timer();
#endif

#if defined(CONFIG_DEV_CONSOLE) && !defined(CONFIG_SIM_UART_DATAPOST)
  /* Handle UART data availability */

  if (g_uart_data_available)
    {
      g_uart_data_available = 0;
      simuart_post();
    }
#endif

#ifdef CONFIG_NET
  /* Run the network if enabled */

  netdriver_loop();
#endif

#ifdef CONFIG_PM
  /* Fake some power management stuff for testing purposes */

  {
    static enum pm_state_e state = PM_NORMAL;
    enum pm_state_e newstate;

    newstate = pm_checkstate();
    if (newstate != state)
      {
        if (pm_changestate(newstate) == OK)
          {
            state = newstate;
          }
      }
  }
#endif

#if defined(CONFIG_SIM_WALLTIME) || defined(CONFIG_SIM_X11FB)
  /* Wait a bit so that the sched_process_timer() is called close to the
   * correct rate.
   */

  (void)up_hostusleep(1000000 / CLK_TCK);

  /* Handle X11-related events */

#ifdef CONFIG_SIM_X11FB
  if (g_x11initialized)
    {
#if defined(CONFIG_SIM_TOUCHSCREEN) || defined(CONFIG_SIM_AJOYSTICK)
       /* Drive the X11 event loop */

      if (g_eventloop)
        {
          up_x11events();
        }
#endif

      /* Update the display periodically */

      g_x11refresh += 1000000 / CLK_TCK;
      if (g_x11refresh > 500000)
        {
          up_x11update();
        }
    }
#endif
#endif
}


text:
from django.conf.urls import patterns
from django.conf.urls import url

urlpatterns = patterns('',
    url(r'^$', 'ocr.views.index', name='ocr-index'),
)


text:
package de.machmireinebook.epubeditor.javafx.cells;

import javafx.scene.control.TableCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import org.apache.log4j.Logger;

/**
 * User: mjungierek
 * Date: 19.11.13
 * Time: 21:20
 */
public class ImageCell<S> extends TableCell<S, Image>
{
    private static final Logger logger = Logger.getLogger(ImageCell.class);

    private Double width;
    private Double height;

    public ImageCell(Double width, Double height)
    {
        this.width = width;
        this.height = height;
    }

    @Override
    public void updateItem(Image item, boolean empty)
    {
        getStyleClass().add("center");
        ImageView imageview = new ImageView();
        if (height != null)
        {
            imageview.setFitHeight(height);
        }
        else
        {
            imageview.setPreserveRatio(true);
        }
        if (width != null)
        {
            imageview.setFitWidth(width);
        }
        else
        {
            imageview.setPreserveRatio(true);
        }
        imageview.setImage(item);

        super.updateItem(item, false);
        setText(null);
        setGraphic(empty ? null : imageview);
    }
}


text:
(function() {
    'use strict'

    angular.module('formobject')
        .directive('foFieldTypeselect', Directive);

    function Directive() {
        return {
            restrict: 'E',
            templateUrl: 'formobject/fo-field-typeselect.tpl.html',
            replace: true,
            controller: 'NgFieldTypeCtrl as typeCtrl'
        }
    }
})();


text:
package org.apache.syncope.client.enduser.panels;

import org.apache.syncope.client.ui.commons.BaseSession;
import org.apache.syncope.client.ui.commons.panels.AbstractOIDCSSOLoginFormPanel;

public class OIDCSSOLoginFormPanel extends AbstractOIDCSSOLoginFormPanel {

    private static final long serialVersionUID = 1154933731474854671L;

    public OIDCSSOLoginFormPanel(final String id, final BaseSession session) {
        super(id, session);
    }
}


text:
from __future__ import absolute_import

import six

from sentry.testutils import APITestCase, SnubaTestCase
from sentry.testutils.helpers.datetime import before_now, iso_format

class GroupEventsLatestEndpointTest(APITestCase, SnubaTestCase):
    def setUp(self):
        super(GroupEventsLatestEndpointTest, self).setUp()

        self.login_as(user=self.user)
        project = self.create_project()

        self.event_a = self.store_event(
            data={
                "event_id": "a" * 32,
                "environment": "development",
                "timestamp": iso_format(before_now(days=1)),
                "fingerprint": ["group-1"],
            },
            project_id=project.id,
        )
        self.event_b = self.store_event(
            data={
                "event_id": "b" * 32,
                "environment": "production",
                "timestamp": iso_format(before_now(minutes=5)),
                "fingerprint": ["group-1"],
            },
            project_id=project.id,
        )
        self.event_c = self.store_event(
            data={
                "event_id": "c" * 32,
                "environment": "staging",
                "timestamp": iso_format(before_now(minutes=1)),
                "fingerprint": ["group-1"],
            },
            project_id=project.id,
        )

    def test_get_simple(self):
        url = u"/api/0/issues/{}/events/latest/".format(self.event_a.group.id)
        response = self.client.get(url, format="json")

        assert response.status_code == 200, response.content
        assert response.data["id"] == six.text_type(self.event_c.event_id)
        assert response.data["previousEventID"] == six.text_type(self.event_b.event_id)
        assert response.data["nextEventID"] is None

    def test_get_with_environment(self):
        url = u"/api/0/issues/{}/events/latest/".format(self.event_a.group.id)
        response = self.client.get(url, format="json", data={"environment": ["production"]})

        assert response.status_code == 200, response.content
        assert response.data["id"] == six.text_type(self.event_b.event_id)
        assert response.data["previousEventID"] is None
        assert response.data["nextEventID"] is None


text:
package com.google.bitcoin.tools;

import com.google.bitcoin.core.*;
import com.google.bitcoin.params.MainNetParams;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.MemoryBlockStore;
import com.google.bitcoin.utils.BriefLogFormatter;
import com.google.bitcoin.utils.Threading;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.Date;
import java.util.TreeMap;

import static com.google.common.base.Preconditions.checkState;

/**
 * Downloads and verifies a full chain from your local peer, emitting checkpoints at each difficulty transition period
 * to a file which is then signed with your key.
 */
public class BuildCheckpoints {
    public static void main(String[] args) throws Exception {
        BriefLogFormatter.init();
        final NetworkParameters params = MainNetParams.get();

        // Sorted map of UNIX time of block to StoredBlock object.
        final TreeMap<Integer, StoredBlock> checkpoints = new TreeMap<Integer, StoredBlock>();

        // Configure bitcoinj to fetch only headers, not save them to disk, connect to a local fully synced/validated
        // node and to save block headers that are on interval boundaries, as long as they are <1 month old.
        final BlockStore store = new MemoryBlockStore(params);
        final BlockChain chain = new BlockChain(params, store);
        final PeerGroup peerGroup = new PeerGroup(params, chain);

        //peerGroup.addAddress(/*InetAddress.getLocalHost()*/InetAddress.getByName("ca1.miningpool.co"));
        peerGroup.addAddress(InetAddress.getLocalHost());
        long now = new Date().getTime() / 1000;
        peerGroup.setFastCatchupTimeSecs(now);

        final long oneMonthAgo = now - (86400);//(86400 * 30);  //1 day ago

        chain.addListener(new AbstractBlockChainListener() {
            @Override
            public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
                int height = block.getHeight();
                if (height % CoinDefinition.getIntervalForCheckpoints(height, false) == 0 &&
                        block.getHeader().getTimeSeconds() <= oneMonthAgo /*&&
                        block.getHeight() < CoinDefinition.nDifficultySwitchHeightTwo - 4033*/) {
                    System.out.println(String.format("Checkpointing block %s at height %d: diff %08x",
                            block.getHeader().getHash(), block.getHeight(), block.getHeader().getDifficultyTarget()));
                    checkpoints.put(height, block);
                }
            }
        }, Threading.SAME_THREAD);

        peerGroup.startAndWait();
        peerGroup.downloadBlockChain();

        checkState(checkpoints.size() > 0);

        // Write checkpoint data out.
        final FileOutputStream fileOutputStream = new FileOutputStream("checkpoints", false);
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest);
        digestOutputStream.on(false);
        final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream);
        dataOutputStream.writeBytes("CHECKPOINTS 1");
        dataOutputStream.writeInt(0);  // Number of signatures to read. Do this later.
        digestOutputStream.on(true);
        dataOutputStream.writeInt(checkpoints.size());
        ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
        int i = 0;
        for (StoredBlock block : checkpoints.values()) {
            block.serializeCompact(buffer);
            dataOutputStream.write(buffer.array());
            buffer.position(0);
            ++i;
            System.out.println("writing checkpoint... " + i);
        }
        dataOutputStream.close();
        Sha256Hash checkpointsHash = new Sha256Hash(digest.digest());
        System.out.println("Hash of checkpoints data is " + checkpointsHash);
        digestOutputStream.close();
        fileOutputStream.close();

        peerGroup.stopAndWait();
        store.close();

        // Sanity check the created file.
        CheckpointManager manager = new CheckpointManager(params, new FileInputStream("checkpoints"));
        checkState(manager.numCheckpoints() == checkpoints.size());
        //StoredBlock test = manager.getCheckpointBefore(1395777062);  // Just after block 65,000
        //checkState(test.getHeight() == 34000);
        //checkState(test.getHeader().getHashAsString().equals("9b7ecc4ea9b413cce66b1f7b37b2e86ea716ee6781be4fe87fc64dde5bd19551"));
    }
}


text:
<?php
/**
 * @author Patsura Dmitry <zaets28rus@gmail.com>
 */

namespace User;

class Module
{
    public function registerAutoloaders()
    {
        $loader = new \Phalcon\Loader();
        $loader->registerNamespaces(array(
            'User\Controller' => APPLICATION_PATH . '/modules/frontend/controllers/',
            'User\Model' => APPLICATION_PATH . '/modules/frontend/models/',
        ));
        $loader->register();
    }

    public function registerServices($di)
    {
        $dispatcher = $di->get('dispatcher');
        $dispatcher->setDefaultNamespace('User\Controller');

        $eventsManager = $di->get('eventsManager');

        $eventsManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) {
            /**
             * @todo and move it to global
             */
        });
        $dispatcher->setEventsManager($eventsManager);
        $di->set('dispatcher', $dispatcher);

        /**
         * @var \Phalcon\Mvc\View
         */
        $view = $di->get('view');
        $view->setLayout('index');
        $view->setViewsDir(APPLICATION_PATH . '/modules/frontend/views/');
        $view->setLayoutsDir('../../common/layouts/');

        $di->set('view', $view);
    }
}


text:
$(function(){
	$( 'textarea.texteditor' ).ckeditor({toolbar:'Full',
    filebrowserBrowseUrl:'/js/ckfinder/ckfinder.html',
filebrowserImageBrowseUrl:'/js/ckfinder/ckfinder.html?Type=Images',
filebrowserImageUploadUrl:'/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images'
    });
	$( 'textarea.mini-texteditor' ).ckeditor({toolbar:'Basic',width:700});
});


text:
<?php

$chat = erLhcoreClassChat::getSession()->load( 'erLhcoreClassModelChat', $Params['user_parameters']['chat_id']);

if ( erLhcoreClassChat::hasAccessToRead($chat) && $currentUser->hasAccessTo('lhfile','use_operator') === true )
{
	$fileData = erLhcoreClassModelChatConfig::fetch('file_configuration');
	$data = (array)$fileData->data;

	$userData = $currentUser->getUserData();

	$path = 'var/storage/'.date('Y').'y/'.date('m').'/'.date('d').'/'.$chat->id.'/';

	erLhcoreClassChatEventDispatcher::getInstance()->dispatch('file.uploadfileadmin.file_path',array('path' => & $path, 'storage_id' => $chat->id));

	$upload_handler = new erLhcoreClassFileUpload(array('name_support' => $userData->name_support, 'user_id' => $currentUser->getUserID(), 'max_file_size' => $data['fs_max']*1024, 'accept_file_types_lhc' => '/\.('.$data['ft_op'].')$/i','chat' => $chat, 'download_via_php' => true, 'upload_dir' => $path));

	if ($upload_handler->uploadedFile instanceof erLhcoreClassModelChatFile)
	{
		erLhcoreClassChatEventDispatcher::getInstance()->dispatch('file.uploadfileadmin.file_store', array('chat_file' => $upload_handler->uploadedFile));
	}

	echo json_encode(array('error' => 'false'));
}

exit;

?>


text:
package org.apache.druid.client;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;

import java.io.InputStream;

public class InputStreamHolder
{
  private final InputStream stream;
  private final long chunkNum;
  private final long length;

  public InputStreamHolder(final InputStream stream, final long chunkNum, final long length)
  {
    this.stream = stream;
    this.chunkNum = chunkNum;
    this.length = length;
  }

  public static InputStreamHolder fromStream(final InputStream stream, final long chunkNum, final long length)
  {
    return new InputStreamHolder(stream, chunkNum, length);
  }

  public static InputStreamHolder fromChannelBuffer(final ChannelBuffer buffer, final long chunkNum)
  {
    final int length = buffer.readableBytes();
    return new InputStreamHolder(new ChannelBufferInputStream(buffer), chunkNum, length);
  }

  public InputStream getStream()
  {
    return stream;
  }

  public long getChunkNum()
  {
    return chunkNum;
  }

  public long getLength()
  {
    return length;
  }
}


text:
using System.Collections.Generic;
using JetBrains.Annotations;
using Txt.Core;

namespace Txt.ABNF.Core.LF
{
    public class LineFeed : Element
    {
        public LineFeed([NotNull] Element element)
            : base(element)
        {
        }

        public LineFeed([NotNull] string terminals, [NotNull] ITextContext context)
            : base(terminals, context)
        {
        }

        public LineFeed([NotNull] string sequence, [NotNull] IList<Element> elements, [NotNull] ITextContext context)
            : base(sequence, elements, context)
        {
        }
    }
}


text:
using namespace Oasis;

class MeshUtil
{
public:
    static Mesh* CreateCube();
};


text:
var User = require('../models/userModel');
var Role = require('../models/roleModel');
//var UserRole = require('../models/userRole');
var Permission = require('../models/permissionModel');
var Resource = require('../models/resourceModel');
//var UserPolicy = require('../models/userPolicy');
var NotFoundError = require('../exceptions/notFoundError');
var handleError = require('../utils/handleJsonResponse').Error;
var handleSuccess = require('../utils/handleJsonResponse').Success;

//Create an user
var addUser = function(req, res) {
  var username = req.body.username;
  var password = req.body.password;
  var email = req.body.email;
  var firstName = req.body.firstName;
  var lastName = req.body.lastName;

  var user = new User({
    username: username,
    password: password,
    email: email,
    firstName: firstName,
    lastName: lastName
  });

  user.save()
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Get an user by id
var getUser = function(req, res) {
  var userId = req.params.user;

  if (userId) {
    User.forge()
    .where({
      id: userId
    })
    .fetch()
    .then(function(ret) {
      handleSuccess(res, ret);
    })
    .catch(function(err) {
      handleError(res, err);
    });
  }
  else {
    return getUsers(req, res);
  }
}

//Get all users
var getUsers = function(req, res) {
  User.collection()
  .fetch()
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Delete an user by id
var delUser = function(req, res) {
  var userId = req.params.user;

  if (userId) {
    User.remove({
      id: userId
    })
    .then(function(ret) {
      handleSuccess(res, ret);
    })
    .catch(function(err) {
      handleError(res, err);
    });
  }
}

//Add a role to an user
var addUserRole = function(req, res) {
  var userId = req.params.user;
  var idRole = req.body.role;
  var main = req.body.main;
  var expiration = req.body.expiration;
  var description = req.body.description;

  var userRole = new UserRole({
    _user: userId,
    _role: idRole,
    main: main,
    expiration: expiration,
    description: description
  });

  userRole.saveAsync()
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Remove a role by id associated to an user
var delUserRole = function(req, res) {
  var userId = req.params.user;
  var idRole = req.params.role;

  if (idRole) {
    UserRole.removeAsync({
      _user: userId,
      _role: idRole
    })
    .then(function(ret) {
      handleSuccess(res, ret);
    })
    .catch(function(err) {
      handleError(res, err);
    });
  }
  else {
    return delUserRoles(req, res);
  }
}

//Remove all roles associated to an user
var delUserRoles = function(req, res) {
  var userId = req.params.user;

  UserRole.removeAsync({
    _user: userId
  })
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Get a role by id associated to an user
var getUserRole = function(req, res) {
  var userId = req.params.user;
  var idRole = req.params.role;

  if (idRole) {
    UserRole.findOne({
      _user: userId,
      _role: idRole,
    })
    .populate('_role')
    .then(function(ret) {
      handleSuccess(res, ret);
    })
    .catch(function(err) {
      handleError(res, err);
    });
  }
  else {
    return getUserRoles(req, res);
  }
}

//Get all roles associated to an user
var getUserRoles = function(req, res) {
  var userId = req.params.user;

  UserRole.find({
    _user: userId
  })
  .populate('_role')
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Add a policy to an user
var addUserPolicy = function(req, res) {
  var userId = req.params.user;
  var idRes = req.body.resource;
  var idPerm = req.body.permission;
  var description = req.body.description;
  var expiration = req.body.expiration;

  var userPolicy = new UserPolicy({
    _user: userId,
    _resource: idRes,
    _permission: idPerm,
    description: description,
    expiration: expiration
  });

  userPolicy.saveAsync()
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Remove a policy by id associated to an user
var delUserPolicy = function(req, res) {
  var userId = req.params.user;
  var idRes = req.params.resource;
  var idPerm = req.params.permission;

  if (idRes == 'all') {
    idRes = null;
  }

  if (idRes && idPerm) {
    UserPolicy.removeAsync({
      _user: userId,
      _resource: idRes,
      _permission: idPerm
    })
    .then(function(ret) {
      handleSuccess(res, ret);
    })
    .catch(function(err) {
      handleError(res, err);
    });
  }
  else if (idRes && !idPerm) {
    return delUserResources(req, res);
  }
  else if (!idRes && idPerm) {
    return delUserPermissions(req, res);
  }
  else {
    return delUserPolicies(req, res);
  }
}

//Remove all policies associated to an user
var delUserPolicies = function(req, res) {
  var userId = req.params.user;

  UserPolicy.removeAsync({
    _user: userId
  })
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Remove all resources associated to an user
var delUserResources = function(req, res) {
  var userId = req.params.user;
  var idRes = req.params.resource;

  UserPolicy.removeAsync({
    _user: userId,
    _resource: idRes
  })
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Remove all permissions associated to an user
var delUserPermissions = function(req, res) {
  var userId = req.params.user;
  var idPerm = req.params.permission;

  UserPolicy.removeAsync({
    _user: userId,
    _permission: idPerm
  })
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Get a policy by id associated to an user
var getUserPolicy = function(req, res) {
  var userId = req.params.user;
  var idRes = req.params.resource;
  var idPerm = req.params.permission;

  if (idRes == 'all') {
    idRes = null;
  }

  if (idRes && idPerm) {
    UserPolicy.findOne({
      _user: userId,
      _resource: idRes,
      _permission: idPerm
    })
    .populate(['_resource', '_permission'])
    .then(function(ret) {
      handleSuccess(res, ret);
    })
    .catch(function(err) {
      handleError(res, err);
    });
  }
  else if (idRes && !idPerm) {
    return getUserResources(req, res);
  }
  else if (!idRes && idPerm) {
    return getUserPermissions(req, res);
  }
  else {
    return getUserPolicies(req, res);
  }
}

//Get all policies associated to an user
var getUserPolicies = function(req, res) {
  var userId = req.params.user;

  UserPolicy.find({
    _user: userId
  })
  .populate(['_resource', '_permission'])
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Get all resources associated to an user
var getUserResources = function(req, res) {
  var userId = req.params.user;
  var idRes = req.params.resource;

  UserPolicy.find({
    _user: userId,
    _resource: idRes
  })
  .populate(['_resource', '_permission'])
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

//Get all permissions associated to an user
var getUserPermissions = function(req, res) {
  var userId = req.params.user;
  var idPerm = req.params.permission;

  UserPolicy.find({
    _user: userId,
    _permission: idPerm
  })
  .populate(['_resource', '_permission'])
  .then(function(ret) {
    handleSuccess(res, ret);
  })
  .catch(function(err) {
    handleError(res, err);
  });
}

exports.createUser = addUser;
exports.deleteUser = delUser;
exports.getUser = getUser;
exports.addUserRole = addUserRole;
exports.removeUserRole = delUserRole;
exports.getUserRole = getUserRole;
exports.addUserPolicy = addUserPolicy;
exports.removeUserPolicy = delUserPolicy;
exports.getUserPolicy = getUserPolicy;


text:
#ifndef H264STREAMSTATS_H_
#define H264STREAMSTATS_H_

#include <boost/utility.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <list>
#include "types.hpp"

namespace H264 {

struct h264_layer {

	h264_layer() {

		temporal_id = -1;
		dependency_id = -1;
		quality_id = -1;

		numb_of_bytes = 0;
		numb_of_nals = 0;
	};

	int32_t temporal_id;
	int32_t dependency_id;
	int32_t quality_id;

	int32_t numb_of_bytes;
	int32_t numb_of_nals;

	h264_layer& operator=(nal_short_info& nal) {
		temporal_id = nal.temporal_id;
		dependency_id = nal.dependency_id;
		quality_id = nal.quality_id;

		return *this;
	}

	bool operator==(h264_layer& lay) {

		if (this->dependency_id == lay.dependency_id &&
			this->temporal_id == lay.temporal_id &&
			this->quality_id == lay.quality_id)
			return true;
		else
			return false;
	}

	bool operator==(nal_short_info& nal) {

		if (this->dependency_id == nal.dependency_id &&
			this->temporal_id == nal.temporal_id &&
			this->quality_id == nal.quality_id)
					return true;
				else
					return false;
	}
};

class h264StreamStats
	: boost::noncopyable {
public:

	typedef boost::shared_ptr<h264StreamStats> ptr;

	h264StreamStats();
	virtual ~h264StreamStats();

	h264StreamStats& operator<<(nal_short_info info);

	bool save(std::string sFile);
	bool load(std::string sFile);

	void reset();

//private:
	int64_t m_iBytesTotal;
	int32_t m_iNumbOfNals;
	int32_t m_iNumbOfParsingErrors;
	int32_t m_iNumbOfFrames;

	int32_t m_iLastFrameNr;
	int32_t m_iHighestFrameNr;

	std::list<h264_layer> m_layers;
	int32_t m_last_layer[3];
};

}

#endif /* H264STREAMSTATS_H_ */