text:
@implementation SKScrollPageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        mNeedUseDelegate = YES;
        [self commInit];
    }
    return self;
}

-(void)initData{
    [self freshContentTableAtIndex:0];
}

- (void)commInit
{
    if (_contentItems == nil) {
        _contentItems = [[NSMutableArray alloc] init];
    }

    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _scrollView.pagingEnabled = YES;
        _scrollView.bounces = NO; // 重要属性,去除scrollView空间的弹跳
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
        _scrollView.delegate = self;
    }

    [self addSubview:_scrollView];
}

#pragma mark -辅助函数
#pragma mark 添加ScrollView的ContentView
- (void)setContentOfTables:(NSInteger)aNumberOfTables
{
    for (int i = 0; i < aNumberOfTables; i++) {
        SKCustomTableView *vCustomTableView = [[SKCustomTableView alloc] initWithFrame:CGRectMake(320 * i, 0, 320, self.frame.size.height)];
        vCustomTableView.delegate = self;
        vCustomTableView.dataSource = self;
        vCustomTableView.tag = i + 1;
        [_scrollView addSubview:vCustomTableView];
        [_contentItems addObject:vCustomTableView];
    }
    [_scrollView setContentSize:CGSizeMake(320 * aNumberOfTables, self.frame.size.height)];
}

#pragma mark 移动ScrollView到某个页面
- (void)moveScrollViewAtIndex:(NSInteger)aIndex
{
    mNeedUseDelegate = NO;
    [_scrollView setContentOffset:CGPointMake(self.frame.size.width *aIndex, 0) animated:YES];
    mCurrentPage = aIndex;
    if ([_delegate respondsToSelector:@selector(didScrollPageViewChangedPage:)]) {
        [_delegate didScrollPageViewChangedPage:mCurrentPage];
    }

}

#pragma mark 刷新某个页面
- (void)freshContentTableAtIndex:(NSInteger)aIndex
{
    if (_contentItems.count < aIndex) {
        return;
    }

    SKCustomTableView *vTableContentView = (SKCustomTableView *)[_contentItems objectAtIndex:aIndex];
    [vTableContentView forceToFreshData:aIndex];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    mNeedUseDelegate = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 滚动Tab动画
    if ([_delegate respondsToSelector:@selector(scrollPageViewCurrentOffset:)]) {
        [_delegate scrollPageViewCurrentOffset:_scrollView.contentOffset.x];
    }

    int page = (_scrollView.contentOffset.x + 320/2.0) / 320;

    if (mCurrentPage == page) {
        return;
    }
    mCurrentPage = page;
    if ([_delegate respondsToSelector:@selector(didScrollPageViewChangedPage:)] && mNeedUseDelegate) {
        [_delegate didScrollPageViewChangedPage:mCurrentPage];
    }

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate) {

    }
}

- (void)didTableViewCellClickedButton:(UIButton *)button
{

    SKHomeViewCell *vCell = (SKHomeViewCell*)button.superview.superview.superview;

    NSURL *url = [NSURL URLWithString: [vCell.cellInfo objectForKey:@"url"]];

    TOWebViewController *webViewController = [[TOWebViewController alloc] initWithURL:url];

    [vCell.controller pushViewController:webViewController animated:YES];

}

// build每一个cell的UI
- (void)buildCellUI:(SKHomeViewCell *)cell fromData:(NSDictionary *)data
{

    NSString *gameName = [data objectForKey:@"name"];

    cell.gameNameLabel.text = gameName;
    [cell.headerImageView sd_setImageWithURL:[NSURL URLWithString:[data objectForKey:@"icon"]] placeholderImage:[UIImage imageNamed:@"placeholder"]];

}

#pragma mark - CustomTableViewDataSource
- (NSInteger)numberOfRowsInTableView:(UITableView *)aTableView Insection:(NSInteger)section FromView:(SKCustomTableView *)aView
{
    return aView.tableInfoArray.count;
}

- (UITableViewCell *)cellForRowInTableView:(UITableView *)aTableView IndexPath:(NSIndexPath *)aIndexPath FromView:(SKCustomTableView *)aView
{
    static NSString *vCellIdentify = @"homeCell";
    SKHomeViewCell *vCell = [aTableView dequeueReusableCellWithIdentifier:vCellIdentify];
    NSDictionary *responseInfo = [aView.tableInfoArray objectAtIndex:aIndexPath.row];
    if (vCell == nil) {
        vCell = [[[NSBundle mainBundle] loadNibNamed:@"SKHomeViewCell" owner:self options:nil] lastObject];

        NSString *gameDownLoad = [responseInfo objectForKey:@"downloads"];
        RTLabel *downloadLabel = [[RTLabel alloc] initWithFrame:CGRectMake(88, 64, 142, 20)];
        downloadLabel.lineSpacing = 20.0;
        [downloadLabel setText: [NSString stringWithFormat:@"已有%@人在玩", gameDownLoad]];

        [vCell addSubview:downloadLabel];

        AMRatingControl *colorRatingControl = [[AMRatingControl alloc] initWithLocation:CGPointMake(88, 42) emptyColor:[UIColor clearColor] solidColor:[UIColor redColor] andMaxRating:5];
        [colorRatingControl setStarFontSize:12];
        [colorRatingControl setUserInteractionEnabled:NO];
        [colorRatingControl setStarWidthAndHeight:15];
        [colorRatingControl setRating: ([[responseInfo objectForKey:@"score"] intValue]/2)];

        [vCell addSubview: colorRatingControl];
    }

    [self buildCellUI: vCell fromData: responseInfo];
    vCell.cellButton.tag = aIndexPath.row;
    vCell.delegate = self;
    vCell.cellInfo = responseInfo;
    vCell.controller =  (UINavigationController *)self.superview.window.rootViewController; // 比较纠结的指针引用方式,待重构

    return vCell;
}

#pragma mark CustomTableViewDelegate
- (float)heightForRowAtIndexPath:(UITableView *)aTableView IndexPath:(NSIndexPath *)aIndexPath FromView:(SKCustomTableView *)aView
{
    SKHomeViewCell *vCell = [[[NSBundle mainBundle] loadNibNamed:@"SKHomeViewCell" owner:self options:nil] lastObject];
    return vCell.frame.size.height;
}

- (void)didSelectedRowAtIndexPath:(UITableView *)aTableView IndexPath:(NSIndexPath *)aIndexPath FromView:(SKCustomTableView *)aView
{
    SKHomeViewCell *vCell = (SKHomeViewCell *)[aTableView cellForRowAtIndexPath:aIndexPath];

    SKDetailViewController *detailController = [[SKDetailViewController alloc] init];
    detailController.currentGameInfo = vCell.cellInfo;
    detailController.gameInfo = aView.tableInfoArray;

    [vCell.controller pushViewController:detailController animated:YES];
}

- (BOOL)tableViewEgoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view FromView:(SKCustomTableView *)aView{
    return  aView.reloading;
}

@end


text:
package javax.sip.header;

public interface MinExpiresHeader extends ExpiresHeader {
    String NAME = "Min-Expires";
}

redpajama_set_name: RedPajamaGithub


text:
import marksystem.db
import marksystem.util
from marksystem.logger import Logger
from marksystem.web import StartWeb

marksystem.logger.GlobalLogger = Logger("./log/mark.log", True)

try:
	marksystem.logger.GlobalLogger.log().info("Starting System etc.!")
	StartWeb(True)
finally:
	pass
#	marksystem.logger.GlobalLogger.Close()


text:
package org.jivesoftware.smackx.geolocation;

import java.net.URI;
import java.util.concurrent.TimeoutException;

import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.NotLoggedInException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;

import org.jivesoftware.smackx.disco.EntityCapabilitiesChangedListener;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.geoloc.GeoLocationManager;
import org.jivesoftware.smackx.geoloc.packet.GeoLocation;
import org.jivesoftware.smackx.pep.PepEventListener;

import org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest;
import org.igniterealtime.smack.inttest.SmackIntegrationTestEnvironment;
import org.igniterealtime.smack.inttest.annotations.AfterClass;
import org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest;
import org.igniterealtime.smack.inttest.util.IntegrationTestRosterUtil;
import org.igniterealtime.smack.inttest.util.SimpleResultSyncPoint;
import org.junit.jupiter.api.Assertions;
import org.jxmpp.util.XmppDateTime;

public class GeolocationIntegrationTest extends AbstractSmackIntegrationTest {

    private final GeoLocationManager glm1;
    private final GeoLocationManager glm2;

    public GeolocationIntegrationTest(SmackIntegrationTestEnvironment environment) {
        super(environment);
        glm1 = GeoLocationManager.getInstanceFor(conOne);
        glm2 = GeoLocationManager.getInstanceFor(conTwo);
    }

