text:
/**
* @name         : EDITOR.actions.createObject
* @localization : core/js/editor/createObject.js
* @arguments    : EDITOR.actions.createObject(string type, string token_parent, int level_parent)
* @description  : Permet de créer un objet et de l'ajouter ensuite dans la liste des objets
* @return       : aucun retour
*/

EDITOR.actions.createObject = function(type, token, level)
{
    var return_modal = query("#return_modal_add");

    var args = [type, token, level, query("#input_modal_add").value, JSON.parse(localStorage.getItem("request_args"))[2]].join("|");

    return_modal.innerHTML = "<img src='public/images/tiny_loader.png' />";

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "core/php/controller.php", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function()
    {
        if(xhr.status == 200 && xhr.readyState == 4)
        {
            var state = xhr.responseText.split("\u0000")[0];
            var data = xhr.responseText.split("\u0000")[1];

            if(state == "S")
            {
                return_modal.innerHTML = "✓";

                try
                {
                    var content = JSON.parse(data);

                    // Convertion du JSON en objet
                    var object = {
                        token: content[0],
                        level: content[3],
                        classement: content[5],
                        title: content[4],
                        content: "",
                        parent: content[2],
                        type: content[1]
                    };
                }
                catch(err)
                {
                    console.error(err);
                }

                EDITOR.actions.putObject(object);

                setTimeout(function(){
                    EDITOR.actions.hideModalCreate();
                }, 1000);
            }
            else
            {
                return_modal.innerHTML = "❌";
            }
        }
    }

    xhr.send("c=Objects&a=addObject&p="+args);
}


text:
<?php
require_once("../lib/init.php");
protectPage(12);	// Profile pictures privileges

// Get a list of all current members
$q = "SELECT ID FROM Members WHERE WardID={$MEMBER->WardID} AND PictureFile != '' ORDER BY FirstName ASC, LastName ASC";
$r = DB::Run($q);

if (mysql_num_rows($r) == 0)
	fail("No pictures to export; no members have a profile picture.");

$zip = new ZipStream("profile_pics.zip");

while ($row = mysql_fetch_array($r))
{
	$member = Member::Load($row['ID']);
	$file = $member->PictureFile;
	if (file_exists("../uploads/{$file}"))
		$zip->addLargeFile("../uploads/".$file, "profile_pictures/".$file);
}

$zip->finalize();
?>

redpajama_set_name: RedPajamaGithub


text:
function test_princomp
% Run some tests to see if the triple negative data could be simplified
% using principal component analysis

% By Daniel Golden (dgolden1 at stanford dot edu) May 2012
% $Id$

%% Setup
if ~exist('b_stanford_only', 'var') || isempty(b_stanford_only)
  b_stanford_only = false;
end
if ~exist('max_num_features', 'var') || isempty(max_num_features)
  max_num_features = Inf;
end

load('lesion_parameters.mat', 'lesions');

%% Remove outliers
lesions = exclude_patients(lesions, b_stanford_only);

%% Set up input and output matrices
[x, x_names, y, patient_ids] = get_glcm_model_inputs(lesions);

%% Do principal component analysis
[coeff, score, latent] = princomp(zscore(x));

for kk = 1:10
  fprintf('Variance explained by %d PCs: %0.3f, PC %d only: %0.3f\n', kk, sum(latent(1:kk))/sum(latent), kk, latent(kk)/sum(latent));
end

figure;
barh(abs(coeff(:, 1)));
set(gca, 'ytick', 1:length(x_names), 'yticklabel', x_names);
xlabel('PC weight');
axis tight;

1;


text:
from math import sqrt

critics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
                         'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
                         'The Night Listener': 3.0},
           'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
                            'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
                            'You, Me and Dupree': 3.5},
           'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
                                'Superman Returns': 3.5, 'The Night Listener': 4.0},
           'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
                            'The Night Listener': 4.5, 'Superman Returns': 4.0,
                            'You, Me and Dupree': 2.5},
           'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
                            'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
                            'You, Me and Dupree': 2.0},
           'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
                             'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
           'Toby': {'Snakes on a Plane': 4.5, 'You, Me and Dupree': 1.0, 'Superman Returns': 4.0}}