    @AfterClass
    public void unsubscribe() throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
        IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);
    }

    /**
     * Verifies that a notification is sent when a publication is received, assuming that notification filtering
     * has been adjusted to allow for the notification to be delivered.
     *
     * @throws Exception if the test fails
     */
    @SmackIntegrationTest
    public void testNotification() throws Exception {
        GeoLocation.Builder builder = GeoLocation.builder();
        GeoLocation data = builder.setAccuracy(23d)
                                            .setAlt(1000d)
                                            .setAltAccuracy(10d)
                                            .setArea("Delhi")
                                            .setBearing(10d)
                                            .setBuilding("Small Building")
                                            .setCountry("India")
                                            .setCountryCode("IN")
                                            .setDescription("My Description")
                                            .setFloor("top")
                                            .setLat(25.098345d)
                                            .setLocality("awesome")
                                            .setLon(77.992034)
                                            .setPostalcode("110085")
                                            .setRegion("North")
                                            .setRoom("small")
                                            .setSpeed(250.0d)
                                            .setStreet("Wall Street")
                                            .setText("Unit Testing GeoLocation")
                                            .setTimestamp(XmppDateTime.parseDate("2004-02-19"))
                                            .setTzo("+5:30")
                                            .setUri(new URI("http://xmpp.org"))
                                            .build();

        IntegrationTestRosterUtil.ensureBothAccountsAreSubscribedToEachOther(conOne, conTwo, timeout);

        final SimpleResultSyncPoint geoLocationReceived = new SimpleResultSyncPoint();

        final PepEventListener<GeoLocation> geoLocationListener = (jid, geoLocation, id, message) -> {
            if (geoLocation.equals(data)) {
                geoLocationReceived.signal();
            }
        };

        try {
            // Register ConTwo's interest in receiving geolocation notifications, and wait for that interest to have been propagated.
            registerListenerAndWait(glm2, ServiceDiscoveryManager.getInstanceFor(conTwo), geoLocationListener);

            // Publish the data.
            glm1.publishGeoLocation(data); // for the purpose of this test, this needs not be blocking/use publishAndWait();

            // Wait for the data to be received.
            try {
                Object result = geoLocationReceived.waitForResult(timeout);

                // Explicitly assert the success case.
                Assertions.assertNotNull(result, "Expected to receive a PEP notification, but did not.");
            } catch (TimeoutException e) {
                Assertions.fail("Expected to receive a PEP notification, but did not.");
            }
        } finally {
            unregisterListener(glm2, geoLocationListener);
        }
    }

    /**
     * Verifies that a notification for a previously sent publication is received as soon as notification filtering
     * has been adjusted to allow for the notification to be delivered.
     *
     * @throws Exception if the test fails
     */
    @SmackIntegrationTest
    public void testNotificationAfterFilterChange() throws Exception {
        GeoLocation.Builder builder = GeoLocation.builder();
        GeoLocation data = builder.setAccuracy(12d)
                .setAlt(999d)
                .setAltAccuracy(9d)
                .setArea("Amsterdam")
                .setBearing(9d)
                .setBuilding("Test Building")
                .setCountry("Netherlands")
                .setCountryCode("NL")
                .setDescription("My Description")
                .setFloor("middle")
                .setLat(25.098345d)
                .setLocality("brilliant")
                .setLon(77.992034)
                .setPostalcode("110085")
                .setRegion("North")
                .setRoom("small")
                .setSpeed(250.0d)
                .setStreet("Wall Street")
                .setText("Unit Testing GeoLocation 2")
                .setTimestamp(XmppDateTime.parseDate("2007-02-19"))
                .setTzo("+5:30")
                .setUri(new URI("http://xmpp.org"))
                .build();

        IntegrationTestRosterUtil.ensureBothAccountsAreSubscribedToEachOther(conOne, conTwo, timeout);

        final SimpleResultSyncPoint geoLocationReceived = new SimpleResultSyncPoint();

        final PepEventListener<GeoLocation> geoLocationListener = (jid, geoLocation, id, message) -> {
            if (geoLocation.equals(data)) {
                geoLocationReceived.signal();
            }
        };

        // TODO Ensure that pre-existing filtering notification excludes geolocation.
        try {
            // Publish the data
            publishAndWait(glm1, ServiceDiscoveryManager.getInstanceFor(conOne), data);

            // Adds listener, which implicitly publishes a disco/info filter for geolocation notification.
            registerListenerAndWait(glm2, ServiceDiscoveryManager.getInstanceFor(conTwo), geoLocationListener);

            // Wait for the data to be received.
            try {
                Object result = geoLocationReceived.waitForResult(timeout);

                // Explicitly assert the success case.
                Assertions.assertNotNull(result, "Expected to receive a PEP notification, but did not.");
            } catch (TimeoutException e) {
                Assertions.fail("Expected to receive a PEP notification, but did not.");
            }
        } finally {
            unregisterListener(glm2, geoLocationListener);
        }
    }

    /**
     * Registers a listener for GeoLocation data. This implicitly publishes a CAPS update to include a notification
     * filter for the geolocation node. This method blocks until the server has indicated that this update has been
     * received.
     *
     * @param geoManager The GeoLocationManager instance for the connection that is expected to receive data.
     * @param discoManager The ServiceDiscoveryManager instance for the connection that is expected to publish data.
     * @param listener A listener instance for GeoLocation data that is to be registered.
     *
     * @throws Exception if the test fails
     */
    public void registerListenerAndWait(GeoLocationManager geoManager, ServiceDiscoveryManager discoManager, PepEventListener<GeoLocation> listener) throws Exception {
        final SimpleResultSyncPoint notificationFilterReceived = new SimpleResultSyncPoint();
        final EntityCapabilitiesChangedListener notificationFilterReceivedListener = info -> {
            if (info.containsFeature(GeoLocationManager.GEOLOCATION_NODE + "+notify")) {
                notificationFilterReceived.signal();
            }
        };

        discoManager.addEntityCapabilitiesChangedListener(notificationFilterReceivedListener);
        try {
            geoManager.addGeoLocationListener(listener);
            notificationFilterReceived.waitForResult(timeout);
        } finally {
            discoManager.removeEntityCapabilitiesChangedListener(notificationFilterReceivedListener);
        }
    }

    /**
     * The functionally reverse of {@link #registerListenerAndWait(GeoLocationManager, ServiceDiscoveryManager, PepEventListener)}
     * with the difference of not being a blocking operation.
     *
     * @param geoManager The GeoLocationManager instance for the connection that was expected to receive data.
     * @param listener A listener instance for GeoLocation data that is to be removed.
     */
    public void unregisterListener(GeoLocationManager geoManager, PepEventListener<GeoLocation> listener) {
        // Does it make sense to have a method implementation that's one line? This is provided to allow for symmetry in the API.
        geoManager.removeGeoLocationListener(listener);
    }

    /**
     * Publish data using PEP, and block until the server has echoed the publication back to the publishing user.
     *
     * @param geoManager The GeoLocationManager instance for the connection that is expected to publish data.
     * @param discoManager The ServiceDiscoveryManager instance for the connection that is expected to publish data.
     * @param data The data to be published.
     *
     * @throws Exception if the test fails
     */
    public void publishAndWait(GeoLocationManager geoManager, ServiceDiscoveryManager discoManager, GeoLocation data) throws Exception {
        final SimpleResultSyncPoint publicationEchoReceived = new SimpleResultSyncPoint();
        final PepEventListener<GeoLocation> publicationEchoListener = (jid, geoLocation, id, message) -> {
            if (geoLocation.equals(data)) {
                publicationEchoReceived.signal();
            }
        };
        try {
            registerListenerAndWait(geoManager, discoManager, publicationEchoListener);
            geoManager.addGeoLocationListener(publicationEchoListener);
            geoManager.publishGeoLocation(data);
        } finally {
            geoManager.removeGeoLocationListener(publicationEchoListener);
        }
    }
}


text:
#include "Snap.h"

class TIntVHashFunc {
public:
 static inline int GetPrimHashCd(const TIntV& Key) {
  //return Key.GetPrimHashCd();
  const int Len = Key.Len();
  int HashVal = 0x345678;
  for (int i = 0; i < Key.Len(); i++) {
    HashVal = 1000003*HashVal ^ Key[i];
  }
  HashVal = HashVal ^ Len;
  return HashVal;
 }
 static inline int GetSecHashCd(const TIntV& Key) {
   return Key.GetSecHashCd();
 }
};

/////////////////////////////////////////////////
// Trawling the web for emerging communities
// (WWW paper by Tomkins, Kumart, Raghavan, etc.)
class TTrawling {
private:
  int MinSup;
  THash<TInt, TIntV> NIdSetH; // node on the left and the neighbors on the right (contains only nodes with in-deg > MinSup)
  THash<TInt, TIntV> SetNIdH; // set to node ids
  THash<TIntV, TInt, TIntVHashFunc> CandItemH, CurItemH;
  TVec<TIntV> MxFqItemSetV;
public:
  TTrawling(const PNGraph& Graph, const int& MinSupport);
  TTrawling(const PUNGraph& UnGraph, const TIntV& LeftNIdV, const int& MinSupport);

  void GenCandidates();
  int GetSupport(const TIntV& ItemSet);
  void CountSupport();
  void ThresholdSupp();
  void GenCandAndCntSupp(const int& FqItemsetLen);

  void InitItemSets();
  int GetNextFqItemSets(const int& FqItemsetLen=-1);

  int GetFqItems() const { return MxFqItemSetV.Len(); }
  const TIntV& GetItem(const int& ItemN) const { return MxFqItemSetV[ItemN]; }
  const TVec<TIntV>& GetItemV() const { return MxFqItemSetV; }
  TVec<TIntV>& GetItemV() { return MxFqItemSetV; }

  TIntPrV PlotMinFqVsMaxSet(const TStr& OutFNm);
  static void JoinItems(const TIntV& Item1, const TIntV& Item2, TIntV& JoinItem);
  static bool IsIn(const TIntV& BigV, const TIntV& SmallV);
};

#endif


text:
package uk.ac.ebi.embl.flatfile.writer.embl;

import uk.ac.ebi.embl.api.entry.Entry;
import uk.ac.ebi.embl.api.entry.location.CompoundLocation;
import uk.ac.ebi.embl.api.entry.location.LocalRange;
import uk.ac.ebi.embl.api.entry.location.Location;
import uk.ac.ebi.embl.api.entry.reference.Reference;
import uk.ac.ebi.embl.flatfile.EmblPadding;
import uk.ac.ebi.embl.flatfile.writer.FlatFileWriter;
import uk.ac.ebi.embl.flatfile.writer.WrapChar;
import uk.ac.ebi.embl.flatfile.writer.WrapType;

import java.io.IOException;
import java.io.Writer;

/** Flat file writer for the RP lines.
 */
public class RPWriter extends FlatFileWriter {

    private Reference reference;

    public RPWriter(Entry entry, Reference reference, WrapType wrapType) {
        super(entry, wrapType);
        this.reference = reference;
        setWrapChar(WrapChar.WRAP_CHAR_COMMA);
    }

    public boolean write(Writer writer) throws IOException {
    	String location = renderLocation(reference);
        writeBlock(writer, EmblPadding.RP_PADDING, location);
        return !location.isEmpty();
    }

    public static String renderLocation(Reference reference) {
    	StringBuilder block = new StringBuilder();
        CompoundLocation<LocalRange> locations = reference.getLocations();
        boolean isFirstLocation = true;
        for(Location location : locations.getLocations()){
        	if (!isFirstLocation) {
        		block.append(", ");
        	}
        	else {
        		isFirstLocation = false;
        	}
        	block.append(location.getBeginPosition());
        	block.append("-");
        	block.append(location.getEndPosition());

        }
        return block.toString();
    }
}


text:
Genji

An error occured while processing your request …

Specific

								Damage reflected : {{ stats.attack.Genji.damageReflected.value }}  (click for more)

Average : {{ stats.attack.Genji.damageReflected.valueAvg }}

Most in game : {{ stats.attack.Genji.damageReflected.valueMig }}

								Dragon blade kills : {{ stats.attack.Genji.dragonBladeKills.value }}  (click for more)

Average : {{ stats.attack.Genji.dragonBladeKills.valueAvg }}

Most in game : {{ stats.attack.Genji.dragonBladeKills.valueMig }}

Used : {{ stats.attack.Genji.dragonBladeKills.valueUsed }}

General

								  Eliminations : {{ stats.attack.Genji.eliminations.value }} (click for more)

Average : {{ stats.attack.Genji.eliminations.valueAvg }}

Most in game : {{ stats.attack.Genji.eliminations.valueMig }}

Most in life : {{ stats.attack.Genji.eliminations.valueMil }}

								  Final blows : {{ stats.attack.Genji.finalBlows.value }}  (click for more)

Average : {{ stats.attack.Genji.finalBlows.valueAvg }}

Most in game : {{ stats.attack.Genji.finalBlows.valueMig }}

								  Solo kills : {{ stats.attack.Genji.soloKills.value }}  (click for more)

Average : {{ stats.attack.Genji.soloKills.valueAvg }}

Most in game : {{ stats.attack.Genji.soloKills.valueMig }}

								  Deaths : {{ stats.attack.Genji.deaths.value }}  (click for more)

Average : {{ stats.attack.Genji.deaths.valueAvg }}

								  Objective time : {{ stats.attack.Genji.objectiveTime.value }}  (click for more)

Average : {{ stats.attack.Genji.objectiveTime.valueAvg }}

Most in game : {{ stats.attack.Genji.objectiveTime.valueMig }}

								  Objective kills : {{ stats.attack.Genji.objectiveKills.value }}  (click for more)

Average : {{ stats.attack.Genji.objectiveKills.valueAvg }}

Most in game : {{ stats.attack.Genji.objectiveKills.valueMig }}

								  Damage done : {{ stats.attack.Genji.damageDone.value }}  (click for more)

Average : {{ stats.attack.Genji.damageDone.valueAvg }}

Most in game : {{ stats.attack.Genji.damageDone.valueMig }}

Most in life : {{ stats.attack.Genji.damageDone.valueMil }}

								  Critical hits : {{ stats.attack.Genji.criticalHits.value }}  (click for more)

Most in game : {{ stats.attack.Genji.criticalHits.valueMig }}

Most in life : {{ stats.attack.Genji.criticalHits.valueMil }}

Accuracy : {{ stats.attack.Genji.criticalHits.valueAcc }}

Per minute : {{ stats.attack.Genji.criticalHits.valuePerMin }}


text:
package com.umeng.bitmap.thread;
/**
 *
 */
public interface DownloadListener {
    public void onDownloadSize(int size);
    public void onStart();
    public void onComplete(String filePath);
    public void onError();
}


text:
from django.contrib.sitemaps import Sitemap
from django.utils.translation import get_language
from i18n.utils import normalize_language_code

from premises.models import Contention, Premise

class ArgumentSitemap(Sitemap):
    changefreq = "never"
    priority = 0.9

    def items(self):
        language = normalize_language_code(get_language())
        return Contention.objects.filter(
            language=language,
            is_published=True
        )

    def location(self, obj):
        return obj.get_absolute_url()

    def lastmod(self, obj):
        return obj.date_modification

class PremiseSitemap(Sitemap):
    changefreq = "never"
    priority = 0.8

    def items(self):
        language = normalize_language_code(get_language())
        return Premise.objects.filter(
            argument__language=language,
            is_approved=True
        )

    def location(self, obj):
        return obj.get_list_url()


text:
import UIComponent from "./UIComponent";
import Data from "../data/Data";

export default class SVGPath extends UIComponent {

	constructor(element) {
		super(element);
		this._offsetMultiplier = 0;
		this.totalLength = this.getTotalLength();
		this.dashArray = 1;
		this.dashOffset = 1;

		// this.showDuration = 1000;
		// this.hideDuration = 1000;

		// let dataDashOffset = this.element.getAttribute("data-dash-offset");
		// if (dataDashOffset) {
		// 	this.dashOffset = Number(dataDashOffset);
		// }
	}

	getTotalLength() {
		return this.element.getTotalLength();
	}

	get dashArray() {
		return this._dashArray;
	}

	set dashArray(value) {
		this._dashArray = value;
		let length = this.totalLength * value;
		this.element.setAttribute("stroke-dasharray", Math.round(length * 100) / 100);
	}

	get dashOffset() {
		return this._dashOffset;
	}

	set dashOffset(value) {
		this._dashOffset = value;
		let length = this.totalLength * (1 - value * this._offsetMultiplier);
		this.element.setAttribute("stroke-dashoffset", Math.round(length * 100) / 100);
	}

	get offsetMultiplier() {
		return this._offsetMultiplier;
	}

	set offsetMultiplier(value) {
		this._offsetMultiplier = value;
		this.dashOffset = this.dashOffset;
	}

	showDelayComplete() {
		let promise = super.showDelayComplete();
		this.offsetMultiplier = 1;
		return promise;
	}

	hideDelayComplete() {
		let promise = super.hideDelayComplete();
		this.offsetMultiplier = 0;
		return promise;
	}

	get model() {
		return super.model;
	}

	set model(value) {
		super.model = value;
		if (value instanceof Data) value = value.value;
		this.dashOffset = value;
	}

}


text:
const crypto = require("crypto")
const cp = require("child_process")
const fs = require("fs")
const {join, dirname, basename} = require("path")

function npm_install() {
  const npm = process.platform != "win32" ? "npm" : "npm.cmd"
  const {status} = cp.spawnSync(npm, ["install"], {stdio: "inherit"})
  if (status !== 0)
    process.exit(status)
}

if (!fs.existsSync("node_modules/")) {
  console.log("New development environment. Running `npm install`.")
  npm_install()
}

const {engines, workspaces} = require("../package.json")

const node_version = process.version
const npm_version = cp.execSync("npm --version").toString().trim()

const semver = require("semver")

if (!semver.satisfies(node_version, engines.node)) {
  console.log(`node ${engines.node} is required. Current version is ${node_version}.`)
  process.exit(1)
}