def sim_distance(prefs, person1, person2):
    shared_item = {}
    for item in prefs[person1]:
        if item in prefs[person2]:
            shared_item[item] = 1
    if len(shared_item) == 0:
        return 0
    sum_of_squares = sum([pow(prefs[person1][item] - prefs[person2][item], 2)
                          for item in prefs[person1] if item in prefs[person2]])
    return 1 / (1 + sum_of_squares)

def sim_pearson(prefs, p1, p2):
    si = {}
    for item in prefs[p1]:
        if item in prefs[p2]: si[item] = 1
    n = len(si)
    if n == 0: return 0
    sum1 = sum([prefs[p1][it] for it in si])
    sum2 = sum([prefs[p2][it] for it in si])

    sum1Sq = sum([pow(prefs[p1][it], 2) for it in si])
    sum2Sq = sum([pow(prefs[p2][it], 2) for it in si])

    pSum = sum([prefs[p1][it] * prefs[p2][it] for it in si])

    num = pSum - (sum1 * sum2 / n)
    den = sqrt((sum1Sq - pow(sum1, 2) / n) * (sum2Sq - pow(sum2, 2) / n))
    if den == 0: return 0
    r = num / den
    return r

def topMatches(prefs, person, n=5, similarity=sim_pearson):
    scores = [(similarity(prefs, person, other), other)
              for other in prefs if other != person]
    scores.sort()
    scores.reverse()
    return scores[0:n]

def getRecommendations(prefs, person, similarity=sim_pearson):
    totals = {}
    simSums = {}
    for other in prefs:
        # don't compare me to myself
        if other == person: continue
        sim = similarity(prefs, person, other)
        # ignore scores of zero or lower
        if sim <= 0: continue
        for item in prefs[other]:
            # only score movies I haven't seen yet
            if item not in prefs[person] or prefs[person][item] == 0:
                # Similarity * Score
                totals.setdefault(item, 0)
                totals[item] += prefs[other][item] * sim
                # Sum of similarities
                simSums.setdefault(item, 0)
                simSums[item] += sim
    # Create the normalized list
    rankings = [(total / simSums[item], item) for item, total in totals.items()]
    # Return the sorted list
    rankings.sort()
    rankings.reverse()
    return rankings

print(sim_distance(critics, 'Lisa Rose', 'Gene Seymour'))
print(sim_pearson(critics, 'Lisa Rose', 'Gene Seymour'))
print(topMatches(critics, 'Lisa Rose', n=3))


text:
from singa import layer
from singa import model

def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return layer.Conv2d(
        in_planes,
        out_planes,
        3,
        stride=stride,
        padding=1,
        bias=False,
    )