if (!semver.satisfies(npm_version, engines.npm)) {
  console.log(`npm ${engines.npm} is required. Current version is ${npm_version}.`)
  process.exit(1)
}

function is_up_to_date(file) {
  const hash_file = join(dirname(file), `.${basename(file)}`)

  if (!fs.existsSync(hash_file))
    return false

  const old_hash = fs.readFileSync(hash_file)

  const new_hash = crypto.createHash("sha256")
                         .update(fs.readFileSync(file))
                         .digest("hex")

  return old_hash == new_hash
}

for (const workspace of ["", ...workspaces]) {
  const path = join(workspace, "package.json")
  if (!is_up_to_date(path)) {
    console.log(`${path} has changed. Running 'npm install'.`)
    npm_install()
    break
  }
}

const {register} = require("ts-node")

process.on('uncaughtException', function(err) {
  console.error(err)
  process.exit(1)
})

register({project: "./make/tsconfig.json", cache: false, logError: true})

const tsconfig_paths = require("tsconfig-paths")

tsconfig_paths.register({
  baseUrl: __dirname,
  paths: {
    "@compiler/*": ["../src/compiler/*"],
  },
})

if (require.main != null)
  require("./main")


text:
const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: slsw.lib.entries,
  target: 'node',
  mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
  optimization: {
    // We no not want to minimize our code.
    minimize: false
  },
  performance: {
    // Turn off size warnings for entry points
    hints: false
  },
  devtool: 'nosources-source-map',
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      }
    ]
  },
  output: {
    libraryTarget: 'commonjs2',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
    sourceMapFilename: '[file].map'
  }
};


text:
package org.gradle.internal.typeconversion;

import org.gradle.api.InvalidUserDataException;
import org.gradle.internal.Cast;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.exceptions.DiagnosticsVisitor;
import org.gradle.internal.reflect.CachedInvokable;
import org.gradle.internal.reflect.ReflectionCache;
import org.gradle.util.ConfigureUtil;

import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * Converts a {@code Map<String, Object>} to the target type. Subclasses should define a {@code T parseMap()} method which takes a parameter
 * for each key value required from the source map. Each parameter should be annotated with a {@code @MapKey} annotation, and can also
 * be annotated with a {@code @Nullable} annotation.
 */
public abstract class MapNotationConverter<T> extends TypedNotationConverter<Map, T> {
    public MapNotationConverter() {
        super(Map.class);
    }

    @Override
    public void describe(DiagnosticsVisitor visitor) {
        visitor.candidate("Maps");
    }

    @Override
    public T parseType(Map values) throws UnsupportedNotationException {
        Map<String, Object> mutableValues = new HashMap<>(Cast.uncheckedNonnullCast(values));
        Set<String> missing = null;
        ConvertMethod convertMethod = null;
        Method method = null;
        while (method == null) {
            convertMethod = ConvertMethod.of(this.getClass());
            // since we need access to the method and that it's weakly referenced
            // we always need to double check that it hasn't been collected
            method = convertMethod.getMethod();
        }
        Class<?>[] parameterTypes = method.getParameterTypes();
        Object[] params = new Object[parameterTypes.length];
        String[] keyNames = convertMethod.keyNames;
        boolean[] optionals = convertMethod.nullables;
        for (int i = 0; i < params.length; i++) {
            String keyName = keyNames[i];
            boolean optional = optionals[i];
            Class<?> type = parameterTypes[i];
            Object value;
            if (type == String.class) {
                value = get(mutableValues, keyName);
            } else {
                value = type.cast(mutableValues.get(keyName));
            }
            if (!optional && value == null) {
                if (missing == null) {
                    missing = new TreeSet<>();
                }
                missing.add(keyName);
            }
            mutableValues.remove(keyName);
            params[i] = value;
        }
        if (missing != null) {
            //below could be better.
            //Throwing InvalidUserDataException here means that useful context information (including candidate formats, etc.) is not presented to the user
            throw new InvalidUserDataException(String.format("Required keys %s are missing from map %s.", missing, values));
        }

        T result;
        try {
            result = Cast.uncheckedNonnullCast(method.invoke(this, params));
        } catch (IllegalAccessException e) {
            throw UncheckedException.throwAsUncheckedException(e);
        } catch (InvocationTargetException e) {
            throw UncheckedException.unwrapAndRethrow(e);
        }

        ConfigureUtil.configureByMap(mutableValues, result);
        return result;
    }

    @Nullable
    protected String get(Map<String, Object> args, String key) {
        Object value = args.get(key);
        String str = value != null ? value.toString() : null;
        if (str != null && str.length() == 0) {
            return null;
        }
        return str;
    }

    private static class ConvertMethodCache extends ReflectionCache<ConvertMethod> {

        @Override
        protected ConvertMethod create(Class<?> key, Class<?>[] params) {
            Method convertMethod = findConvertMethod(key);
            Annotation[][] parameterAnnotations = convertMethod.getParameterAnnotations();
            String[] keyNames = new String[parameterAnnotations.length];
            boolean[] nullables = new boolean[parameterAnnotations.length];
            for (int i = 0; i < parameterAnnotations.length; i++) {
                Annotation[] annotations = parameterAnnotations[i];
                keyNames[i] = keyName(annotations);
                nullables[i] = nullable(annotations);
            }
            return new ConvertMethod(convertMethod, keyNames, nullables);
        }

        private static Method findConvertMethod(Class clazz) {
            for (Method method : clazz.getDeclaredMethods()) {
                if (method.getName().equals("parseMap")) {
                    method.setAccessible(true);
                    return method;
                }
            }
            throw new UnsupportedOperationException(String.format("No parseMap() method found on class %s.", clazz.getSimpleName()));
        }

        private static boolean nullable(Annotation[] annotations) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof Nullable) {
                    return true;
                }
            }
            return false;
        }

        private static String keyName(Annotation[] annotations) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof MapKey) {
                    return ((MapKey) annotation).value();
                }
            }
            throw new UnsupportedOperationException("No @Key annotation on parameter of parseMap() method");
        }

    }

    private static class ConvertMethod extends CachedInvokable<Method> {
        private final static ConvertMethodCache CONVERT_METHODS = new ConvertMethodCache();
        public static final Class[] EMPTY = new Class[0];

        private final String[] keyNames;
        private final boolean[] nullables;

        private ConvertMethod(Method method, String[] keyNames, boolean[] nullables) {
            super(method);
            this.keyNames = keyNames;
            this.nullables = nullables;
        }

        public static synchronized ConvertMethod of(Class clazz) {
            return CONVERT_METHODS.get(clazz, EMPTY);
        }
    }

}


text:
//
//  JCRecord+JCDBOperation.h
//  JCDB
//
//  Created by ChenJianjun on 16/6/16.
//  Copyright © 2016 Joych<https://github.com/imjoych>. All rights reserved.
//

#import "JCRecord.h"

/**
 * Database operation.
 */
@interface JCRecord (JCDBOperation)

#pragma mark - Table operation

/** Create table With class name. */
+ (BOOL)createTable;

/** Delete table */
+ (BOOL)dropTable;

/** Add column in the table. */
+ (BOOL)alterTableWithColumn:(NSString *)column;

#pragma mark - Records operation

/** Query a record with primary key value. */
+ (id)queryRecordWithPrimaryKeyValue:(id)value;

/** Query records with AND conditions which are properties values for properties names. */
+ (NSArray<JCRecord *> *)queryRecordsWithConditions:(NSDictionary *)conditions;

/** Query records with conditional expression and arguments. */
+ (NSArray<JCRecord *> *)queryRecordsWithConditionalExpression:(NSString *)conditionalExpression
                                                     arguments:(NSArray *)arguments;

/** Query all records */
+ (NSArray<JCRecord *> *)queryAllRecords;

/** Query columns values for columns names with conditional expression and arguments. */
+ (NSArray<NSDictionary *> *)queryColumns:(NSArray<NSString *> *)columns
                    conditionalExpression:(NSString *)conditionalExpression
                                arguments:(NSArray *)arguments;

/** Count records with AND conditions which are properties values for properties names. */
+ (uint64_t)countRecordsWithConditions:(NSDictionary *)conditions;

/** Count records with conditional expression and arguments. */
+ (uint64_t)countRecordsWithConditionalExpression:(NSString *)conditionalExpression
                                        arguments:(NSArray *)arguments;

/** Count all records in the table. */
+ (uint64_t)countAllRecords;

/** Delete records with AND conditions which are properties values for properties names. */
+ (BOOL)deleteRecordsWithConditions:(NSDictionary *)conditions;

/** Delete records with conditional expression and arguments. */
+ (BOOL)deleteRecordsWithConditionalExpression:(NSString *)conditionalExpression
                                     arguments:(NSArray *)arguments;

/** Delete all records in the table. */
+ (BOOL)deleteAllRecords;

#pragma mark - Current record operation

/** Insert or replace the record. */
- (BOOL)updateRecord;