class BasicBlock(layer.Layer):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = layer.BatchNorm2d(planes)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = layer.BatchNorm2d(planes)
        self.relu1 = layer.ReLU()
        self.add = layer.Add()
        self.relu2 = layer.ReLU()
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu1(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out = self.add(out, residual)
        out = self.relu2(out)

        return out

class Bottleneck(layer.Layer):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = layer.Conv2d(inplanes, planes, 1, bias=False)
        self.bn1 = layer.BatchNorm2d(planes)
        self.relu1 = layer.ReLU()
        self.conv2 = layer.Conv2d(planes,
                                  planes,
                                  3,
                                  stride=stride,
                                  padding=1,
                                  bias=False)
        self.bn2 = layer.BatchNorm2d(planes)
        self.relu2 = layer.ReLU()
        self.conv3 = layer.Conv2d(planes,
                                  planes * self.expansion,
                                  1,
                                  bias=False)
        self.bn3 = layer.BatchNorm2d(planes * self.expansion)

        self.add = layer.Add()
        self.relu3 = layer.ReLU()

        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu1(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu2(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out = self.add(out, residual)
        out = self.relu3(out)

        return out

__all__ = [
    'ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'
]

class ResNet(model.Model):

    def __init__(self, block, layers, num_classes=10, num_channels=3):
        self.inplanes = 64
        super(ResNet, self).__init__()
        self.num_classes = num_classes
        self.input_size = 224
        self.dimension = 4
        self.conv1 = layer.Conv2d(num_channels,
                                  64,
                                  7,
                                  stride=2,
                                  padding=3,
                                  bias=False)
        self.bn1 = layer.BatchNorm2d(64)
        self.relu = layer.ReLU()
        self.maxpool = layer.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1, layers1 = self._make_layer(block, 64, layers[0])
        self.layer2, layers2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3, layers3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4, layers4 = self._make_layer(block, 512, layers[3], stride=2)
        self.avgpool = layer.AvgPool2d(7, stride=1)
        self.flatten = layer.Flatten()
        self.fc = layer.Linear(num_classes)
        self.softmax_cross_entropy = layer.SoftMaxCrossEntropy()

        self.register_layers(*layers1, *layers2, *layers3, *layers4)

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            conv = layer.Conv2d(
                self.inplanes,
                planes * block.expansion,
                1,
                stride=stride,
                bias=False,
            )
            bn = layer.BatchNorm2d(planes * block.expansion)

            def _downsample(x):
                return bn(conv(x))

            downsample = _downsample

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        def forward(x):
            for layer in layers:
                x = layer(x)
            return x

        return forward, layers

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = self.flatten(x)
        x = self.fc(x)

        return x

    def train_one_batch(self, x, y, dist_option, spars):
        out = self.forward(x)
        loss = self.softmax_cross_entropy(out, y)

        if dist_option == 'plain':
            self.optimizer(loss)
        elif dist_option == 'half':
            self.optimizer.backward_and_update_half(loss)
        elif dist_option == 'partialUpdate':
            self.optimizer.backward_and_partial_update(loss)
        elif dist_option == 'sparseTopK':
            self.optimizer.backward_and_sparse_update(loss,
                                                      topK=True,
                                                      spars=spars)
        elif dist_option == 'sparseThreshold':
            self.optimizer.backward_and_sparse_update(loss,
                                                      topK=False,
                                                      spars=spars)
        return out, loss

    def set_optimizer(self, optimizer):
        self.optimizer = optimizer

def resnet18(pretrained=False, **kwargs):
    """Constructs a ResNet-18 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet.

    Returns:
        The created ResNet-18 model.
    """
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)

    return model

def resnet34(pretrained=False, **kwargs):
    """Constructs a ResNet-34 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet.

    Returns:
        The created ResNet-34 model.
    """
    model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)

    return model

def resnet50(pretrained=False, **kwargs):
    """Constructs a ResNet-50 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet.

    Returns:
        The created ResNet-50 model.
    """
    model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)

    return model

def resnet101(pretrained=False, **kwargs):
    """Constructs a ResNet-101 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet.

    Returns:
        The created ResNet-101 model.
    """
    model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)

    return model

def resnet152(pretrained=False, **kwargs):
    """Constructs a ResNet-152 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet.

    Returns:
        The created ResNet-152 model.
    """
    model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)

    return model

__all__ = [
    'ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'
]


text:
{% extends "base.html" %}

{% block meta %}
    <meta name="description" content="A blog created by Ubuntu community members to provide news, tutorials, reviews, tips, and the occasional rant - all centering around the world's most popular Linux distribution: Ubuntu.">
    <meta name="google-site-verification" content="BOrMmOCjwsu-XkdXWgqIHA5CP85AZjA2-MZzn8DWkvI">
    <meta name="wot-verification" content="e3ab301eccb71149c5d5">
{% endblock %}

{% block rss %}
    <link rel="alternate" type="application/rss+xml" title="2buntu Articles" href="{% url "rss" %}" />
{% endblock %}

{% block content %}

            {% if not "page" in request.GET %}
                {% include "articles/fragments/featured.html" %}

                {% include "accounts/fragments/authors.html" %}

Recent Articles

                    Looking for more great content? There's more where that came from!
                    Here are some other articles that have recently been published.

                {% with articles|slice:"3:" as articles %}
                    {% include "articles/fragments/articles.html" %}
                {% endwith %}
            {% else %}

Archives — Page {{ request.GET.page }}

                    Check out some of our older articles below.
                    We've been publishing articles for a very long time, so there's
                    sure to be something here for everybody.

                {% include "articles/fragments/articles.html" %}
            {% endif %}

            {% include "fragments/search.html" %}

            {% include "news/fragments/items.html" %}

                    Latest Articles Feed

                    Pushbullet Channel

            {% include "categories/fragments/categories.html" %}

{% endblock %}


text:
module System.HID.Internal.Utils where

import Foreign.C.Types

-- |Convert returned int by hidapi into booleans.
--
--   - **0** means success; 'True'
--   - **-1** means failure; 'False'
--
-- For the sake of safety, anything that is not **0** is considered a failure.
fromHIDRet :: CInt -> Bool
fromHIDRet r
  | r == 0 = True
  | otherwise = False


text:
package org.apache.activemq.security;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Set;

import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext;

import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.jaas.GroupPrincipal;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifFiles;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.apache.directory.server.ldap.LdapServer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * This test assumes setup like in file 'AMQauth.ldif'. Contents of this file is attached below in comments.
 *
 * @author ngcutura
 */
@RunWith(FrameworkRunner.class)
@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")})
@ApplyLdifFiles("org/apache/activemq/security/AMQauth.ldif")
public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit {

   private static LDAPAuthorizationMap authMap;

   public static LdapServer ldapServer;

   @Before
   public void setup() throws Exception {
      authMap = new LDAPAuthorizationMap();
      authMap.setConnectionURL("ldap://localhost:" + getLdapServer().getPort());
      authMap.setTopicSearchMatchingFormat(new MessageFormat("uid={0},ou=topics,ou=destinations,o=ActiveMQ,ou=system"));
      authMap.setQueueSearchMatchingFormat(new MessageFormat("uid={0},ou=queues,ou=destinations,o=ActiveMQ,ou=system"));
      authMap.setAdvisorySearchBase("uid=ActiveMQ.Advisory,ou=topics,ou=destinations,o=ActiveMQ,ou=system");
      authMap.setTempSearchBase("uid=ActiveMQ.Temp,ou=topics,ou=destinations,o=ActiveMQ,ou=system");
   }

   @Test
   public void testOpen() throws Exception {
      DirContext ctx = authMap.open();
      HashSet<String> set = new HashSet<>();
      NamingEnumeration<NameClassPair> list = ctx.list("ou=destinations,o=ActiveMQ,ou=system");
      while (list.hasMore()) {
         NameClassPair ncp = list.next();
         set.add(ncp.getName());
      }
      assertTrue(set.contains("ou=topics"));
      assertTrue(set.contains("ou=queues"));
   }

   /*
    * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getAdminACLs(ActiveMQDestination)'
    */
   @Test
   public void testGetAdminACLs() {
      ActiveMQDestination q1 = new ActiveMQQueue("queue1");
      Set<GroupPrincipal> aclsq1 = authMap.getAdminACLs(q1);
      assertEquals(1, aclsq1.size());
      assertTrue(aclsq1.contains(new GroupPrincipal("role1")));

      ActiveMQDestination t1 = new ActiveMQTopic("topic1");
      Set<GroupPrincipal> aclst1 = authMap.getAdminACLs(t1);
      assertEquals(1, aclst1.size());
      assertTrue(aclst1.contains(new GroupPrincipal("role1")));
   }

   /*
    * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getReadACLs(ActiveMQDestination)'
    */
   @Test
   public void testGetReadACLs() {
      ActiveMQDestination q1 = new ActiveMQQueue("queue1");
      Set<GroupPrincipal> aclsq1 = authMap.getReadACLs(q1);
      assertEquals(1, aclsq1.size());
      assertTrue(aclsq1.contains(new GroupPrincipal("role1")));

      ActiveMQDestination t1 = new ActiveMQTopic("topic1");
      Set<GroupPrincipal> aclst1 = authMap.getReadACLs(t1);
      assertEquals(1, aclst1.size());
      assertTrue(aclst1.contains(new GroupPrincipal("role2")));
   }

   /*
    * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getWriteACLs(ActiveMQDestination)'
    */
   @Test
   public void testGetWriteACLs() {
      ActiveMQDestination q1 = new ActiveMQQueue("queue1");
      Set<GroupPrincipal> aclsq1 = authMap.getWriteACLs(q1);
      assertEquals(2, aclsq1.size());
      assertTrue(aclsq1.contains(new GroupPrincipal("role1")));
      assertTrue(aclsq1.contains(new GroupPrincipal("role2")));

      ActiveMQDestination t1 = new ActiveMQTopic("topic1");
      Set<GroupPrincipal> aclst1 = authMap.getWriteACLs(t1);
      assertEquals(1, aclst1.size());
      assertTrue(aclst1.contains(new GroupPrincipal("role3")));
   }

   @Test
   public void testComposite() {
      ActiveMQDestination q1 = new ActiveMQQueue("queue1,topic://topic1");
      Set<GroupPrincipal> aclsq1 = authMap.getWriteACLs(q1);
      assertEquals(0, aclsq1.size());
   }

   @Test
   public void testAdvisory() {
      ActiveMQDestination dest = AdvisorySupport.getConnectionAdvisoryTopic();
      Set<GroupPrincipal> acls = authMap.getWriteACLs(dest);

      assertEquals(1, acls.size());
      assertTrue(acls.contains(new GroupPrincipal("role3")));
   }

   @Test
   public void testTemp() {
      Set<GroupPrincipal> acls = authMap.getTempDestinationAdminACLs();

      assertEquals(1, acls.size());
      assertTrue(acls.contains(new GroupPrincipal("role1")));
   }

}