/** Update some columns values of the record. */
- (BOOL)updateRecordColumns:(NSArray<NSString *> *)columns
                     values:(NSArray *)values;

/** Delete the record. */
- (BOOL)deleteRecord;

@end


text:
title: Spina
date: 2016-09-19 06:55:00 Z
tags:
- bridal
- flowers
- e-commerce
- shopify
- design
image: "/uploads/162-spina@2x.jpg"
store-link: https://spinanyc.com
credit: Scott Haven
credit-link: http://scott-haven.com
credit-2: Arishill
credit-link-2: https://www.arishill.com
---


text:
package org.opensingular.flow.core;

/**
 * Identify how the task should be displayed if converted to a diagram when rendering a diagram for a {@link
 * FlowDefinition}.
 *
 * @author Daniel C. Bordin on 21/09/2017.
 * @see org.opensingular.flow.core.renderer.IFlowRenderer
 */
public enum DisplayType {
    GATEWAY_EXCLUSIVE, SEND_MESSAGE;
}


text:
using System;
using Zirpl.AppEngine.Service;
using Zirpl.AppEngine.Service.EntityFramework;
using Zirpl.Examples.CodeGeneration.VS2013.Commerce.DataService.Orders;
using Zirpl.Examples.CodeGeneration.VS2013.Commerce.DataService;
using Zirpl.Examples.CodeGeneration.VS2013.Commerce.Model.Orders;

namespace Zirpl.Examples.CodeGeneration.VS2013.Commerce.Service.Orders
{
    public partial class SubscriptionOrderItemService  : DbContextServiceBase<CommerceDataContext, SubscriptionOrderItem, int>, ISubscriptionOrderItemService
    {
    }
}


text:
package ch.genidea.geniweb.base.domain;

import java.io.Serializable;

import javax.persistence.*;

@Entity(name="genidea_role")
public class Role implements Serializable {
    /**
	 *
	 */
	private static final long serialVersionUID = 3717543368267689131L;

	@Id @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne
    private User user;
    private Integer role;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Integer getRole() {
        return role;
    }