text:
"""
Tests for biblio.webquery.isbndb, using nose.
"""

### IMPORTS ###

from biblio.webquery import isbndb

### CONSTANTS & DEFINES ###

BAD_STATUS_XML = """<?xml version="1.0" encoding="UTF-8" ?>
	<rsp xmlns="http://worldcat.org/xid/isbn/" stat="invalidId"/>"""

SIMPLE_ONE_XML = """<?xml version="1.0" encoding="UTF-8"?>
	<ISBNdb server_time="2005-07-29T02:41:22">
	 <BookList total_results="1" page_size="10" page_number="1" shown_results="1">
	  <BookData book_id="law_and_disorder" isbn="0210406240">
	   <Title>Law and disorder</Title>
	   <TitleLong>
	    Law and disorder: law enforcement in television network news
	   </TitleLong>
	   <AuthorsText>V. M. Mishra</AuthorsText>
	   <PublisherText publisher_id="asia_pub_house">
	    New York: Asia Pub. House, c1979.
	   </PublisherText>
	   <Details dewey_decimal="302.2/3"
	            dewey_decimal_normalized="302.23"
	            lcc_number="PN4888"
	            language="eng"
	            physical_description_text="x, 127 p. ; 22 cm."
	            edition_info=""
	            change_time="2004-10-19T23:52:56"
	            price_time="2005-07-29T02:06:41" />
	  </BookData>
	 </BookList>
	</ISBNdb>"""

SIMPLE_TWO_XML = """<?xml version="1.0" encoding="UTF-8"?>
<ISBNdb server_time="2009-05-07T15:54:03Z">
<BookList total_results="1" page_size="10" page_number="1" shown_results="1">
<BookData book_id="progress_in_botany_volume_66" isbn="3540224742" isbn13="9783540224747">
<Title>Progress in Botany / Volume 66</Title>
<TitleLong></TitleLong>
<AuthorsText>K. Esser (Editor), U. Lüttge (Editor), W. Beyschlag (Editor), J. Murata (Editor)</AuthorsText>
<PublisherText publisher_id="springer">Springer</PublisherText>
</BookData>
</BookList>
</ISBNdb>"""

### TESTS ###

class test_isbndb_xml_to_bibrecords (object):
	#def test_bad_status (self):
	#	try:
	#		recs = xisbn.xisbn_xml_to_dicts (BAD_STATUS_XML)
	#		assert (False), "should fail if reading document with bad status"
	#	except:
	#		pass

	def test_simple_one (self):
		recs = isbndb.isbndb_xml_to_bibrecords (SIMPLE_ONE_XML)
		assert (len (recs) == 1)

	def test_simple_two (self):
		recs = isbndb.isbndb_xml_to_bibrecords (SIMPLE_TWO_XML)
		print recs
		assert (len (recs) == 2)

### END ######################################################################


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script type="text/javascript" src="02-InfiniteRecursion.js"></script>
</body>
</html>