    public void setRole(Integer role) {
        this.role = role;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView android:layout_width="fill_parent" android:id ="@+id/phvTitle"
		android:layout_height="wrap_content" android:text="Hosting:Title" />
	<ImageView android:layout_height="wrap_content"
		android:layout_width="wrap_content" android:id="@+id/phvSlide"
		android:src="@drawable/icon"></ImageView>
</LinearLayout>


text:
package com.lee.util;

import java.util.UUID;

/**
 * An {@link IdGenerator} that calls {@link java.util.UUID#randomUUID()}.
 *
 * @author Rossen Stoyanchev
 * @since 4.1.5
 */
public class JdkIdGenerator implements IdGenerator {

    @Override
    public UUID generateId() {
        return UUID.randomUUID();
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>用python脚本优雅的整理Kindle的标注和笔记</title>
    <meta name="description" content="与机器,人,神共舞 - 编程,读书,思考,旅行,与机器对话,与人交谈,对神发问,探索,体验人生美丽的风景" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="/assets/images/favicon.ico" >

    <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css"
          href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
    <link rel="stylesheet" type="text/css" href="/assets/css/syntax.css" />

        <link rel="canonical" href="/" />
    <meta name="referrer" content="origin" />
    <link rel="next" href="/page2/" />

    <meta property="og:site_name" content="与机器,人,神共舞" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="与机器,人,神共舞" />
    <meta property="og:description" content="编程,读书,思考,旅行,与机器对话,与人交谈,对神发问,探索,体验人生美丽的风景" />
    <meta property="og:url" content="/" />
    <meta property="og:image" content="/assets/images/cover1.jpg" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="与机器,人,神共舞" />
    <meta name="twitter:description" content="编程,读书,思考,旅行,与机器对话,与人交谈,对神发问,探索,体验人生美丽的风景" />
    <meta name="twitter:url" content="/" />
    <meta name="twitter:image:src" content="/assets/images/cover1.jpg" />

    <meta name="generator" content="Jekyll 3.0.0" />
    <link rel="alternate" type="application/rss+xml" title="与机器,人,神共舞" href="/rss.xml" />

Menu

        Close

Home

About

Machine

Human

God

Author

    Subscribe

用python脚本优雅的整理Kindle的标注和笔记

            <time class="post-date" datetime="2020-11-12">12 Nov 2020</time>

                on

                       Machine

我是重度Kindle使用者,Kindle里面存满了各类书籍,经常会同时读两三本书,时间一长,多本书的标注和笔记都交叉记录在My Clippings.txt文本文件里,现在这个文件已经有几万行,每次手动去整理特定的一本书的标注和笔记时都极为头疼,还容易错漏,终于有一天实在忍不了了,就去网上找有没有整理kindle标注和笔记的服务,还真让我给找到了,clipping.io,在线服务,马上使用,上传My Clippings.txt文件,一切顺利,文件上传后开始分析整理文本,看到几本书的标注已经出来了,等全部整理结束后发现少了好几本书的,再次重新上传文件重试整理,问题依旧,空欢喜一场,依旧不能解决我的痛点,最近在读的两本书的标注和笔记恰好没有被整理出来,一怒之下,决定自己用python脚本来写一个这样的整理工具,还以为得花费一两天的时间,一不小心,两个小时不到的功夫写完了,调试了一番,完全满足我的需求,现在只需一条命令,传入书名就可以整理出指定的一本书的所有标注和笔记,脚本如下:

# coding=utf-8

import os
import sys

def main():
   filepath = sys.argv[1]
   bookName = sys.argv[2]

   if not os.path.isfile(filepath):
       print("File path {} does not exist. Exiting...".format(filepath))
       sys.exit()

   DELIMITER = "=========="
   TIME_MAKR = "- 您在第"
   lineNum = 0
   books = {}

   bag_of_words = {}
   with open(filepath) as fp:
       encounter = False
       delimiterCount = 0
       curBookName = ""
       for line in fp:
           if lineNum == 0:
               books[line] = []
               curBookName = line
               delimiterCount += 1
           else:
               if line.startswith(DELIMITER):
                   delimiterCount += 1
                   encounter = True
               else:
                   if encounter == True:
                       if line in books:
                           curBookName = line
                       else:
                           books[line] = []
                       encounter = False
                       curBookName = line
                   else:
                       books[curBookName].append(line)
           lineNum += 1
           #print(line)

       fp.close()

   outFile = open("MyClippingOutput.txt", "w")
   for k in books:
       if k.startswith(bookName) :
           outFile.writelines(k)
           lines = books[k]
           for l in lines:
               if l.startswith(TIME_MAKR):
                   continue
               if l.startswith(bookName):
                   continue
               outFile.writelines(l)
   outFile.close()

if __name__ == '__main__':
    main()

目前这个脚本我只是自用,满足我个人的需求,我想肯定也有很多kindle的重度使用者有类似的需求,后续我准备把这个工具也做成在在线服务,使用方式类似clipping.io,做到比clipping.io的可定制型更强,能够适应更多的异常情况,因为我发现clipping.io对一些不规范的书名的容错性很差。期待这个服务上线!

                's Picture

Tao He

 A computer engineer, reader and thinker.

                     Beijing, China
                     longlinht.github.io/

Share this post

                    Twitter

                    Facebook

                    Google+

Please enable JavaScript to view the comments powered by Disqus.

Android module SDK化的实践

读《未来简史》

与机器,人,神共舞 © 2021


text:
This is a simple combination of a button and a piezo buzzer.
Here is the scheam for setting up the button on the arduino:
![button](./alarm.jpg)

# Sample source code
Here is the [link](./alarm.ino) to the sample code.
Prior uploading it to the arduino, you shoùld have the sparkgw running with also the ngrok software in order to replace xxxxx in the sample code to the right id return by ngork


text:
module Radius
  module Generators
    class ErrorPagesGenerator < ::Rails::Generators::Base
      source_root File.expand_path("../templates", __FILE__)
      desc "Copy the error pages to public"
      def create_error_pages
        %w{ 401.html 404.html 422.html 500.html }.each do |file|
          template file, File.join('public', file)
        end
      end
    end
  end
end


text:
namespace IECoreArnoldPreview
{

namespace ShaderAlgo
{

std::vector<AtNode *> convert( const IECore::ObjectVector *shaderNetwork, const std::string &namePrefix = "" );

} // namespace ShaderAlgo

} // namespace IECoreArnoldPreview

#endif // IECOREARNOLDPREVIEW_SHADERALGO_H


text:
package org.wso2.carbon.governance.registry.extensions.handlers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.governance.api.cache.ArtifactCache;
import org.wso2.carbon.governance.api.cache.ArtifactCacheManager;
import org.wso2.carbon.governance.api.exception.GovernanceException;
import org.wso2.carbon.governance.api.util.GovernanceUtils;
import org.wso2.carbon.governance.registry.extensions.utils.CommonUtil;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.internal.RegistryCoreServiceComponent;
import org.wso2.carbon.registry.core.jdbc.handlers.Handler;
import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext;
import org.wso2.carbon.registry.core.session.CurrentSession;
import org.wso2.carbon.registry.core.utils.RegistryUtils;

import javax.cache.Cache;
import java.lang.String;

/**
 * This handler used to handle the Meta Data resources(wsdl,schema,policy, and rxt) cache
 */
public class MetaDataCacheHandler extends Handler {
    private static final Log log = LogFactory.getLog(MetaDataCacheHandler.class);

    @Override
    public void put(RequestContext requestContext) throws RegistryException {
       clearPreFetchArtifact(requestContext);
    }

    @Override
    public void delete(RequestContext requestContext) throws RegistryException {
        clearPreFetchArtifact(requestContext);
    }

   /**
     *  Clear meta data cache
     * @param requestContext RequestContext
     */
    private void clearPreFetchArtifact(RequestContext requestContext) throws RegistryException {
        if(!CommonUtil.isMetaDataClearLockAvailable()){
            return;
        }
        CommonUtil.acquireMetaDataClearLock();
        try{
            Resource resource = requestContext.getResource();
            if (resource == null || resource.getUUID() == null) {
               return;
            }
        String mediaType = resource.getMediaType();
        String artifactPath = null;
        try {
            artifactPath = GovernanceUtils.getDirectArtifactPath(requestContext.getRegistry(), resource.getUUID());
        } catch (GovernanceException e) {
            String msg = "Failed to get path of artifact id = " + resource.getUUID();
            log.error(msg, e);
            throw new RegistryException(msg, e);
        }

        if (mediaType == null || artifactPath == null) {
            return;
        }
        if (mediaType.matches("application/.[a-zA-Z0-9.-]+\\+xml")) {
            ArtifactCache artifactCache =
                    ArtifactCacheManager.getCacheManager().
                            getTenantArtifactCache(CurrentSession.getTenantId());
            String cachePath = RegistryUtils.getRelativePathToOriginal(artifactPath,
                    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
            if (artifactCache != null) {
                if (artifactCache.getArtifact(cachePath) != null) {
                    artifactCache.invalidateArtifact(cachePath);
                }
            }
        }
        }finally {
            CommonUtil.releaseMetaDataClearLock();
        }
    }
}


text:
Spells link logic

= If(C18 <> "", Hyperlink("http://www.d20pfsrd.com/magic/all-spells/" & Lower(Left(C18, 1)) & "/" & Substitute(Substitute(Substitute(Substitute(Substitute(Substitute(Lower(C18), ", communal", ""), ", lesser", ""), ", greater", ""), ", mass", ""), " ", "-"), "'","-"), "●"), "")


text:
package mj.ocraptor.extraction.tika.parser.chm;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import mj.ocraptor.extraction.tika.parser.chm.accessor.DirectoryListingEntry;
import mj.ocraptor.extraction.tika.parser.chm.core.ChmExtractor;
import mj.ocraptor.extraction.tika.parser.html.HtmlParser;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AbstractParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.XHTMLContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

public class ChmParser extends AbstractParser {

  /** Serial version UID */
  private static final long serialVersionUID = 5938777307516469802L;

  private static final Set<MediaType> SUPPORTED_TYPES = Collections
      .unmodifiableSet(new HashSet<MediaType>(Arrays.asList(MediaType
          .application("vnd.ms-htmlhelp"), MediaType.application("chm"), MediaType
          .application("x-chm"))));

  @Override
  public Set<MediaType> getSupportedTypes(ParseContext context) {
    return SUPPORTED_TYPES;
  }

  @Override
  public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
      ParseContext context) throws IOException, SAXException, TikaException {
    ChmExtractor chmExtractor = new ChmExtractor(stream);

    // metadata
    metadata.set(Metadata.CONTENT_TYPE, "application/vnd.ms-htmlhelp");

    // content
    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();

    for (DirectoryListingEntry entry : chmExtractor.getChmDirList().getDirectoryListingEntryList()) {
      if (entry.getName().endsWith(".html") || entry.getName().endsWith(".htm")) {
        xhtml.characters(extract(chmExtractor.extractChmEntry(entry)));
      }
    }

    xhtml.endDocument();
  }

  /**
   * Extracts data from byte[]
   */
  private String extract(byte[] byteObject) throws TikaException {// throws
                                                                  // IOException
    StringBuilder wBuf = new StringBuilder();
    InputStream stream = null;
    Metadata metadata = new Metadata();
    HtmlParser htmlParser = new HtmlParser();
    BodyContentHandler handler = new BodyContentHandler(-1);// -1
    ParseContext parser = new ParseContext();
    try {
      stream = new ByteArrayInputStream(byteObject);
      htmlParser.parse(stream, handler, metadata, parser);
      wBuf.append(handler.toString() + System.getProperty("line.separator"));
    } catch (SAXException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      // Pushback overflow from tagsoup
    }
    return wBuf.toString();
  }

}


text:
'use strict';

var Service = require('hudson-taylor/lib/service');
var Schema  = require('ht-schema');

module.exports = function(transport, config) {

    var mathService = new Service(transport, config);

    mathService.on('add', {
        one: Schema.Number(),
        two: Schema.Number()
    }, function(request, callback) {

        var result = request.one + request.two;

        callback(null, result);

    });

    mathService.on('subtract', {
        one: Schema.Number(),
        two: Schema.Number()
    }, function(request, callback) {

        var result = request.one - request.two;

        callback(null, result);

    });

    return mathService;

};


text:
import { TwoListSelectionPage } from './app.po';

describe('two-list-selection App', () => {
  let page: TwoListSelectionPage;

  beforeEach(() => {
    page = new TwoListSelectionPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('app works!');
  });
});


text:
package org.jbpm.workbench.ht.client.editors.taskdetails;

import java.util.Date;

import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import com.google.gwt.user.client.ui.IsWidget;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jbpm.workbench.common.client.util.UTCDateBox;
import org.jbpm.workbench.ht.client.resources.i18n.Constants;
import org.jbpm.workbench.ht.model.TaskSummary;
import org.jbpm.workbench.ht.model.events.TaskCalendarEvent;
import org.jbpm.workbench.ht.model.events.TaskRefreshedEvent;
import org.jbpm.workbench.ht.model.events.TaskSelectionEvent;
import org.jbpm.workbench.ht.service.TaskService;

@Dependent
public class TaskDetailsPresenter {

    public interface TaskDetailsView extends IsWidget {

        void init(final TaskDetailsPresenter presenter);

        void setTaskDescription(String text);

        void setTaskDescriptionEnabled(Boolean enabled);

        void setDueDate(Long date);

        void setDueDateEnabled(Boolean enabled);

        void setDueDateTime(Long time);

        void setDueDateTimeEnabled(Boolean enabled);

        void setUser(String user);

        void setTaskStatus(String status);

        void setTaskPriority(String priority);

        void setTaskPriorityEnabled(Boolean enabled);

        void setUpdateTaskVisible(Boolean enabled);

        void displayNotification(final String text);
    }

    private Constants constants = Constants.INSTANCE;

    TaskDetailsView view;

    @Inject
    private Caller<TaskService> taskService;

    private Event<TaskRefreshedEvent> taskRefreshed;

    private Event<TaskCalendarEvent> taskCalendarEvent;

    private long currentTaskId = 0;
    private String currentServerTemplateId;
    private String currentContainerId;

    @Inject
    public TaskDetailsPresenter(
            TaskDetailsView view,
            Event<TaskRefreshedEvent> taskRefreshed,
            Event<TaskCalendarEvent> taskCalendarEvent) {
        this.view = view;
        this.taskRefreshed = taskRefreshed;
        this.taskCalendarEvent = taskCalendarEvent;
    }

    @PostConstruct
    public void init() {
        view.init(this);
    }

    public IsWidget getView() {
        return view;
    }

    public void updateTask(final String taskDescription,
            final String userId,
            final Date dueDate,
            final int priority) {

        if (currentTaskId > 0) {

            taskService.call(new RemoteCallback<Void>() {
                @Override
                public void callback( Void nothing ) {
                    view.displayNotification(constants.TaskDetailsUpdatedForTaskId(currentTaskId));
                    taskRefreshed.fire( new TaskRefreshedEvent( currentTaskId ) );
                    taskCalendarEvent.fire( new TaskCalendarEvent( currentTaskId ) );
                }
            }).updateTask(currentServerTemplateId, currentContainerId, currentTaskId, priority, taskDescription, dueDate);

        }
    }

    public void refreshTask() {

        taskService.call(new RemoteCallback<TaskSummary>() {
            @Override
            public void callback(TaskSummary details) {
                if (details == null) {
                    setReadOnlyTaskDetail();
                    return;
                }
                if (details.getStatus().equals("Completed")) {
                    setReadOnlyTaskDetail();
                }
                view.setTaskDescription(details.getDescription());
                final Long date = UTCDateBox.date2utc(details.getExpirationTime());
                if (date != null) {
                    view.setDueDate(date);
                    view.setDueDateTime(date);
                }
                view.setUser(details.getActualOwner());
                view.setTaskStatus(details.getStatus());
                view.setTaskPriority(String.valueOf(details.getPriority()));
            }
        }).getTask(currentServerTemplateId, currentContainerId, currentTaskId);
    }

    public void setReadOnlyTaskDetail() {
        view.setTaskDescriptionEnabled(false);
        view.setDueDateEnabled(false);
        view.setDueDateTimeEnabled(false);
        view.setTaskPriorityEnabled(false);
        view.setUpdateTaskVisible(false);
    }

    public void onTaskSelectionEvent(@Observes final TaskSelectionEvent event) {
        this.currentTaskId = event.getTaskId();
        this.currentServerTemplateId = event.getServerTemplateId();
        this.currentContainerId = event.getContainerId();
        refreshTask();
    }

    public void onTaskRefreshedEvent(@Observes final TaskRefreshedEvent event) {
        if (currentTaskId == event.getTaskId()) {
            refreshTask();
        }
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "duration".
 *
 * @property integer $id
 * @property string $title
 */
class Duration extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'duration';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required'],
            [['title'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
        ];
    }
}


text:
import ToastStore from "../svelte-stores/toast-store"
import {firstToReturn} from "./function-utils";

const fallbackReasons = {
    404: "Not found",
    500: "Server error",
    501: "Disallowed"
};

export function mkErrorMessage(message, e) {
    const fallbackReason = e
        ? fallbackReasons[e.status] || `Status Code: ${e.status}`
        : "Unknown reason";

    const possiblePaths = [
        d => _.get(d,["data", "message"]),
        d => _.get(d, ["error"])
    ];

    const reason = e
        ? ": " + firstToReturn(e, possiblePaths)
        : "";

    return `${message}${reason}`;
}

/**
 * Displays the given message as an error in the toaster.
 * If e is provided then the `e.data.message` attribute will be
 * included (if present).  Also prints the message to `console.log`
 *
 * @param message
 * @param e
 */
export function displayError(message, e) {
    const msg = mkErrorMessage(message, e);
    ToastStore.error(msg);
    console.log(msg, e);
    return msg;
}


text:
require "method_decorators"

module MethodDecorators
  class Retry < Decorator
    def initialize(max, options = {})
      @max = max
      @options = options
      @exceptions = options[:exceptions] || [StandardError]
    end

    def call(orig, this, *args, &blk)
      attempts = 0
      begin
        attempts += 1
        orig.call(*args, &blk)
      rescue *@exceptions
        if attempts < @max
          sleep(@options[:sleep]) if @options[:sleep]
          retry
        end
        raise
      end
    end
  end
end


text:
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{% if page.title %}{{ page.title }}{% else %}{{ site.name }}{% endif %}</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="{{ site.description }}">
    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl }}">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
    <script type="text/javascript" src="//use.typekit.net/djm0fcn.js"></script>
    <script type="text/javascript">try{Typekit.load();}catch(e){}</script>
    <script src="{{ site.baseurl }}/js/main.js"></script>

</head>


text:
<?php

/**
 * @file
 * Contains \Drupal\update\UpdateSettingsForm.
 */

namespace Drupal\update;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Egulias\EmailValidator\EmailValidator;

/**
 * Configure update settings for this site.
 */
class UpdateSettingsForm extends ConfigFormBase implements ContainerInjectionInterface {

  /**
   * The email validator.
   *
   * @var \Egulias\EmailValidator\EmailValidator
   */
  protected $emailValidator;

  /**
   * Constructs a new UpdateSettingsForm.
   *
   * @param \Egulias\EmailValidator\EmailValidator $email_validator
   *   The email validator.
   */
  public function __construct(EmailValidator $email_validator) {
    $this->emailValidator = $email_validator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('email.validator')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'update_settings';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['update.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('update.settings');

    $form['update_check_frequency'] = array(
      '#type' => 'radios',
      '#title' => t('Check for updates'),
      '#default_value' => $config->get('check.interval_days'),
      '#options' => array(
        '1' => t('Daily'),
        '7' => t('Weekly'),
      ),
      '#description' => t('Select how frequently you want to automatically check for new releases of your currently installed modules and themes.'),
    );

    $form['update_check_disabled'] = array(
      '#type' => 'checkbox',
      '#title' => t('Check for updates of uninstalled modules and themes'),
      '#default_value' => $config->get('check.disabled_extensions'),
    );

    $notification_emails = $config->get('notification.emails');
    $form['update_notify_emails'] = array(
      '#type' => 'textarea',
      '#title' => t('Email addresses to notify when updates are available'),
      '#rows' => 4,
      '#default_value' => implode("\n", $notification_emails),
      '#description' => t('Whenever your site checks for available updates and finds new releases, it can notify a list of users via email. Put each address on a separate line. If blank, no emails will be sent.'),
    );

    $form['update_notification_threshold'] = array(
      '#type' => 'radios',
      '#title' => t('Email notification threshold'),
      '#default_value' => $config->get('notification.threshold'),
      '#options' => array(
        'all' => t('All newer versions'),
        'security' => t('Only security updates'),
      ),
      '#description' => t('You can choose to send email only if a security update is available, or to be notified about all newer versions. If there are updates available of Drupal core or any of your installed modules and themes, your site will always print a message on the status report page, and will also display an error message on administration pages if there is a security update.', array(':status_report' => $this->url('system.status')))
    );

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_state->set('notify_emails', []);
    if (!$form_state->isValueEmpty('update_notify_emails')) {
      $valid = array();
      $invalid = array();
      foreach (explode("\n", trim($form_state->getValue('update_notify_emails'))) as $email) {
        $email = trim($email);
        if (!empty($email)) {
          if ($this->emailValidator->isValid($email)) {
            $valid[] = $email;
          }
          else {
            $invalid[] = $email;
          }
        }
      }
      if (empty($invalid)) {
        $form_state->set('notify_emails', $valid);
      }
      elseif (count($invalid) == 1) {
        $form_state->setErrorByName('update_notify_emails', $this->t('%email is not a valid email address.', array('%email' => reset($invalid))));
      }
      else {
        $form_state->setErrorByName('update_notify_emails', $this->t('%emails are not valid email addresses.', array('%emails' => implode(', ', $invalid))));
      }
    }

    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('update.settings');
     // See if the update_check_disabled setting is being changed, and if so,
    // invalidate all update status data.
    if ($form_state->getValue('update_check_disabled') != $config->get('check.disabled_extensions')) {
      update_storage_clear();
    }

    $config
      ->set('check.disabled_extensions', $form_state->getValue('update_check_disabled'))
      ->set('check.interval_days', $form_state->getValue('update_check_frequency'))
      ->set('notification.emails', $form_state->get('notify_emails'))
      ->set('notification.threshold', $form_state->getValue('update_notification_threshold'))
      ->save();

    parent::submitForm($form, $form_state);
  }

}


text:
class ProjectClassificationsCountWorker
  include Sidekiq::Worker

  sidekiq_options queue: :data_low

  sidekiq_options congestion: {
    interval: 60,
    max_in_interval: 1,
    min_delay: 10,
    reject_with: :reschedule,
    key: ->(project_id) {
      "project_#{project_id}_classifications_count_worker"
    }
  }

  sidekiq_options unique: :until_executing

  def perform(project_id)
    project = Project.find(project_id)
    counter = ProjectCounter.new(project)
    project.update_column(:classifications_count, counter.classifications)
  end
end


text:
<?php

namespace Kunstmaan\NodeBundle\Form\EventListener;

use Kunstmaan\NodeBundle\Form\Type\URLChooserType;
use Kunstmaan\NodeBundle\Validation\URLValidator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class URLChooserFormSubscriber implements EventSubscriberInterface
{
    use URLValidator;

    public static function getSubscribedEvents()
    {
        return [
            FormEvents::POST_SET_DATA => 'postSetData',
        ];
    }

    /**
     * When opening the form for the first time, check the type of URL and set the according fields.
     *
     * @param FormEvent $event
     */
    public function postSetData(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $form->getData();

        $attributes['class'] = 'js-change-urlchooser';

        if (!empty($data) && $form->has('link_type')) {
            // Check if e-mail address
            if ($this->isEmailAddress($data)) {
                $form->get('link_type')->setData(URLChooserType::EMAIL);
            } // Check if internal link
            elseif ($this->isInternalLink($data) || $this->isInternalMediaLink($data)) {
                $form->get('link_type')->setData(URLChooserType::INTERNAL);
                $attributes['choose_url'] = true;
            } // Else, it's an external link
            else {
                $form->get('link_type')->setData(URLChooserType::EXTERNAL);
            }
        } else {
            $choices = $form->get('link_type')->getConfig()->getOption('choices');
            $firstOption = array_shift($choices);

            if (URLChooserType::INTERNAL === $firstOption) {
                $attributes['choose_url'] = true;
            }

            $form->get('link_type')->setData($firstOption);
        }

        $form->add('link_url', TextType::class, [
            'label' => 'URL',
            'required' => true,
            'attr' => $attributes,
        ]);
    }
}


text:
import React from 'react';

export const PortalContext = React.createContext(undefined);


text:
const vs = `#version 300 es

// an attribute is an input (in) to a vertex shader.
// It will receive data from a buffer
in vec2 a_position;

uniform vec2 u_resolution;
uniform vec2 u_translation;
uniform vec2 u_rotation;
uniform vec2 u_scale;

// all shaders have a main function
void main() {
  // Scale the positon
  vec2 scaledPosition = a_position * u_scale;

  // Rotate the position
  vec2 rotatedPosition = vec2(
   scaledPosition.x * u_rotation.y + scaledPosition.y * u_rotation.x,
   scaledPosition.y * u_rotation.y - scaledPosition.x * u_rotation.x);

  // Add in the translation
  vec2 position = rotatedPosition + u_translation;

  // convert the position from pixels to 0.0 to 1.0
  vec2 zeroToOne = position / u_resolution;

  // convert from 0->1 to 0->2
  vec2 zeroToTwo = zeroToOne * 2.0;

  // convert from 0->2 to -1->+1 (clipspace)
  vec2 clipSpace = zeroToTwo - 1.0;

  // Flip clipSpace vertically
  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
`;

const fs = `#version 300 es

// fragment shaders don't have a default precision so we need
// to pick one. mediump is a good default. It means "medium precision"
precision mediump float;

uniform vec4 u_color;

// we need to declare an output for the fragment shader
out vec4 outColor;

void main() {
  // Just set the output to a constant redish-purple
  outColor = u_color;
}
`;

var gl;
var uniforms;

function main() {
  // Get A WebGL context
  gl = document.getElementById("canvas").getContext("webgl2");

  if (!gl) {
    alert("No support for WebGL2");
    return;
  }

  // Inital resize of canvas
  canvasAndViewportResize(gl);

  // Compile the shaders and link into a program
  const program = webglUtils.createProgramFromSources(gl, [vs, fs]);

  // Look up where the vertex data needs to go
  const positionAttributeLocation = gl.getAttribLocation(program, "a_position");

  uniforms = initUniforms(program, [
    { name: "u_resolution", type: "2f" },
    { name: "u_translation", type: "2f" },
    { name: "u_rotation", type: "2f" },
    { name: "u_scale", type: "2f" },
    { name: "u_color", type: "4f" },
  ]);

  // Create a buffer
  let positionBuffer = gl.createBuffer();

  // Create a vertex array object (attribute state)
  let vao = gl.createVertexArray();

  // and make it the one we're currently working with
  gl.bindVertexArray(vao);

  // Turn on the attribute
  gl.enableVertexAttribArray(positionAttributeLocation);

  // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

  // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
  let size = 2;          // 2 components per iteration
  let type = gl.FLOAT;   // the data is 32bit floats
  let normalize = false; // don't normalize the data
  let stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
  let offset = 0;        // start at the beginning of the buffer
  gl.vertexAttribPointer(
      positionAttributeLocation, size, type, normalize, stride, offset);

  // Set the clear color to black
  gl.clearColor(0, 0, 0, 1);

  // Tell it to use our program (pair of shaders)
  gl.useProgram(program);

  // Bind the attribute/buffer set we want
  gl.bindVertexArray(vao);

  // --------------------------------------------------------------------------

  // Setup buffer data
  let vertexCount = setGeometry(gl);

  // Bounding box, for wall collision
  let width = 100;
  let height = 100;

  // Initial state
  let state = {
    translation: [
      randomInt(gl.canvas.width - width),
      randomInt(gl.canvas.height - height)
    ],
    angle: 20,
    scale: [1, 0.75],
    color: randomColor(),
    xRight: true,
    yDown: true,
  }

  function updateState() {
    // Update angle
    state.angle = state.angle + 2;

    // Update translation and directions
    state.xRight ? state.translation[0]++ : state.translation[0]--;
    state.yDown ? state.translation[1]++ : state.translation[1]--;
    if (state.translation[0] <= 0) {
      if (!state.xRight) { state.color = randomColor(); }
      state.xRight = true;
    }
    if (state.translation[0] + width >= gl.canvas.width) {
      if (state.xRight) { state.color = randomColor(); }
      state.xRight = false;
    }
    if (state.translation[1] <= 0) {
      if (!state.yDown) { state.color = randomColor(); }
      state.yDown = true;
    }
    if (state.translation[1] + height >= gl.canvas.height) {
      if (state.yDown) { state.color = randomColor(); }
      state.yDown = false;
    }
  }

  function render() {
    canvasAndViewportResize(gl);

    // Clear to black
    gl.clear(gl.COLOR_BUFFER_BIT);

    // Set uniforms
    setUniform("u_resolution", [gl.canvas.width, gl.canvas.height]);
    setUniform("u_translation", state.translation);
    setUniform("u_rotation", angleToRotation(state.angle));
    setUniform("u_scale", state.scale);
    setUniform("u_color", state.color);

    // Draw current contents of buffers
    draw(vertexCount);

    updateState();

    // Loop on new frame
    requestAnimationFrame(render);
  }

  // Start render loop
  render();
}

function canvasAndViewportResize(gl) {
  // let cssToRealPixels = window.devicePixelRatio || 1;
  let cssToRealPixels = 1;
  if (webglUtils.resizeCanvasToDisplaySize(gl.canvas, cssToRealPixels)) {
    // Update viewport to new canvas size
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    return true;
  }
  return false;
}

function initUniforms(program, us) {
  let result = {};
  for(const u of us) {
    result[u.name] = {
      location: gl.getUniformLocation(program, u.name),
      type: u.type
    }
  }
  return result;
}

function setUniform(name, value) {
  const u = uniforms[name];
  switch (u.type) {
    case '2f':
      gl.uniform2fv(u.location, value);
      break;
    case '3f':
      gl.uniform3fv(u.location, value);
      break;
    case '4f':
      gl.uniform4fv(u.location, value);
      break;
  }
}

function draw(count) {
  let primitiveType = gl.TRIANGLES;
  let offset = 0;
  gl.drawArrays(primitiveType, offset, count);
}

function randomColor() {
  return [Math.random(), Math.random(), Math.random(), 1];
}

// Returns a random integer from 0 to range - 1.
function randomInt(range) {
  return Math.floor(Math.random() * range);
}

function angleToRotation(angle) {
  let angleInRadians = angle * Math.PI / 180;
  return [Math.sin(angleInRadians), Math.cos(angleInRadians)];
}

// Fills the buffer with the values that define a rectangle.
function setRectangle(gl, width, height) {
  let x1 = 0;
  let x2 = width;
  let y1 = 0;
  let y2 = height;

  // NOTE: gl.bufferData(gl.ARRAY_BUFFER, ...) will affect
  // whatever buffer is bound to the `ARRAY_BUFFER` bind point
  // but so far we only have one buffer. If we had more than one
  // buffer we'd want to bind that buffer to `ARRAY_BUFFER` first.

  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
    x1, y1,
    x2, y1,
    x1, y2,
    x1, y2,
    x2, y1,
    x2, y2]), gl.STATIC_DRAW);

    return 6;
}

function setGeometry(gl) {
  var width = 100;
  var height = 150;
  var x = -width/2;
  var y = -height/2;
  var thickness = 30;
  gl.bufferData(
    gl.ARRAY_BUFFER,
    new Float32Array([
      // left column
      x, y,
      x + thickness, y,
      x, y + height,
      x, y + height,
      x + thickness, y,
      x + thickness, y + height,

      // top rung
      x + thickness, y,
      x + width, y,
      x + thickness, y + thickness,
      x + thickness, y + thickness,
      x + width, y,
      x + width, y + thickness,

      // middle rung
      x + thickness, y + thickness * 2,
      x + width * 2 / 3, y + thickness * 2,
      x + thickness, y + thickness * 3,
      x + thickness, y + thickness * 3,
      x + width * 2 / 3, y + thickness * 2,
      x + width * 2 / 3, y + thickness * 3]),
    gl.STATIC_DRAW);
  return 18;
}


text:
//
//  GTLYouTubeVideoContentDetailsRegionRestriction.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   YouTube Data API (youtube/v3)
// Description:
//   Programmatic access to YouTube features.
// Documentation:
//   https://developers.google.com/youtube/v3
// Classes:
//   GTLYouTubeVideoContentDetailsRegionRestriction (0 custom class methods, 2 custom properties)

#import "GTLYouTubeVideoContentDetailsRegionRestriction.h"

// ----------------------------------------------------------------------------
//
//   GTLYouTubeVideoContentDetailsRegionRestriction
//

@implementation GTLYouTubeVideoContentDetailsRegionRestriction
@dynamic allowed, blocked;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"allowed" : [NSString class],
    @"blocked" : [NSString class]
  };
  return map;
}

@end