text:
module Backup
  module Database
    class OpenLDAP < Base
      class Error < Backup::Error; end

      ##
      # Name of the ldap backup
      attr_accessor :name

      ##
      # run slapcat under sudo if needed
      # make sure to set SUID on a file, to let you run the file with permissions of file owner
      # eg. sudo chmod u+s /usr/sbin/slapcat
      attr_accessor :use_sudo

      ##
      # Stores the location of the slapd.conf or slapcat confdir
      attr_accessor :slapcat_conf

      ##
      # Additional slapcat options
      attr_accessor :slapcat_args

      ##
      # Path to slapcat utility (optional)
      attr_accessor :slapcat_utility

      ##
      # Takes the name of the archive and the configuration block
      def initialize(model, database_id = nil, &block)
        super
        instance_eval(&block) if block_given?

        @name             ||= "ldap_backup"
        @use_sudo         ||= false
        @slapcat_args     ||= []
        @slapcat_utility  ||= utility(:slapcat)
        @slapcat_conf     ||= "/etc/ldap/slapd.d"
      end

      ##
      # Performs the slapcat command and outputs the
      # data to the specified path based on the 'trigger'
      def perform!
        super

        pipeline = Pipeline.new
        dump_ext = "ldif"

        pipeline << slapcat
        if @model.compressor
          @model.compressor.compress_with do |command, ext|
            pipeline << command
            dump_ext << ext
          end
        end

        pipeline << "#{utility(:cat)} > " \
            "'#{File.join(dump_path, dump_filename)}.#{dump_ext}'"

        pipeline.run
        if pipeline.success?
          log!(:finished)
        else
          raise Error, "Dump Failed!\n" + pipeline.error_messages
        end
      end

      private

      ##
      # Builds the full slapcat string based on all attributes
      def slapcat
        command = "#{slapcat_utility} #{slapcat_conf_option} #{slapcat_conf} #{user_options}"
        command.prepend("sudo ") if use_sudo
        command
      end

      ##
      # Uses different slapcat switch depending on confdir or conffile set
      def slapcat_conf_option
        @slapcat_conf.include?(".d") ? "-F" : "-f"
      end

      ##
      # Builds a compatible string for the additional options
      # specified by the user
      def user_options
        slapcat_args.join(" ")
      end
    end
  end
end


text:
This is the Git repository for my personal website which is built on [jekyll](http://jekyllrb.com/).

Social icons are [octicons](https://octicons.github.com).
Mardown parser is [redcarpet](https://github.com/vmg/redcarpet).

### License

All original (posts) content at jjjjess.com is licensed under a [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) attributable to [Jess Anastasia](http://jjjjess.com).

All code available [on GitHub](https://github.com/janastasia/jjjjess.com) and licensed under the [MIT license](http://opensource.org/licenses/MIT).


text:
package org.apache.asterix.runtime.evaluators.common;

import java.io.DataOutput;
import java.io.IOException;

import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.dataflow.data.nontagged.serde.AFloatSerializerDeserializer;
import org.apache.asterix.dataflow.data.nontagged.serde.AOrderedListSerializerDeserializer;
import org.apache.asterix.dataflow.data.nontagged.serde.AUnorderedListSerializerDeserializer;
import org.apache.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import org.apache.asterix.fuzzyjoin.IntArray;
import org.apache.asterix.fuzzyjoin.similarity.PartialIntersect;
import org.apache.asterix.fuzzyjoin.similarity.SimilarityFiltersJaccard;
import org.apache.asterix.fuzzyjoin.similarity.SimilarityMetric;
import org.apache.asterix.om.base.AFloat;
import org.apache.asterix.om.base.AMutableFloat;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.asterix.om.types.EnumDeserializer;
import org.apache.asterix.om.types.hierachy.ATypeHierarchy;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.data.std.api.IPointable;
import org.apache.hyracks.data.std.primitive.VoidPointable;
import org.apache.hyracks.data.std.util.ArrayBackedValueStorage;
import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference;

public class SimilarityJaccardPrefixEvaluator implements IScalarEvaluator {
    // assuming type indicator in serde format
    protected final int typeIndicatorSize = 1;

    protected final ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage();
    protected final DataOutput out = resultStorage.getDataOutput();
    protected final IPointable inputVal = new VoidPointable();
    protected final IScalarEvaluator evalLen1;
    protected final IScalarEvaluator evalTokens1;
    protected final IScalarEvaluator evalLen2;
    protected final IScalarEvaluator evalTokens2;
    protected final IScalarEvaluator evalTokenPrefix;
    protected final IScalarEvaluator evalThreshold;

    protected float similarityThresholdCache;
    protected SimilarityFiltersJaccard similarityFilters;
    protected final IntArray tokens1 = new IntArray();
    protected final IntArray tokens2 = new IntArray();
    protected final PartialIntersect parInter = new PartialIntersect();

    protected float sim = 0.0f;

    // result
    protected final AMutableFloat res = new AMutableFloat(0);
    @SuppressWarnings("unchecked")
    protected final ISerializerDeserializer<AFloat> reusSerde = AqlSerializerDeserializerProvider.INSTANCE
            .getSerializerDeserializer(BuiltinType.AFLOAT);

    public SimilarityJaccardPrefixEvaluator(IScalarEvaluatorFactory[] args, IHyracksTaskContext context)
            throws AlgebricksException {
        evalLen1 = args[0].createScalarEvaluator(context);
        evalTokens1 = args[1].createScalarEvaluator(context);
        evalLen2 = args[2].createScalarEvaluator(context);
        evalTokens2 = args[3].createScalarEvaluator(context);
        evalTokenPrefix = args[4].createScalarEvaluator(context);
        evalThreshold = args[5].createScalarEvaluator(context);
    }

    @Override
    public void evaluate(IFrameTupleReference tuple, IPointable result) throws AlgebricksException {
        resultStorage.reset();
        // similarity threshold
        sim = 0;
        evalThreshold.evaluate(tuple, inputVal);
        float similarityThreshold = AFloatSerializerDeserializer.getFloat(inputVal.getByteArray(),
                inputVal.getStartOffset() + 1);

        if (similarityThreshold != similarityThresholdCache || similarityFilters == null) {
            similarityFilters = new SimilarityFiltersJaccard(similarityThreshold);
            similarityThresholdCache = similarityThreshold;
        }

        evalLen1.evaluate(tuple, inputVal);
        int length1 = 0;
        try {
            length1 = ATypeHierarchy.getIntegerValue(inputVal.getByteArray(), inputVal.getStartOffset());
        } catch (HyracksDataException e1) {
            throw new AlgebricksException(e1);
        }

        evalLen2.evaluate(tuple, inputVal);
        int length2 = 0;

        try {
            length2 = ATypeHierarchy.getIntegerValue(inputVal.getByteArray(), inputVal.getStartOffset());
        } catch (HyracksDataException e1) {
            throw new AlgebricksException(e1);
        }

        //
        // -- - length filter - --
        //
        if (similarityFilters.passLengthFilter(length1, length2)) {

            // -- - tokens1 - --
            int i;
            tokens1.reset();
            evalTokens1.evaluate(tuple, inputVal);

            byte[] serList = inputVal.getByteArray();
            int startOffset = inputVal.getStartOffset();
            if (serList[startOffset] != ATypeTag.SERIALIZED_ORDEREDLIST_TYPE_TAG
                    && serList[startOffset] != ATypeTag.SERIALIZED_UNORDEREDLIST_TYPE_TAG) {
                throw new AlgebricksException("Scan collection is not defined for values of type"
                        + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(serList[startOffset]));
            }

            int lengthTokens1;
            if (serList[startOffset] == ATypeTag.SERIALIZED_ORDEREDLIST_TYPE_TAG) {
                lengthTokens1 = AOrderedListSerializerDeserializer.getNumberOfItems(inputVal.getByteArray(),
                        startOffset);
                // read tokens
                for (i = 0; i < lengthTokens1; i++) {
                    int itemOffset;
                    int token;
                    try {
                        itemOffset = AOrderedListSerializerDeserializer.getItemOffset(serList, startOffset, i);
                    } catch (AsterixException e) {
                        throw new AlgebricksException(e);
                    }

                    try {
                        token = ATypeHierarchy.getIntegerValueWithDifferentTypeTagPosition(serList, itemOffset,
                                startOffset + 1);
                    } catch (HyracksDataException e) {
                        throw new AlgebricksException(e);
                    }
                    tokens1.add(token);
                }
            } else {
                lengthTokens1 = AUnorderedListSerializerDeserializer.getNumberOfItems(inputVal.getByteArray(),
                        startOffset);
                // read tokens
                for (i = 0; i < lengthTokens1; i++) {
                    int itemOffset;
                    int token;

                    try {
                        itemOffset = AUnorderedListSerializerDeserializer.getItemOffset(serList, startOffset, i);
                    } catch (AsterixException e) {
                        throw new AlgebricksException(e);
                    }

                    try {
                        token = ATypeHierarchy.getIntegerValueWithDifferentTypeTagPosition(serList, itemOffset,
                                startOffset + 1);
                    } catch (HyracksDataException e) {
                        throw new AlgebricksException(e);
                    }
                    tokens1.add(token);
                }
            }
            // pad tokens
            for (; i < length1; i++) {
                tokens1.add(Integer.MAX_VALUE);
            }

            // -- - tokens2 - --
            tokens2.reset();
            evalTokens2.evaluate(tuple, inputVal);

            serList = inputVal.getByteArray();
            startOffset = inputVal.getStartOffset();
            if (serList[startOffset] != ATypeTag.SERIALIZED_ORDEREDLIST_TYPE_TAG
                    && serList[startOffset] != ATypeTag.SERIALIZED_UNORDEREDLIST_TYPE_TAG) {
                throw new AlgebricksException("Scan collection is not defined for values of type"
                        + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(serList[startOffset]));
            }

            int lengthTokens2;
            if (serList[startOffset] == ATypeTag.SERIALIZED_ORDEREDLIST_TYPE_TAG) {
                lengthTokens2 = AOrderedListSerializerDeserializer.getNumberOfItems(inputVal.getByteArray(),
                        startOffset);
                // read tokens
                for (i = 0; i < lengthTokens2; i++) {
                    int itemOffset;
                    int token;

                    try {
                        itemOffset = AOrderedListSerializerDeserializer.getItemOffset(serList, startOffset, i);
                    } catch (AsterixException e) {
                        throw new AlgebricksException(e);
                    }

                    try {
                        token = ATypeHierarchy.getIntegerValueWithDifferentTypeTagPosition(serList, itemOffset,
                                startOffset + 1);
                    } catch (HyracksDataException e) {
                        throw new AlgebricksException(e);
                    }
                    tokens2.add(token);
                }
            } else {
                lengthTokens2 = AUnorderedListSerializerDeserializer.getNumberOfItems(inputVal.getByteArray(),
                        startOffset);
                // read tokens
                for (i = 0; i < lengthTokens2; i++) {
                    int itemOffset;
                    int token;

                    try {
                        itemOffset = AUnorderedListSerializerDeserializer.getItemOffset(serList, startOffset, i);
                    } catch (AsterixException e) {
                        throw new AlgebricksException(e);
                    }

                    try {
                        token = ATypeHierarchy.getIntegerValueWithDifferentTypeTagPosition(serList, itemOffset,
                                startOffset + 1);
                    } catch (HyracksDataException e) {
                        throw new AlgebricksException(e);
                    }
                    tokens2.add(token);
                }
            }
            // pad tokens
            for (; i < length2; i++) {
                tokens2.add(Integer.MAX_VALUE);
            }

            // -- - token prefix - --
            evalTokenPrefix.evaluate(tuple, inputVal);
            int tokenPrefix = 0;

            try {
                tokenPrefix = ATypeHierarchy.getIntegerValue(inputVal.getByteArray(), inputVal.getStartOffset());
            } catch (HyracksDataException e) {
                throw new AlgebricksException(e);
            }

            //
            // -- - position filter - --
            //
            SimilarityMetric.getPartialIntersectSize(tokens1.get(), 0, tokens1.length(), tokens2.get(), 0,
                    tokens2.length(), tokenPrefix, parInter);
            if (similarityFilters.passPositionFilter(parInter.intersectSize, parInter.posXStop, length1,
                    parInter.posYStop, length2)) {

                //
                // -- - suffix filter - --
                //
                if (similarityFilters.passSuffixFilter(tokens1.get(), 0, tokens1.length(), parInter.posXStart,
                        tokens2.get(), 0, tokens2.length(), parInter.posYStart)) {

                    sim = similarityFilters.passSimilarityFilter(tokens1.get(), 0, tokens1.length(),
                            parInter.posXStop + 1, tokens2.get(), 0, tokens2.length(), parInter.posYStop + 1,
                            parInter.intersectSize);
                }
            }
        }

        try {
            writeResult();
        } catch (IOException e) {
            throw new AlgebricksException(e);
        }
        result.set(resultStorage);
    }

    public void writeResult() throws AlgebricksException, IOException {
        res.setValue(sim);
        reusSerde.serialize(res, out);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Main xref</title>
<link type="text/css" rel="stylesheet" href="../../../stylesheet.css" />

View Javadoc

1   package com.goodgames.ponggame;
2
3   /**
4    * Main class, for starting the game.
5    * @author lahtelat
6    */
7   public class Main {
8
9       private static GameWindow gameWindow;
10
11
12
13      /**
14       * void main.
15       * @param args arguments
16       */
17      public static void main(String[] args) {
18          gameWindow = new GameWindow();
19          if (args != null && args.length > 0 && args[0].contains("test")) {
20              gameWindow.setTest();
21          }
22          gameWindow.startGame();
23      }
24
25      public static GameWindow getGameWindow() {
26          return gameWindow;
27      }
28
29  }

Copyright © 2016. All rights reserved.