text:
---
layout: post
title: LearningActiveMq_AbstractOwnableSynchronizer(2)
---

>Connection Hierarchy

###Data structure of AbstractOwnableSynchronizer(2)
   ![](http://xule1991.github.io/images/Java_Concurrent_AbstractOwnableSynchronizer.png)

###build the unsafe object used for CAS
######need objectFiledOffset when CAS is called by unsafe, so we prepare them we building AQS.class object.
```
private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long stateOffset;
    private static final long headOffset;
    private static final long tailOffset;
    private static final long waitStatusOffset;
    private static final long nextOffset;

    static {
        try {
            stateOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("state"));
            headOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("head"));
            tailOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
            waitStatusOffset = unsafe.objectFieldOffset
                (Node.class.getDeclaredField("waitStatus"));
            nextOffset = unsafe.objectFieldOffset
                (Node.class.getDeclaredField("next"));

        } catch (Exception ex) { throw new Error(ex); }
    }

```
######encapsulate CAS operations from sun.misc.Unsafe

```
 /**
     * CAS head field. Used only by enq.
     */
    private final boolean compareAndSetHead(Node update) {
        return unsafe.compareAndSwapObject(this, headOffset, null, update);
    }

    /**
     * CAS tail field. Used only by enq.
     */
    private final boolean compareAndSetTail(Node expect, Node update) {
        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
    }

    /**
     * CAS waitStatus field of a node.
     */
    private static final boolean compareAndSetWaitStatus(Node node,
                                                         int expect,
                                                         int update) {
        return unsafe.compareAndSwapInt(node, waitStatusOffset,
                                        expect, update);
    }

    /**
     * CAS next field of a node.
     */
    private static final boolean compareAndSetNext(Node node,
                                                   Node expect,
                                                   Node update) {
        return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
    }
```

###The queue structure
```
private transient volatile Node head;
private transient volatile Node tail;
private volatile int state;
protected final int getState() {
    return state;
}
protected final void setState(int newState) {
    state = newState;
}
protected final boolean compareAndSetState(int expect, int update) {
    // See below for intrinsics setup to support this
    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}

```
###Inserts node into queue
######If tail == null, means the AQS queue is empty, then thread A trying to init the queue, at this time, if another thread B aslo trying to init queue. because CAS in atomic, so if A succeed, then B will fail because when B call compareAndSetHead, the head, is not null,so,B go to next loop.

######When queue is not empty, there are these variables, node, tail, node.prev, tail.next,it is clear node will operate only in one thread, but tail is shared by multithreads, so node.prev=t is safe, compareAndSetTail(t, node) will ensure the shared variable tail is modified sync, if other also executed node.prev = t, but find t is changed when call compareAndSetTail(t, node), this thread will loop again to set node.prev = t, the lastest t, until t is changed successfully, enq will return the node added to the current thread.
######Key point is tail is shared, the node added is thread safe.
```
private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }
```

###addWaiter
- static final Node SHARED = new Node();
- static final Node EXCLUSIVE = null;

```
 /**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */
    private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }
```
###unparkSuccessor
######waitStatus :
-   static final int CANCELLED =  1;
-   static final int SIGNAL    = -1;
-   static final int CONDITION = -2;
-   static final int PROPAGATE = -3;
-    0:          None of the above

```

    /**
     * Wakes up node's successor, if one exists.
     *
     * @param node the node
     */
    private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
            LockSupport.unpark(s.thread);
    }
```
###doReleaseShared
```
/**
     * Release action for shared mode -- signal successor and ensure
     * propagation. (Note: For exclusive mode, release just amounts
     * to calling unparkSuccessor of head if it needs signal.)
     */
    private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }
```
###doReleaseShared
```
 /**
     * Release action for shared mode -- signal successor and ensure
     * propagation. (Note: For exclusive mode, release just amounts
     * to calling unparkSuccessor of head if it needs signal.)
     */
    private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }
```

###setHeadAndPropagate
```
/**
     * Sets head of queue, and checks if successor may be waiting
     * in shared mode, if so propagating if either propagate > 0 or
     * PROPAGATE status was set.
     *
     * @param node the node
     * @param propagate the return value from a tryAcquireShared
     */
    private void setHeadAndPropagate(Node node, int propagate) {
        Node h = head; // Record old head for check below
        setHead(node);
        /*
         * Try to signal next queued node if:
         *   Propagation was indicated by caller,
         *     or was recorded (as h.waitStatus) by a previous operation
         *     (note: this uses sign-check of waitStatus because
         *      PROPAGATE status may transition to SIGNAL.)
         * and
         *   The next node is waiting in shared mode,
         *     or we don't know, because it appears null
         *
         * The conservatism in both of these checks may cause
         * unnecessary wake-ups, but only when there are multiple
         * racing acquires/releases, so most need signals now or soon
         * anyway.
         */
        if (propagate > 0 || h == null || h.waitStatus < 0) {
            Node s = node.next;
            if (s == null || s.isShared())
                doReleaseShared();
        }
    }

```

###
```
// Utilities for various versions of acquire

    /**
     * Cancels an ongoing attempt to acquire.
     *
     * @param node the node
     */
    private void cancelAcquire(Node node) {
        // Ignore if node doesn't exist
        if (node == null)
            return;

        node.thread = null;

        // Skip cancelled predecessors
        Node pred = node.prev;
        while (pred.waitStatus > 0)
            node.prev = pred = pred.prev;

        // predNext is the apparent node to unsplice. CASes below will
        // fail if not, in which case, we lost race vs another cancel
        // or signal, so no further action is necessary.
        Node predNext = pred.next;

        // Can use unconditional write instead of CAS here.
        // After this atomic step, other Nodes can skip past us.
        // Before, we are free of interference from other threads.
        node.waitStatus = Node.CANCELLED;

        // If we are the tail, remove ourselves.
        if (node == tail && compareAndSetTail(node, pred)) {
            compareAndSetNext(pred, predNext, null);
        } else {
            // If successor needs signal, try to set pred's next-link
            // so it will get one. Otherwise wake it up to propagate.
            int ws;
            if (pred != head &&
                ((ws = pred.waitStatus) == Node.SIGNAL ||
                 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
                pred.thread != null) {
                Node next = node.next;
                if (next != null && next.waitStatus <= 0)
                    compareAndSetNext(pred, predNext, next);
            } else {
                unparkSuccessor(node);
            }

            node.next = node; // help GC
        }
    }

```
###
```
  /**
     * Checks and updates status for a node that failed to acquire.
     * Returns true if thread should block. This is the main signal
     * control in all acquire loops.  Requires that pred == node.prev
     *
     * @param pred node's predecessor holding status
     * @param node the node
     * @return {@code true} if thread should block
     */
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
             * need a signal, but don't park yet.  Caller will need to
             * retry to make sure it cannot acquire before parking.
             */
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

```

###
```
/**
     * Acquires in exclusive uninterruptible mode for thread already in
     * queue. Used by condition wait methods as well as acquire.
     *
     * @param node the node
     * @param arg the acquire argument
     * @return {@code true} if interrupted while waiting
     */
    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
```

###
```
  /**
     * Acquires in exclusive interruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
```

###
```
   /**
     * Acquires in exclusive timed mode.
     *
     * @param arg the acquire argument
     * @param nanosTimeout max wait time
     * @return {@code true} if acquired
     */
    private boolean doAcquireNanos(int arg, long nanosTimeout)
        throws InterruptedException {
        long lastTime = System.nanoTime();
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return true;
                }
                if (nanosTimeout <= 0)
                    return false;
                if (shouldParkAfterFailedAcquire(p, node) &&
                    nanosTimeout > spinForTimeoutThreshold)
                    LockSupport.parkNanos(this, nanosTimeout);
                long now = System.nanoTime();
                nanosTimeout -= now - lastTime;
                lastTime = now;
                if (Thread.interrupted())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
```

###
```
  /**
     * Acquires in shared uninterruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireShared(int arg) {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        if (interrupted)
                            selfInterrupt();
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
```
###
```
  /**
     * Acquires in shared interruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
```
###
```
/**
     * Acquires in shared timed mode.
     *
     * @param arg the acquire argument
     * @param nanosTimeout max wait time
     * @return {@code true} if acquired
     */
    private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
        throws InterruptedException {

        long lastTime = System.nanoTime();
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return true;
                    }
                }
                if (nanosTimeout <= 0)
                    return false;
                if (shouldParkAfterFailedAcquire(p, node) &&
                    nanosTimeout > spinForTimeoutThreshold)
                    LockSupport.parkNanos(this, nanosTimeout);
                long now = System.nanoTime();
                nanosTimeout -= now - lastTime;
                lastTime = now;
                if (Thread.interrupted())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
```
###waitStatus (in Node):
```

1、SIGNAL:后继节点将被或者已经被阻塞,所以当前节点在释放或者取消时,需要unpark它的后继节点。

2、CANCELLED:节点因为超时或者中断被取消。该状态不会再发生变,而且被取消节点对应的线程不会再发生阻塞。

3、CONDITION:该状态仅供在条件队列中的节点使用。当该节点转移到同步队列中时,该状态将被设置为0。

4、PROPAGATE:仅在共享模式下使用。在doReleaseShared()方法中,仅仅会设置头节点的状态为PROPAGATE。

5、0:除以上场景外的其他情况,状态均设置为0。
```

    Learning travel~

2015-12-13


text:
package io.aos.endpoint.socket.bio;

import java.net.*;
import java.io.*;

public class BioTcpEchoClient1a {

    public static void main(String... args) {

        String hostname = "localhost";

        if (args.length > 0) {
            hostname = args[0];
        }

        PrintWriter outputStream = null;
        BufferedReader networkIn = null;
        try {
            Socket theSocket = new Socket(hostname, 7);
            networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
            BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
            outputStream = new PrintWriter(theSocket.getOutputStream());
            System.out.println("Connected to echo server");

            while (true) {
                String theLine = userIn.readLine();
                if (theLine.equals("."))
                    break;
                outputStream.println(theLine);
                outputStream.flush();
                System.out.println(networkIn.readLine());
            }

        } // end try
        catch (IOException e) {
            System.err.println(e);
        }
        finally {
            try {
                if (networkIn != null)
                    networkIn.close();
                if (outputStream != null)
                    outputStream.close();
            }
            catch (IOException e) {
            }
        }

    }

} // end EchoClient

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Prodr. 1:340. 1824

#### Original name
null

### Remarks
null


text:
package com.hazelcast.multimap.impl.txn;

import com.hazelcast.multimap.impl.MultiMapContainer;
import com.hazelcast.multimap.impl.MultiMapDataSerializerHook;
import com.hazelcast.multimap.impl.operations.AbstractKeyBasedMultiMapOperation;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.BackupOperation;
import com.hazelcast.transaction.TransactionException;

import java.io.IOException;

public class TxnRollbackBackupOperation extends AbstractKeyBasedMultiMapOperation implements BackupOperation {

    private String caller;

    public TxnRollbackBackupOperation() {
    }

    public TxnRollbackBackupOperation(String name, Data dataKey, String caller, long threadId) {
        super(name, dataKey);
        this.caller = caller;
        this.threadId = threadId;
    }

    @Override
    public void run() throws Exception {
        MultiMapContainer container = getOrCreateContainerWithoutAccess();
        if (container.isLocked(dataKey) && !container.unlock(dataKey, caller, threadId, getCallId())) {
            throw new TransactionException("Lock is not owned by the transaction! -> " + container.getLockOwnerInfo(dataKey));
        }
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeUTF(caller);
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        caller = in.readUTF();
    }

    @Override
    public int getId() {
        return MultiMapDataSerializerHook.TXN_ROLLBACK_BACKUP;
    }
}


text:
title: Using Passwordless SMS & Email Authentication with Auth0
url: /connections/passwordless
---

<%= include('./_introduction', { withFingerprint: false }) %>

## Tutorials

See the following tutorials for a step-by-step guide on how to implement passwordless authentication for each of these scenarios:

### Passwordless on Single Page Apps

 - [Authenticate users with a one time code via SMS](/connections/passwordless/spa-sms)
 - [Authenticate users with a one time code via e-mail](/connections/passwordless/spa-email-code)
 - [Authenticate users with a magic link via e-mail](/connections/passwordless/spa-email-link)

### Passwordless on Regular Web Apps

 - [Authenticate users with a one time code via SMS](/connections/passwordless/regular-web-app-sms)
 - [Authenticate users with a one time code via e-mail](/connections/passwordless/regular-web-app-email-code)
 - [Authenticate users with a magic link via e-mail](/connections/passwordless/regular-web-app-email-link)

### Passwordless on iOS

 - [Authenticate users with a one time code via SMS](/connections/passwordless/ios-sms-swift)
 - [Authenticate users with a one time code via e-mail](/connections/passwordless/ios-email-swift)
 - [Authenticate users with Touch ID](/connections/passwordless/ios-touch-id-swift)
 - [Authenticate users with Magic Link](/connections/passwordless/ios-magic-link)

### Passwordless on Android

 - [Authenticate users with a one time code via SMS](/connections/passwordless/android-sms)
 - [Authenticate users with a one time code via e-mail](/connections/passwordless/android-email)

### Passwordless API

If you'd like to build your own implementation or understand how this works under the hood, check out the [complete API reference](/auth-api#passwordless).

## Advanced Topics

 - [Send one time codes via your own SMS Gateway](/connections/passwordless/sms-gateway)

## Have Questions?

You may find the answers on the [Auth0 Passwordless FAQ](/connections/passwordless/faq).


text:
@interface SDKLabel (FLExtras)
- (CGSize) sizeThatFitsText:(CGSize) size;
- (CGSize) sizeThatFitsText;
- (CGSize) sizeToFitText;
- (CGSize) sizeToFitText:(CGSize) size;
- (void) drawUnderline:(CGRect) inRect
	withColor:(SDKColor*) color
	withLineWidth:(CGFloat) width;

- (void)sizeToFitWidth:(CGFloat)fixedWidth;
- (CGSize)sizeThatFitsWidth:(CGFloat)fixedWidth;

- (void) addGlow;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (C) 2012 Facebook, Inc.

    Licensed under the Apache License, Version 2.0 (the "License"); you may
    not use this file except in compliance with the License. You may obtain
    a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    License for the specific language governing permissions and limitations
    under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.facebook.swift</groupId>
    <artifactId>swift-root</artifactId>
    <version>0.12.0-SNAPSHOT</version>
  </parent>

  <artifactId>swift-generator</artifactId>
  <packaging>jar</packaging>
  <name>${project.artifactId}</name>
  <description>Code generator for Thrift IDLs</description>

  <properties>
    <fb.main.basedir>${project.parent.basedir}</fb.main.basedir>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.facebook.swift</groupId>
      <artifactId>swift-annotations</artifactId>
    </dependency>

    <dependency>
      <groupId>com.facebook.swift</groupId>
      <artifactId>swift-idl-parser</artifactId>
    </dependency>

    <dependency>
      <groupId>com.facebook.swift</groupId>
      <artifactId>swift-codec</artifactId>
    </dependency>

    <dependency>
      <groupId>com.facebook.swift</groupId>
      <artifactId>swift-service</artifactId>
    </dependency>

      <dependency>
      <groupId>org.antlr</groupId>
      <artifactId>stringtemplate</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.code.findbugs</groupId>
      <artifactId>annotations</artifactId>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
package org.apache.maven.model.plugin;

import org.apache.maven.model.Build;
import org.apache.maven.model.InputLocation;
import org.apache.maven.model.InputSource;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginManagement;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.model.ReportSet;
import org.apache.maven.model.Reporting;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelProblemCollector;
import org.apache.maven.model.building.ModelProblemCollectorRequest;
import org.apache.maven.model.building.ModelProblem.Severity;
import org.apache.maven.model.building.ModelProblem.Version;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.Xpp3Dom;

/**
 * Handles conversion of the <reporting> section into the configuration of Maven Site Plugin 3.x,
 * i.e. reportPlugins and outputDirectory parameters.
 *
 * @author Benjamin Bentmann
 */
@Component( role = ReportingConverter.class )
public class DefaultReportingConverter
    implements ReportingConverter
{
    private final InputLocation location;
    {
        String modelId = "org.apache.maven:maven-model-builder:"
            + this.getClass().getPackage().getImplementationVersion() + ":reporting-converter";
        InputSource inputSource = new InputSource();
        inputSource.setModelId( modelId );
        location = new InputLocation( -1, -1, inputSource );
        location.setLocation( 0, location );
    }

    @Override
    public void convertReporting( Model model, ModelBuildingRequest request, ModelProblemCollector problems )
    {
        Reporting reporting = model.getReporting();

        if ( reporting == null )
        {
            return;
        }

        Build build = model.getBuild();

        if ( build == null )
        {
            build = new Build();
            model.setBuild( build );
            model.setLocation( "build", location );
        }

        Plugin sitePlugin = findSitePlugin( build );

        if ( sitePlugin == null )
        {
            sitePlugin = new Plugin();
            sitePlugin.setArtifactId( "maven-site-plugin" );
            sitePlugin.setLocation( "artifactId", location );
            PluginManagement pluginManagement = build.getPluginManagement();
            if ( pluginManagement == null )
            {
                pluginManagement = new PluginManagement();
                build.setPluginManagement( pluginManagement );
            }
            pluginManagement.addPlugin( sitePlugin );
        }

        Xpp3Dom configuration = (Xpp3Dom) sitePlugin.getConfiguration();

        if ( configuration == null )
        {
            configuration = new Xpp3Dom( "configuration", location );
            sitePlugin.setConfiguration( configuration );
        }

        Xpp3Dom reportPlugins = configuration.getChild( "reportPlugins" );

        if ( reportPlugins != null )
        {
            // new-style report configuration already present: warn since this new style has been deprecated
            // in favor of classical reporting section MSITE-647 / MSITE-684
            problems.add( new ModelProblemCollectorRequest( Severity.WARNING, Version.BASE )
                    .setMessage( "Reporting configuration should be done in <reporting> section, "
                          + "not in maven-site-plugin <configuration> as reportPlugins parameter." )
                    .setLocation( sitePlugin.getLocation( "configuration" ) ) );
            return;
        }

        if ( configuration.getChild( "outputDirectory" ) == null )
        {
            addDom( configuration, "outputDirectory", reporting.getOutputDirectory(),
                    reporting.getLocation( "outputDirectory" ) );
        }

        reportPlugins = new Xpp3Dom( "reportPlugins", location );
        configuration.addChild( reportPlugins );

        boolean hasMavenProjectInfoReportsPlugin = false;

        /* waiting for MSITE-484 before deprecating <reporting> section
        if ( !reporting.getPlugins().isEmpty()
            && request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1 )
        {

            problems.add( new ModelProblemCollectorRequest( Severity.WARNING, Version.V31 )
                    .setMessage( "The <reporting> section is deprecated, please move the reports to the <configuration>"
                                 + " section of the new Maven Site Plugin." )
                    .setLocation( reporting.getLocation( "" ) ) );
        }*/

        for ( ReportPlugin plugin : reporting.getPlugins() )
        {
            Xpp3Dom reportPlugin = convert( plugin );
            reportPlugins.addChild( reportPlugin );

            if ( !reporting.isExcludeDefaults() && !hasMavenProjectInfoReportsPlugin
                && "org.apache.maven.plugins".equals( plugin.getGroupId() )
                && "maven-project-info-reports-plugin".equals( plugin.getArtifactId() ) )
            {
                hasMavenProjectInfoReportsPlugin = true;
            }
        }

        if ( !reporting.isExcludeDefaults() && !hasMavenProjectInfoReportsPlugin )
        {
            Xpp3Dom dom = new Xpp3Dom( "reportPlugin", location );

            addDom( dom, "groupId", "org.apache.maven.plugins" );
            addDom( dom, "artifactId", "maven-project-info-reports-plugin" );

            reportPlugins.addChild( dom );
        }
    }

    private Plugin findSitePlugin( Build build )
    {
        for ( Plugin plugin : build.getPlugins() )
        {
            if ( isSitePlugin( plugin ) )
            {
                return plugin;
            }
        }

        PluginManagement pluginManagement = build.getPluginManagement();
        if ( pluginManagement != null )
        {
            for ( Plugin plugin : pluginManagement.getPlugins() )
            {
                if ( isSitePlugin( plugin ) )
                {
                    return plugin;
                }
            }
        }

        return null;
    }

    private boolean isSitePlugin( Plugin plugin )
    {
        return "maven-site-plugin".equals( plugin.getArtifactId() )
            && "org.apache.maven.plugins".equals( plugin.getGroupId() );
    }

    private Xpp3Dom convert( ReportPlugin plugin )
    {
        Xpp3Dom dom = new Xpp3Dom( "reportPlugin", plugin.getLocation( "" ) );

        addDom( dom, "groupId", plugin.getGroupId(), plugin.getLocation( "groupId" ) );
        addDom( dom, "artifactId", plugin.getArtifactId(), plugin.getLocation( "artifactId" ) );
        addDom( dom, "version", plugin.getVersion(), plugin.getLocation( "version" ) );

        Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration();
        if ( configuration != null )
        {
            configuration = new Xpp3Dom( configuration );
            dom.addChild( configuration );
        }

        if ( !plugin.getReportSets().isEmpty() )
        {
            Xpp3Dom reportSets = new Xpp3Dom( "reportSets", plugin.getLocation( "reportSets" ) );
            for ( ReportSet reportSet : plugin.getReportSets() )
            {
                Xpp3Dom rs = convert( reportSet );
                reportSets.addChild( rs );
            }
            dom.addChild( reportSets );
        }

        return dom;
    }

    private Xpp3Dom convert( ReportSet reportSet )
    {
        Xpp3Dom dom = new Xpp3Dom( "reportSet", reportSet.getLocation( "" ) );

        InputLocation idLocation = reportSet.getLocation( "id" );
        addDom( dom, "id", reportSet.getId(), idLocation == null ? location : idLocation );

        Xpp3Dom configuration = (Xpp3Dom) reportSet.getConfiguration();
        if ( configuration != null )
        {
            configuration = new Xpp3Dom( configuration );
            dom.addChild( configuration );
        }

        if ( !reportSet.getReports().isEmpty() )
        {
            InputLocation location = reportSet.getLocation( "reports" );
            Xpp3Dom reports = new Xpp3Dom( "reports", location );
            int n = 0;
            for ( String report : reportSet.getReports() )
            {
                addDom( reports, "report", report, ( location == null ) ? null : location.getLocation( n++ ) );
            }
            dom.addChild( reports );
        }

        return dom;
    }

    private void addDom( Xpp3Dom parent, String childName, String childValue )
    {
        addDom( parent, childName, childValue, location );
    }

    private void addDom( Xpp3Dom parent, String childName, String childValue, InputLocation location )
    {
        if ( StringUtils.isNotEmpty( childValue ) )
        {
            parent.addChild( newDom( childName, childValue, location ) );
        }
    }

    private Xpp3Dom newDom( String name, String value, InputLocation location )
    {
        Xpp3Dom dom = new Xpp3Dom( name, location );
        dom.setValue( value );
        return dom;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/Administrator/Desktop/ONOFFZONE0617/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.2.0/res/values-w720dp/values-w720dp.xml -->
    <eat-comment/>
    <bool name="abc_action_bar_expanded_action_views_exclusive">false</bool>
</resources>


text:
/* RAND.C - Random number generation module. */

/* Copyright (c) 1995, 1996, 2000, 2001 by Radford M. Neal
 *
 * Permission is granted for anyone to copy, use, modify, or distribute this
 * program and accompanying programs and documents for any purpose, provided
 * this copyright notice is retained and prominently displayed, along with
 * a note saying that the original programs are available from Radford Neal's
 * web page, and note is made of any changes made to the programs.  The
 * programs and documents are distributed without any warranty, express or
 * implied.  As the programs were written for research purposes only, they have
 * not been tested to the degree that would be advisable in any important
 * application.  All use of these programs is entirely at the user's own risk.
 */

/* NOTE:  See rand.html for documentation on these procedures. */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#include "rand.h"

/* This module uses the 'drand48' pseudo-random number generator found
   on most Unix systems, the output of which is combined with a file
   of real random numbers.

   Many of the methods used in this module may be found in the following
   reference:

      Devroye, L. (1986) Non-Uniform Random Variate Generation,
        New York: Springer-Verlag.

   The methods used here are not necessarily the fastest available.  They're
   selected to be reasonably fast while also being easy to write.
*/

/* CONSTANT PI.  Defined here if not in <math.h>. */

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

/* TABLES OF REAL RANDOM NUMBERS.  A file of 100000 real random numbers
   (NOT pseudo-random) is used in conjunction with pseudo-random numbers
   for extra insurance.  These are employed in the form of five tables
   of 5000 32-bit integers.

   The file must be located at the path given by RAND_FILE, which should
   be defined on the "cc" command line. */

#define Table_size 5000			/* Number of words in each table */

static int rn[N_tables][Table_size];	/* Random number tables */

/* STATE OF RANDOM NUMBER GENERATOR. */

static int initialized = 0;		/* Has module been initialized? */

static rand_state state0;		/* Default state structure */

static rand_state *state;		/* Pointer to current state */

/* INITIALIZE MODULE.  Sets things up using the default state structure,
   set as if rand_seed had been called with a seed of one. */

static void initialize (void)
{
  int i, j, k, w;
  char b;
  FILE *f;

  if (!initialized)
  {
    f = fopen(RAND_FILE,"rb");

    if (f==NULL)
    { fprintf(stderr,"Can't open file of random numbers (%s)\n",RAND_FILE);
      exit(1);
    }

    for (i = 0; i<N_tables; i++)
    { for (j = 0; j<Table_size; j++)
      { w = 0;
        for (k = 0; k<4; k++)
        { if (fread(&b,1,1,f)!=1)
          { fprintf(stderr,"Error reading file of random numbers (%s)\n",
                            RAND_FILE);
            exit(1);
          }
          w = (w<<8) | (b&0xff);
        }
        rn[i][j] = w;
      }
    }

    state = &state0;

    initialized = 1;

    rand_seed(1);
  }
}

/* SET CURRENT STATE ACCORDING TO SEED. */

void rand_seed
( int seed
)
{
  int j;

  if (!initialized) initialize();

  state->seed = seed;

  state->state48[0] = seed>>16;
  state->state48[1] = seed&0xffff;
  state->state48[2] = rn[0][(seed&0x7fffffff)%Table_size];

  for (j = 0; j<N_tables; j++)
  { state->ptr[j] = seed%Table_size;
    seed /= Table_size;
  }
}

/* SET STATE STRUCTURE TO USE. */

void rand_use_state
( rand_state *st
)
{
  if (!initialized) initialize();

  state = st;
}

/* RETURN POINTER TO CURRENT STATE. */

rand_state *rand_get_state (void)
{
  if (!initialized) initialize();

  return state;
}

/* GENERATE RANDOM 31-BIT INTEGER.  Not really meant for use outside this
   module. */

int rand_word(void)
{
  int v;
  int j;

  if (!initialized) initialize();

  v = nrand48(state->state48);

  for (j = 0; j<N_tables; j++)
  { v ^= rn[j][state->ptr[j]];
  }

  for (j = 0; j<N_tables && state->ptr[j]==Table_size-1; j++)
  { state->ptr[j] = 0;
  }

  if (j<N_tables)
  { state->ptr[j] += 1;
  }

  return v & 0x7fffffff;
}

/* GENERATE UNIFORMLY FROM [0,1). */

double rand_uniform (void)
{
  return (double)rand_word() / (1.0+(double)0x7fffffff);
}

/* GENERATE UNIFORMLY FORM (0,1). */

double rand_uniopen (void)
{
  return (0.5+(double)rand_word()) / (1.0+(double)0x7fffffff);
}

/* GENERATE RANDOM INTEGER FROM 0, 1, ..., (n-1). */

int rand_int
( int n
)
{
  return (int) (n * rand_uniform());
}

/* GENERATE INTEGER FROM 0, 1, ..., (n-1), WITH GIVEN DISTRIBUTION. */

int rand_pickd
( double *p,
  int n
)
{
  double t, r;
  int i;

  t = 0;
  for (i = 0; i<n; i++)
  { if (p[i]<0) abort();
    t += p[i];
  }

  if (t<=0) abort();

  r = t * rand_uniform();

  for (i = 0; i<n; i++)
  { r -= p[i];
    if (r<0) return i;
  }

  /* Return value with non-zero probability if we get here due to roundoff. */

  for (i = 0; i<n; i++)
  { if (p[i]>0) return i;
  }

  abort();
}

/* SAME PROCEDURE AS ABOVE, BUT WITH FLOAT ARGUMENT. */

int rand_pickf
( float *p,
  int n
)
{
  double t, r;
  int i;

  t = 0;
  for (i = 0; i<n; i++)
  { if (p[i]<=0) abort();
    t += p[i];
  }

  if (t<=0) abort();

  r = t * rand_uniform();

  for (i = 0; i<n; i++)
  { r -= p[i];
    if (r<0) return i;
  }

  /* Return value with non-zero probability if we get here due to roundoff. */

  for (i = 0; i<n; i++)
  { if (p[i]>0) return i;
  }

  abort();
}

/* GAUSSIAN GENERATOR.  Done by using the Box-Muller method, but only one
   of the variates is retained (using both would require saving more state).
   See Devroye, p. 235.

   As written, should never deliver exactly zero, which may sometimes be
   helpful. */

double rand_gaussian (void)
{
  double a, b;

  a = rand_uniform();
  b = rand_uniopen();

  return cos(2.0*M_PI*a) * sqrt(-2.0*log(b));
}

/* EXPONENTIAL GENERATOR.  See Devroye, p. 29.  Written so as to never
   return exactly zero. */

double rand_exp (void)
{
  return -log(rand_uniopen());
}

/* LOGISTIC GENERATOR.  Just inverts the CDF. */

double rand_logistic (void)
{ double u;
  u = rand_uniopen();
  return log(u/(1-u));
}

/* CAUCHY GENERATOR.  See Devroye, p. 29. */

double rand_cauchy (void)
{
  return tan (M_PI * (rand_uniopen()-0.5));
}

/* GAMMA GENERATOR.  Generates a positive real number, r, with density
   proportional to r^(a-1) * exp(-r).  See Devroye, p. 410 and p. 420.
   Things are fiddled to avoid ever returning a value that is very near
   zero. */

double rand_gamma
( double a
)
{
  double b, c, X, Y, Z, U, V, W;

  if (a<0.00001)
  { X = a;
  }

  else if (a<=1)
  {
    U = rand_uniopen();
    X = rand_gamma(1+a) * pow(U,1/a);
  }

  else if (a<1.00001)
  { X = rand_exp();
  }

  else
  {
    b = a-1;
    c = 3*a - 0.75;

    for (;;)
    {
      U = rand_uniopen();
      V = rand_uniopen();

      W = U*(1-U);
      Y = sqrt(c/W) * (U-0.5);
      X = b+Y;

      if (X>=0)
      {
        Z = 64*W*W*W*V*V;

        if (Z <= 1 - 2*Y*Y/X || log(Z) <= 2 * (b*log(X/b) - Y)) break;
      }
    }
  }

  return X<1e-30 && X<a ? (a<1e-30 ? a : 1e-30) : X;
}

/* BETA GENERATOR. Generates a real number, r, in (0,1), with density
   proportional to r^(a-1) * (1-r)^(b-1).  Things are fiddled to avoid
   the end-points, and to make the procedure symmetric between a and b. */

double rand_beta
( double a,
  double b
)
{
  double x, y, r;

  do
  { x = rand_gamma(a);
    y = rand_gamma(b);
    r = 1.0 + x/(x+y);
    r = r - 1.0;
  } while (r<=0.0 || r>=1.0);

  return r;
}


text:
import sys
import os
import platform

EXT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, 'external_libs'))
if not os.path.exists(EXT_PATH):
    raise Exception('Wrong path to external libs: %s' % EXT_PATH)

CLIENT_UTILS_MODULES = [
                         {'name': 'scapy-2.3.1', 'py-dep': True},
                         {'name': 'texttable-0.8.4'},
                        ]

def generate_module_path (module, is_python3, is_64bit, is_ucs2):
    platform_path = [module['name']]

    if module.get('py-dep'):
        platform_path.append('python3' if is_python3 else 'python2')

    if module.get('arch-dep'):
        platform_path.append('ucs2' if is_ucs2 else 'ucs4')
        platform_path.append('64bit' if is_64bit else '32bit')

    return os.path.normcase(os.path.join(EXT_PATH, *platform_path))

def import_module_list(modules_list):

    # platform data
    is_64bit   = platform.architecture()[0] == '64bit'
    is_python3 = (sys.version_info >= (3, 0))
    is_ucs2    = (sys.maxunicode == 65535)

    # regular modules
    for p in modules_list:
        full_path = generate_module_path(p, is_python3, is_64bit, is_ucs2)

        if not os.path.exists(full_path):
            print("Unable to find required module library: '{0}'".format(p['name']))
            print("Please provide the correct path using TREX_STL_EXT_PATH variable")
            print("current path used: '{0}'".format(full_path))
            exit(1)
        if full_path not in sys.path:
            sys.path.insert(1, full_path)

import_module_list(CLIENT_UTILS_MODULES)


text:
<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">

    <title>shorty-creator-view</title>

    <script src="../bower_components/webcomponentsjs/webcomponents-lite.js"></script>
    <script src="../bower_components/web-component-tester/browser.js"></script>

    <!-- Import the element to test -->
    <link rel="import" href="../src/shorty-creator-view.html">
  </head>
  <body>
    <test-fixture id="basic">
      <template>
        <shorty-creator-view></shorty-creator-view>
      </template>
    </test-fixture>

    <script>
      suite('shorty-creator-view tests', function() {
        var home;

        setup(function() {
          home = fixture('basic');
        });

        test('Text in header should be Shorten a URL', function() {
          var header = Polymer.dom(home.root).querySelector('.card h1');
          assert.equal(header.textContent, 'Shorten a URL');
        });
      });
    </script>
  </body>
</html>


text:
% FILE: sample_td_script.m
%
% PURPOSE: Matlab script to build up the files listed below into a valid
%          training data file, for use in page classification
%
% USEAGE: matlab -nojvm -nosplash < sample_td_script.m > /dev/null
%
% NOTES: All data is saved to the output file outfile

# change the output file below
outfile = './sample.data';

# list the path and filename of each page to be included in training data
# (enclose each in single quotes)
imgs = {
'/h/42/scottl/research/READY_TO_TAG/allwein00a.aa.tif'
'/h/42/scottl/research/READY_TO_TAG/allwein00a.ab.tif'
'/h/42/scottl/research/READY_TO_TAG/allwein00a.ac.tif'
}

s = create_training_data(imgs);
dump_training_data(s, outfile);


text:
package edu.regis.mvanhemert.ice.analyzer.service.topic;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import edu.regis.mvanhemert.ice.common.Article;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.util.Span;

public abstract class TopicFinder {

	private final Log LOGGER = LogFactory.getLog(TopicFinder.class);

	protected NameFinderME nameFinder;
	protected boolean modelLoaded;

	public abstract void findTopics(final Article article);

	protected boolean loadModel(final String modelFile) {
		LOGGER.info("Loading name finder model " + modelFile);

		try {
			Resource resource = new ClassPathResource(modelFile);
			TokenNameFinderModel model = new TokenNameFinderModel(resource.getInputStream());

			nameFinder = new NameFinderME(model);
			modelLoaded = true;

			LOGGER.debug("Model loaded");
		} catch (IOException e) {
			LOGGER.error("Failed to load NameFinder model", e);
		}

		return modelLoaded;
	}

	protected void executeTopicSearch(final Article article) {
		boolean first = true;

		for (List<String> tokenizedSentence : article.getTokenizedSentences()) {
			String[] tokenizedSentenceArray = tokenizedSentence.toArray(new String[0]);
			Span[] locationSpans = nameFinder.find(tokenizedSentenceArray);

			for (Span locationSpan : locationSpans) {
				StringBuilder sb = new StringBuilder();
				int index = locationSpan.getStart();

				sb.append(tokenizedSentence.get(index));
				index++;

				while (index < locationSpan.getEnd()) {
					sb.append(" ");
					sb.append(tokenizedSentence.get(index));
					index++;
				}

				String topic = sb.toString();

				addTopic(article.getTopicMap(), topic);
				if (first && !article.getTitleTopics().contains(topic))
					article.getTitleTopics().add(topic);

				first = false;
			}
		}

		// Ensure we have an easy-to-query set of topics
		article.getSimpleTopics().addAll(article.getTopicMap().keySet());

		// Fix the 'title topic' list
		fixTitleTopics(article);

		nameFinder.clearAdaptiveData();
	}

	private void addTopic(final Map<String, Set<String>> topicMap, final String newTopic) {
		Iterator<String> topicIterator = topicMap.keySet().iterator();

		boolean added = false;

		while (topicIterator.hasNext()) {
			String topic = topicIterator.next();

			if (newTopic.equals(topic)) {
				added = true;
				break;
			} else if (topic.contains(newTopic)) {
				added = true;
				topicMap.get(topic).add(newTopic);
			} else if (newTopic.contains(topic)) {
				added = true;
				topicMap.put(newTopic, topicMap.get(topic));
				topicMap.remove(topic);
				topicMap.get(newTopic).add(topic);
				break;
			}
		}

		if (!added)
			topicMap.put(newTopic, new HashSet<>());
	}

	private void fixTitleTopics(final Article article) {
		Set<String> newTitleTopics = new HashSet<>();
		Set<String> oldTitleTopics = new HashSet<>();

		for (String topic : article.getTitleTopics()) {
			if (article.getTopicMap().keySet().contains(topic))
				continue;

			for (Map.Entry<String, Set<String>> entry : article.getTopicMap().entrySet()) {
				if (entry.getValue().contains(topic)) {
					newTitleTopics.add(entry.getKey());
					oldTitleTopics.add(topic);
					break;
				}
			}
		}

		article.getTitleTopics().removeAll(oldTitleTopics);
		article.getTitleTopics().addAll(newTitleTopics);
	}
}


text:
$buildCmd = "C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe";
$buildArgs = @(
              "ICSharpCode.SharpZipLib.sln"
              "/l:C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll",
              "/m",
              "/p:UseSharedCompilation=false",
              "/p:Configuration=Release",
              "/p:Platform=Any CPU");

# If build is not a scheduled one, then simply build the project with MSBuild.
if ($env:APPVEYOR_SCHEDULED_BUILD -ne "True") {
  & $buildCmd $buildArgs
#  & nuget pack <project_file> -OutputDirectory <temp_path>
  return  # exit script
}

# Else, build project with Coverity Scan.
$publishCoverityExe = $env:APPVEYOR_BUILD_FOLDER + "\packages\PublishCoverity.0.11.0\tools\PublishCoverity.exe";
"Building project with Coverity Scan..."
& cov-build --dir Documentation\cov-int $buildCmd $buildArgs;

# Compress scan data.
& $publishCoverityExe compress -o Documentation\coverity.zip -i Documentation\cov-int;

# Upload scan data.
& $publishCoverityExe publish -z Documentation\coverity.zip -r McNeight/SharpZipLib -t $env:Coverity_Token -e $env:Coverity_Email -d "AppVeyor scheduled build";


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="header_fragment" type="id"/>
</resources>


text:
<?php
	ob_start();
	session_start();
	include 'testmysql.php';
	if (!(isset($_SESSION['user_id']))||trim($_SESSION['user_id'])=="") {
		session_regenerate_id();
		$redirect_url=$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
		$_SESSION['redirect_url']=$redirect_url;
		session_write_close();
		header('Location:login.php');
		exit();
	}
	else
	{
		$id=$_SESSION['user_id'];
		$i=mysqli_query($con,"SELECT * FROM usermyca WHERE id='$id'");
		$j=mysqli_fetch_array($i);
		$status=$j['admin'];
		if ($status!=1)
		{
			header('Location:unauthorised_access.php');
			exit();
			# code...
		}
	}
?>
<!DOCTYPE html>

	<title>
		Hello Admin!
	</title>

		<a href="add_problem.php?author=<?php echo $_SESSION['username'];?>">Add a problem

		<a href="add_editorial.php?editorialist=<?php echo $_SESSION['username'];?>">Write Editorial

		View as user

		<a href='create.php?creator=<?php echo $_SESSION['username'];?>'>Create a new contest


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.messaging.testing;

import android.os.Bundle;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.firebase.analytics.connector.AnalyticsConnector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * A fast, deterministic, fake implementation of AnalyticsConnector to be used for unit testing.
 *
 * <p>It provides support for logging events, setting/getting user properties, and setting/getting
 * conditional user properties.
 */
public class FakeAnalyticsConnector implements AnalyticsConnector, AnalyticsValidator {

  private static final String CAMPAIGN_INFO_SOURCE = "_cis";
  private static final String FCM_CONNECTOR_CAMPAIGN = "fcm_integration";
  private final List<AnalyticsValidator.LoggedEvent> events = new ArrayList<>();
  private final Map<String, Object> userProperties = new HashMap<>();
  private final List<ConditionalUserProperty> conditionalUserProperties = new ArrayList<>();

  @Override
  public AnalyticsConnectorHandle registerAnalyticsConnectorListener(
      String origin, AnalyticsConnectorListener listener) {
    return null;
  }

  @Override
  public void logEvent(String origin, String name, Bundle params) {
    if (origin.equals("fcm")) {
      params.putString(CAMPAIGN_INFO_SOURCE, FCM_CONNECTOR_CAMPAIGN);
    }
    events.add(AnalyticsValidator.LoggedEvent.create(origin, name, params));
  }

  @Override
  public void setUserProperty(String origin, String name, Object value) {
    userProperties.put(name, value);
  }

  @Override
  public Map<String, Object> getUserProperties(boolean includeInternal) {
    ImmutableMap.Builder<String, Object> filteredProperties = ImmutableMap.builder();
    for (Entry<String, Object> property : userProperties.entrySet()) {
      if (includeInternal || !property.getKey().startsWith("_")) {
        filteredProperties.put(property);
      }
    }
    return filteredProperties.build();
  }

  @Override
  public void setConditionalUserProperty(ConditionalUserProperty conditionalUserProperty) {
    conditionalUserProperties.add(conditionalUserProperty);
  }

  @Override
  public void clearConditionalUserProperty(
      String userPropertyName, String clearEventName, Bundle clearEventParams) {
    for (Iterator<ConditionalUserProperty> iterator = conditionalUserProperties.iterator();
        iterator.hasNext(); ) {
      ConditionalUserProperty conditionalUserProperty = iterator.next();
      if (conditionalUserProperty.name.equals(userPropertyName)) {
        iterator.remove();
        logEvent(conditionalUserProperty.origin, clearEventName, clearEventParams);
      }
    }
  }

  @Override
  public int getMaxUserProperties(String origin) {
    return 25;
  }

  @Override
  public List<ConditionalUserProperty> getConditionalUserProperties(
      String origin, String propertyNamePrefix) {
    ImmutableList.Builder<ConditionalUserProperty> filteredProperties = ImmutableList.builder();
    for (ConditionalUserProperty property : conditionalUserProperties) {
      if (property.origin.equals(origin) && property.name.startsWith(propertyNamePrefix)) {
        filteredProperties.add(property);
      }
    }
    return filteredProperties.build();
  }

  @Override
  public List<ConditionalUserProperty> getConditionalUserProperties() {
    return conditionalUserProperties;
  }

  @Override
  public ImmutableList<AnalyticsValidator.LoggedEvent> getLoggedEvents() {
    return ImmutableList.copyOf(events);
  }

  @Override
  public ImmutableList<String> getLoggedEventNames() {
    ImmutableList.Builder<String> names = ImmutableList.builder();
    for (AnalyticsValidator.LoggedEvent event : events) {
      names.add(event.getName());
    }
    return names.build();
  }

  @Override
  public void reset() {
    events.clear();
    userProperties.clear();
    conditionalUserProperties.clear();
  }
}


text:
angular.module('mwUI.Inputs')

  .directive('mwCheckboxGroup', function (i18n) {
    return {
      restrict: 'A',
      scope: {
        mwCollection: '=',
        mwOptionsCollection: '=',
        mwOptionsLabelKey: '@',
        mwOptionsLabelI18nPrefix: '@',
        mwRequired: '=',
        mwDisabled: '='
      },
      templateUrl: 'uikit/mw-inputs/directives/templates/mw_checkbox_group.html',
      link: function (scope) {
        var getModelIdAttr = function () {
          return scope.mwCollection.model.prototype.idAttribute;
        };

        scope.getLabel = function (model) {
          var modelAttr = model.get(scope.mwOptionsLabelKey);

          if (modelAttr) {
            if (scope.mwOptionsLabelI18nPrefix) {
              return i18n.get(scope.mwOptionsLabelI18nPrefix + '.' + modelAttr);
            } else {
              return modelAttr;
            }
          }
        };

        scope.isOptionDisabled = function (model) {
          return model.selectable.isDisabled();
        };

        scope.isSelected = function (model) {
          return !!scope.mwCollection.get(model.get(getModelIdAttr()));
        };

        scope.toggleModel = function (model) {
          var existingModel = scope.mwCollection.findWhere(model.toJSON());
          if (existingModel) {
            scope.mwCollection.remove(existingModel);
          } else {
            scope.mwCollection.add(model.toJSON());
          }
        };

        if (! (scope.mwCollection instanceof Backbone.Collection) ) {
          throw new Error('[mwCheckboxGroup] The attribute mwCollection is required and has to be an instanceof Backbone Collection');
        }

        if ( !(scope.mwOptionsCollection instanceof Backbone.Collection) ) {
          throw new Error('[mwCheckboxGroup] The attribute mwOptionsCollection is required and has to be an instanceof Backbone Collection');
        }
      }
    };
  });


text:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _

class VouchersDashboardConfig(AppConfig):
    label = 'vouchers_dashboard'
    name = 'oscar.apps.dashboard.vouchers'
    verbose_name = _('Vouchers dashboard')


text:
layout: layout
title: "Ben Newton - Front End Engineer"
---

Hi, I'm Ben Newton. I'm a Front End Engineer. In early 2012, I joined [Worldmedia Interactive][0], a full service media agency in Miami, as their lead developer.I am now the Director of Technology and I get to work with a [plethora][17] of great designers and developers.  See some of our work below.  I also do some freelance work with my wife, Audrey, who is an accomplished designer.  If you have a project you would like to discuss, [contact me](/about).

This website is my playground and I am constantly trying out different hosts and technologies and it is never really complete.  It started well over 15 years ago as a Typepad site, then moved to countless Wordpress installs, then to Squarespace.  For the past few months now I have been using Jekyll and Github Pages.  I'm already planning my next move to a Node.js backend and Angular.js front end.  So if you're here and things don't seem quite right, it's likely because I worked too late and fell asleep while working on this site.  I will get back to it soon.. I always do.

##Projects at Worldmedia Interactive

###Current Projects

#####Norwegian Cruise Line - Norwegian Escape Website - Norwegian Cruise Line

_Front End: HTML, CSS, Angular.js, Greensock Back End: Wordpress Custom Back End_

#####Enterprise Rent-a-Car's European Website - Enterprise Rent-a-Car

_Front End: HTML, CSS, Angular.js Back End: Node.js and Mongo (MEAN STACK)_

###Past Projects

#####Alamo Rent-a-Car Latin American Specials - Alamo Rent-a-Car

_Front End: Javascript_

#####Aston 65 Reasons - Aston Resorts and Hotels

_Front End: Javascript_

#####Ipremios - Batanga Media

_Front End: HTML, CSS, Angular.js  Back End:Node.js and Firebase Database._

#####worldmedia.net - Worldmedia Interactive

_Front End: HTML, CSS, Javascript_

#####TorontoEscapes Flight Deals - Air Canada, Toronto Tourism

_Front End: HTML, CSS, Angular.js Back End: Node.js_

#####Norewegian Breakaway Microsite (Retired) - Norwegian Cruise Line

_Front End: Some HTML, CSS and Javascript (Timeline, Spinning Ship, Conversation Panels)_

#####Norwegian Getaway Microsite (Retired) - Norwegian Cruise Line

_Front End: Some HTML, CSS and Javascript (Timeline, Spinning Ship, Conversation Panels)_

#####Norwegian Escape Microsite (Under Development) - Norwegian Cruise Line

_Full site design & development_

#####[MSC Divina LP][9] - MSC Cruise Line

_Front End: HTML, CSS_

#####TAMOffers.com (Retired) - TAM Airlines

_Front End: HTML, CSS_

#####LANPass Mobile Landing Page - LAN Airlines

_Front End: HTML, CSS_

#####[Cayman Yellow Pages Landing Page][11] - Cayman Yellow Pages

_Front End: HTML, CSS_

#####[TiempoTimepieces.com][18] - Turley Timepieces

_Front End: HTML, CSS, Angular.js Back End:Classic ASP, (Yes, Classic ASP)_

###Projects I've recently worked on independently

#####[Pure Brazilian][15]

_Front End: HTML, CSS Javascript  Back End:Wordpress_

#####[My Amazing Blow Dry Secret][16]

_Front End: HTML, CSS Javascript  Back End:Wordpress_

[0]: http://worldmedia.ne
[2]: http://getaway.ncl.com
[4]: http://torontoespaces.com
[5]:
[7]:
[8]:
[9]: http://wmmsc.s3-website-us-east-1.amazonaws.com/DivinaLP/
[10]:
[11]: http://caymanyp.com/distribution/
[12]: https://s3.amazonaws.com/wmsaa/landing_page_10092013/index.html
[14]: http://www.flysaaspecials.com/
[15]: http://purebrazilian.com/
[16]: http://myamazingblowdrysecret.com/
[17]: http://www.youtube.com/watch?v=-mTUmczVdik
[18]: http://tiempotimepieces.com/


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
   xmlns:android="http://schemas.android.com/apk/res/android"
   package="pepper.app"
   android:installLocation="auto"

   android:versionCode="1" android:versionName="0.1"
   >

  <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <application android:name="App" android:label="Pepper" android:icon="@drawable/icon" >
    <!-- android:debuggable="true" android:largeHeap="true" -->
      <activity android:name="PepperApp"
                android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                android:label="Pepper"
                >
        <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
  </application>
</manifest>


text:
package org.apache.flink.formats.avro.typeutils;

import org.apache.flink.api.common.typeutils.SerializerTestBase;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.formats.avro.generated.User;
import org.apache.flink.formats.avro.utils.TestDataGenerator;

import java.util.Random;

/** Tests for the {@link AvroSerializer} that test specific avro types. */
public class AvroSerializerTest extends SerializerTestBase<User> {

    @Override
    protected TypeSerializer<User> createSerializer() {
        return new AvroSerializer<>(User.class);
    }

    @Override
    protected int getLength() {
        return -1;
    }

    @Override
    protected Class<User> getTypeClass() {
        return User.class;
    }

    @Override
    protected User[] getTestData() {
        final Random rnd = new Random();
        final User[] users = new User[20];

        for (int i = 0; i < users.length; i++) {
            users[i] = TestDataGenerator.generateRandomUser(rnd);
        }

        return users;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>类 org.apache.giraph.bsp.ApplicationState的使用 (Apache Giraph Core 1.0.0 API)</title>
<meta name="date" content="2013-11-04">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

类 org.apache.giraph.bsp.ApplicationState
的使用

使用ApplicationState的程序包

程序包
说明

org.apache.giraph.bsp

Package of generic bulk synchronous processing objects.

org.apache.giraph.master

Package of all the master related things.

org.apache.giraph.bsp中ApplicationState的使用

返回ApplicationState的org.apache.giraph.bsp中的方法

限定符和类型
方法和说明

static ApplicationState
ApplicationState.valueOf(String name)

返回带有指定名称的该类型的枚举常量。

static ApplicationState[]
ApplicationState.values()

按照声明该枚举类型的常量的顺序, 返回
包含这些常量的数组。

参数类型为ApplicationState的org.apache.giraph.bsp中的方法

限定符和类型
方法和说明

void
CentralizedServiceMaster.setJobState(ApplicationState state,
           long applicationAttempt,
           long desiredSuperstep)

If the master decides that this job doesn't have the resources to
 continue, it can fail the job.

org.apache.giraph.master中ApplicationState的使用

参数类型为ApplicationState的org.apache.giraph.master中的方法

限定符和类型
方法和说明

void
BspServiceMaster.setJobState(ApplicationState state,
           long applicationAttempt,
           long desiredSuperstep)

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

Copyright © 2011-2013 The Apache Software Foundation. All Rights Reserved.


text:
RSSNZB_DIR = '/etc/rssnzb'

# Where to put downloaded NZB files
DOWNLOAD_DIR = '/mnt/media/upload'

from urllib import urlretrieve
from xmlrpclib import ServerProxy
from time import sleep
import feedparser
import simplejson as json
import re
from pprint import pprint

dl = open('%s/downloaded' % RSSNZB_DIR, 'r')
downloaded = []
for line in dl.readlines():
    downloaded.append(line[:-1])
dl.close()

def download_nzbs(urls, hella):
    entries = []
    for url in urls:
        feed = feedparser.parse(url)
        entries += feed['entries']
    downloaded = json.load(file('%s/downloaded' % RSSNZB_DIR, 'r'))
    queue = {}

    for entry in entries:
        if entry['report_progress'] != 'Report is complete':
            continue
        if entry['title'] in downloaded:
            existing = downloaded[entry['title']]
            if int(entry['report_size']) <= int(existing['report_size']):
                continue
        queue[entry['title']] = entry['report_id']
        downloaded[entry['title']] = entry

    for title in queue:
        print 'Downloading', title
        hella.enqueuenewzbin(queue[title])
        sleep(1)

    serial = {}
    for key in downloaded:
        serial[key] = {}
        for k in downloaded[key]:
            if k in ['report_id', 'report_size', 'title']:
                serial[key][k] = downloaded[key][k]
    json.dump(serial, file('%s/downloaded' % RSSNZB_DIR, 'w'), indent=4)

def main():
    hella = ServerProxy('http://hellanzb:massive@localhost:8760/')

    download_nzbs([x.rstrip('\r\n') for x in file('%s/savedsearches' % RSSNZB_DIR, 'r').readlines()], hella)

if __name__ == '__main__':
    main()


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="jp.co.recruit_mp.android.rmp_appiraterkit">

    <application/>

</manifest>


text:
package test.design.pattern.structure;

/**
 * from http://www.cnblogs.com/java-my-life/archive/2012/04/13/2442795.html
 */
public class testAdapter {
    public interface Target {
        /**
         * 这是源类Adaptee也有的方法
         */
        public void sampleOperation1();

        /**
         * 这是源类Adapteee没有的方法
         */
        public void sampleOperation2();
    }

    public class Adaptee {

        public void sampleOperation1() {
        }

    }

    public class AdapterClass extends Adaptee implements Target {
        /**
         * 由于源类Adaptee没有方法sampleOperation2() 因此适配器补充上这个方法
         */
        @Override
        public void sampleOperation2() {
            // 写相关的代码
        }

    }

    public class AdapterObject {
        private Adaptee adaptee;

        public AdapterObject(Adaptee adaptee) {
            this.adaptee = adaptee;
        }

        /**
         * 源类Adaptee有方法sampleOperation1 因此适配器类直接委派即可
         */
        public void sampleOperation1() {
            this.adaptee.sampleOperation1();
        }

        /**
         * 源类Adaptee没有方法sampleOperation2 因此由适配器类需要补充此方法
         */
        public void sampleOperation2() {
            // 写相关的代码
        }
    }

}


text:
using __gnu_cxx::power;
#else
template <class Value>
Value power(Value value, int n)
{
    return pow(value, n);
}
#endif

namespace graph_tool
{
using namespace boost;

#ifdef HAVE_SPARSEHASH
using google::dense_hash_set;
#else
using std::unordered_set;
#endif

// calculates the number of triangles to which v belongs
template <class Graph>
pair<int,int>
get_triangles(typename graph_traits<Graph>::vertex_descriptor v, const Graph &g)
{
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

#ifdef HAVE_SPARSEHASH
    typedef dense_hash_set<vertex_t, std::hash<vertex_t>> set_t;
#else
    typedef unordered_set<vertex_t> set_t;
#endif

    set_t neighbour_set;

#ifdef HAVE_SPARSEHASH
     neighbour_set.set_empty_key(numeric_limits<vertex_t>::max());
     neighbour_set.resize(out_degree(v, g));
#endif

    size_t triangles = 0;

    typename graph_traits<Graph>::adjacency_iterator n, n_end;
    for (tie(n, n_end) = adjacent_vertices(v, g); n != n_end; ++n)
    {
        if (*n == v) // no self-loops
            continue;
        neighbour_set.insert(*n);
    }

    for (tie(n, n_end) = adjacent_vertices(v, g); n != n_end; ++n)
    {
        typename graph_traits<Graph>::adjacency_iterator n2, n2_end;
        for (tie(n2, n2_end) = adjacent_vertices(*n, g); n2 != n2_end; ++n2)
        {
            if (*n2 == *n) // no self-loops
                continue;
            if (neighbour_set.find(*n2) != neighbour_set.end())
                ++triangles;
        }
    }

    size_t k = out_degree(v, g);
    return make_pair(triangles/2,(k*(k-1))/2);
}

// retrieves the global clustering coefficient
struct get_global_clustering
{
    template <class Graph>
    void operator()(const Graph& g, double& c, double& c_err) const
    {
        size_t triangles = 0, n = 0;
        pair<size_t, size_t> temp;

        int i, N = num_vertices(g);

        #pragma omp parallel for default(shared) private(i,temp) \
            schedule(runtime) if (N > 100) reduction(+:triangles, n)
        for (i = 0; i < N; ++i)
        {
            typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);
            if (v == graph_traits<Graph>::null_vertex())
                continue;

            temp = get_triangles(v, g);
            triangles += temp.first;
            n += temp.second;
        }
        c = double(triangles) / n;

        // "jackknife" variance
        c_err = 0.0;
        double cerr = 0.0;

        #pragma omp parallel for default(shared) private(i,temp) \
            schedule(runtime) if (N > 100) reduction(+:cerr)
        for (i = 0; i < N; ++i)
        {
            typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);
            if (v == graph_traits<Graph>::null_vertex())
                continue;

            temp = get_triangles(v, g);
            double cl = double(triangles - temp.first) / (n - temp.second);

            cerr += power(c - cl, 2);
        }
        c_err = sqrt(cerr);
    }
};

// sets the local clustering coefficient to a property
struct set_clustering_to_property
{
    template <class Graph, class ClustMap>
    void operator()(const Graph& g, ClustMap clust_map) const
    {
        typedef typename property_traits<ClustMap>::value_type c_type;
        typename get_undirected_graph<Graph>::type ug(g);
        int i, N = num_vertices(g);

        #pragma omp parallel for default(shared) private(i) schedule(runtime) if (N > 100)
        for (i = 0; i < N; ++i)
        {
            typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);
            if (v == graph_traits<Graph>::null_vertex())
                continue;

            pair<size_t,size_t> triangles = get_triangles(v,ug); // get from ug
            double clustering = (triangles.second > 0) ?
                double(triangles.first)/triangles.second :
                0.0;

            clust_map[v] = c_type(clustering);
        }
    }

    template <class Graph>
    struct get_undirected_graph
    {
        typedef typename mpl::if_
           <std::is_convertible<typename graph_traits<Graph>::directed_category,
                                directed_tag>,
            const UndirectedAdaptor<Graph>,
            const Graph& >::type type;
    };
};

} //graph-tool namespace

#endif // GRAPH_CLUSTERING_HH


text:
<?xml version="1.0" ?>
<tei xml:space="preserve">
	<teiHeader>
		<fileDesc xml:id="PMC5221852"/>
	</teiHeader>
	<text xml:lang="en">
		<front>

	<note type="doctype">Editorial<lb/></note>

	<reference>Gut and Liver, Vol. 11, No. 1, January 2017, pp. 3-4<lb/></reference>

	<note type="copyright">This is an Open Access article distributed under the terms of the Creative Commons Attribution Non-Commercial License (http://creativecommons.org/licenses/by-nc/4.0)<lb/> which permits unrestricted non-commercial use, distribution, and reproduction in any medium, provided the original work is properly cited.<lb/></note>

	Correspondence to:
	<byline>
	<docAuthor>Chang Soo Eun<lb/></docAuthor>
	</byline>

	<byline>
	<affiliation>Department of Internal Medicine, Hanyang University Guri Hospital,</affiliation>
	</byline>

	<address>153 Gyeongchun-ro, Guri 11923, Korea<lb/></address>

	Tel: <phone>+82-31-560-2228</phone>, Fax: +82-31-555-2998, E-mail:
	<email>cseun@hanyang.ac.kr<lb/></email>

	<idno>pISSN 1976-2283</idno>
	<idno>eISSN 2005-1212</idno>

	<idno>https://doi.org/10.5009/gnl16574<lb/></idno>

	<docTitle>
	<titlePart>Is the Therapeutic Drug Monitoring of Anti-TNF Agents Necessary in Korean<lb/> Inflammatory Bowel Disease Patients?<lb/></titlePart>
	</docTitle>

	<byline>
	<docAuthor>Chang Soo Eun<lb/></docAuthor>
	</byline>

	<byline>
	<affiliation>Department of Internal Medicine, Hanyang University Guri Hospital,</affiliation>
	</byline>

	<address>Guri, Korea<lb/></address>

	<reference>See "Clinical Use of Measuring Trough Levels and Antibodies against Infliximab in Patients with Pediatric Inflammatory<lb/> Bowel Disease" by So Yoon Choi, et al. on page 55, Vol. 11. No. 1, 2017</reference>

		</front>
	</text>
</tei>


text:
package io.github.swagger2markup.markup.builder.internal;

/**
 * @author Robert Winkler
 */
public interface Markup {
    String toString();
}


text:
ViewController::ViewController(int th, Tilemap* tm) {
    int tw = th * 2;

    tilemap = tm;
    iso = new IsometricD(th, tw);

    tileCounter = tilemap->getTilesCounter();

    status = new int*[tilemap->getWidth()];
    for (int r = 0; r < tilemap->getWidth(); r++) {
        status[r] = new int[tilemap->getHeight()];
        for (int c = 0; c < tilemap->getHeight(); c++) {
            status[r][c] = STATUS_NORMAL;
        }
    }

    screenHeightOffset = -250;
    screenWidthOffset = -50;

    tileSelected = 0;
    brushSize = 0;
    mouseButtoDown = MOUSE_NONE;
}

ViewController::~ViewController() {
    delete iso;
}

Tilemap* ViewController::getTilemap() {
    return tilemap;
}

int ViewController::getTileSelected() {
    return tileSelected;
}

void ViewController::setTileSelected(int tile) {
    tileSelected = tile;
}

void ViewController::setBrushSize(int size) {
    if(size < 0) return;
    if(size % 2 != 0) size += 1;
    brushSize = size;
}

int ViewController::getBrushSize() {
    return brushSize;
}

void ViewController::createMap(void (*createTile)(int, int, int, int, int, color)) {
    int x, y;
    for (int r = 0; r < tilemap->getHeight(); r++) {
        for (int c = 0; c < tilemap->getWidth(); c++) {
            int tile = tilemap->getTile(c, r);
            if(tile == -1) continue;

            iso->mapToScreenPosition(c, r, x, y);
            color col = selectColor(c, r);
            tile = selectTile(tile, c, r);
            createTile(x - screenWidthOffset, y - screenHeightOffset, tile, iso->getTileHeight(), iso->getTileWidth(), col);
        }
    }
}

void ViewController::moveMap(direction dir) {
    switch (dir) {
    case NORTH:
        screenHeightOffset += iso->getTileHeight() / 2;
        break;
    case SOUTH:
        screenHeightOffset -= iso->getTileHeight() / 2;
        break;
    case EAST:
        screenWidthOffset += iso->getTileWidth() / 2;
        break;
    case WEST:
        screenWidthOffset -= iso->getTileWidth() / 2;
        break;
    }
}

void ViewController::addZoom(int mag) {
    std::cout << ":: ViewController :: Adding " << mag << " zoom" << '\n';
    iso->setTileSize(iso->getTileHeight() + mag);
}

void ViewController::removeZoom(int mag) {
    std::cout << ":: ViewController :: Removing " << mag << " zoom" << '\n';
    iso->setTileSize(iso->getTileHeight() - mag);
}

void ViewController::mouseUp(int xclick, int yclick) {
    mouseButtoDown = MOUSE_NONE;
}

void ViewController::mouseDown(int xclick, int yclick) {
    std::cout << ":: ViewController :: Click on " << xclick << ", " << yclick << '\n';

    int mc, mr;
    iso->screenToMapPosition(xclick + screenWidthOffset, yclick + screenHeightOffset, mc, mr);

    int halfSize = brushSize / 2;
    for (int x = -halfSize; x <= halfSize; x++) {
        for (int y = -halfSize; y <= halfSize; y++) {
            tilemap->setTile(tileSelected, mc + x, mr + y);
        }
    }
    mouseButtoDown = MOUSE_LEFT;
}

void ViewController::rightMouseUp(int xclick, int yclick) {
    mouseButtoDown = MOUSE_NONE;
}

void ViewController::rightMouseDown(int xclick, int yclick) {
    std::cout << ":: ViewController :: Click on " << xclick << ", " << yclick << '\n';

    int mc, mr;
    iso->screenToMapPosition(xclick + screenWidthOffset, yclick + screenHeightOffset, mc, mr);
    tileSelected = tilemap->getTile(xMouse, yMouse);
    mouseButtoDown = MOUSE_RIGHT;
}

void ViewController::mouseDrag(int xmouse, int ymouse) {
    iso->screenToMapPosition(xmouse + screenWidthOffset, ymouse + screenHeightOffset, xMouse, yMouse);
    if(mouseButtoDown == MOUSE_LEFT) {
        tilemap->setTile(tileSelected, xMouse, yMouse);
    }
}

void ViewController::setMousePosition(int xmouse, int ymouse) {
    iso->screenToMapPosition(xmouse + screenWidthOffset, ymouse + screenHeightOffset, xMouse, yMouse);
}

color ViewController::selectColor(int c, int r) {
    color col = {255, 255, 255};
    if(tileSelected == -1 && c == xMouse && r == yMouse) {
        col = {200, 200, 255};
    }
    return col;
}

int ViewController::selectTile(int tile, int c, int r) {
    if(c == xMouse && r == yMouse) {
        return tileSelected;
    }
    int halfSize = brushSize / 2;
    for (int x = -halfSize; x <= halfSize; x++) {
        for (int y = -halfSize; y <= halfSize; y++) {
            if(c == xMouse + x && r == yMouse + y) return tileSelected;
        }
    }
    return tile;
}


text:
define('test/transform/App',
[
    'jquery'
    , 'underscore'
    , 'backbone'
    , 'test/transform/controller/Router'
],
function($, _, Backbone, Router){
    function initialize(){
        console.log('init');

        var router = new Router({});
        Backbone.history.start();
    }

    return {
        initialize:initialize
    }
})


text:
package ri

/* Procedural */
func (r *Ri) Procedural(args RtStringArray, bound RtBound, subdividefunc RtProcSubdivFunc, freefunc RtProcFreeFunc) error {
	return r.writef("Procedural", subdividefunc, args, bound)
}


text:
namespace Mordor {

class GzipStream : public ZlibStream
{
public:
    GzipStream(Stream::ptr parent, int level, int windowBits, int memlevel, Strategy strategy, bool own = true)
        : ZlibStream(parent, own, GZIP, level, windowBits, memlevel, strategy)
    {}

    GzipStream(Stream::ptr parent, bool own = true)
        : ZlibStream(parent, own, GZIP)
    {}
};

}

#endif


text:
  {% include icon-youtube.svg %}
  {{ include.label | default: include.username }}


text:
diretorio_atual="$(dirname "$0")"
# Carregando as parametrizacoes do script
source "$diretorio_atual/controlador_parametrizacao.sh"

# Carregando as funcoes uteis
source "$diretorio_atual/controlador_funcoes_uteis.sh"

# Carregando as funcoes
source "$diretorio_atual/controlador_funcoes.sh"

# Comandos utilizados
source "$diretorio_atual/controlador_comandos.sh"

function MenuPrincipal(){
  AbsorveBufferTeclado
  echo "------------------------------------------"
  echo "---> $NOME_APP"
  echo "------------------------------------------"
  echo "Opções:"
  echo
  echo "1. Verificar dependencias"
  echo "2. Instalar"
  echo "3. Reinstalar"
  echo "4. Iniciar $NOME_APP"
  echo "5. Parar $NOME_APP"
  echo "6. Verificar status  $NOME_APP"
  echo "="
  echo "(I)nformações sobre este script"
  echo "(Q)uit / (S)air"
  echo
  echo -n "Qual a opção desejada? "
  read opcao
  case $opcao in
    1) Dependencias verificar;read; Main ;;
    2) Instalar;read; Main ;;

    I|i) Info ;read; Main ;;
    Q|q|S|s) exit ;;
    *) echo "Opção desconhecida." ; $CMD_SLEEP 2 ; Main ;;
  esac
}

#######################
# CHMADA DA PRINCIPAL #
#######################
function Main(){
    $CMD_CLEAR
    AbsorveBufferTeclado
    MenuPrincipal
}

Main


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>poc-apresentacao-da-ferramenta</id>
    <dbId>1268</dbId>
    <nome>POC - Apresentação da Ferramenta</nome>
    <sigla>poc</sigla>
    <nomes-populares>
        <item id="1214">poc</item>
        <item id="1215">Apresentação</item>
        <item id="1216">Apresentação da Ferramenta</item>
    </nomes-populares>
    <descricao>Serviço para demonstrar o que é possível  fazer com o Lecom BPM</descricao>
    <contato></contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>true</servico-digital>
    <link-servico-digital>https://mpdg-hom-ps.lecom.com.br/processos/iniciar</link-servico-digital>
    <solicitantes>
        <solicitante id="1223">
            <tipo>Qualquer cidadão</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <ate max="3" unidade="dias-uteis"/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="2838">
            <titulo>Solicitar</titulo>
            <descricao></descricao>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3036" tipo="web">
                        <descricao>web</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/14" dbId="37524">
        <nomeOrgao>Ministério da Agricultura, Pecuária e Abastecimento (MAPA)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="1" idServicoSegmento="2946">Cidadãos</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Administração</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="3646">poc</item>
        <item id="3647">apresentação</item>
        <item id="3648">demonstração</item>
        <item id="3649">ferramentas</item>
    </palavras-chave>
</servico>


text:
BroadcastManager *BroadcastManager::s_instance;

BroadcastManager *BroadcastManager::getInstance()
{
    if (s_instance == 0) {
        s_instance = new BroadcastManager();
    }
    return s_instance;
}

void BroadcastManager::cleanUp()
{
    if (s_instance != 0) {
        delete s_instance;
        s_instance = 0;
    }
}

BroadcastManager::BroadcastManager(QObject *parent) : QObject(parent)
{

}

void BroadcastManager::sendBroadcast(int signalId, const QVariant &data)
{
    emit _newBroadcastSignal(signalId, data);
}

void BroadcastManager::registerHandler(const QObject *receiver, const char *slot)
{
    connect(this, SIGNAL(_newBroadcastSignal(int,QVariant)), receiver, slot);
}

void BroadcastManager::unregisterHandler(const QObject *receiver, const char *slot)
{
    disconnect(this, SIGNAL(_newBroadcastSignal(int,QVariant)), receiver, slot);
}


text:
import { Address } from '../../validation/services/types';
import * as R from 'ramda';

export const addressIsEmpty = (address: Address): boolean => {
    return R.all(R.isEmpty, R.map(R.trim, [address.address, address.city, address.postalCode]));
};


text:
"""
The deprecated Linear solvers (:mod:`qiskit.algorithms.linear_solvers`)
=======================================================================
It  contains classical and quantum algorithms to solve systems of linear equations such as
:class:`~qiskit.algorithms.HHL`.
Although the quantum algorithm accepts a general Hermitian matrix as input, Qiskit's default
Hamiltonian evolution is exponential in such cases and therefore the quantum linear solver will
not achieve an exponential speedup.
Furthermore, the quantum algorithm can find a solution exponentially faster in the size of the
system than their classical counterparts (i.e. logarithmic complexity instead of polynomial),
meaning that reading the full solution vector would kill such speedup (since this would take
linear time in the size of the system).
Therefore, to achieve an exponential speedup we can only compute functions from the solution
vector (the so called observables) to learn information about the solution.
Known efficient implementations of Hamiltonian evolutions or observables are contained in the
following subfolders:

`Matrices`_
  A placeholder for efficient implementations of the Hamiltonian evolution of particular types of
  matrices.

`Observables`_
  A placeholder for efficient implementations of functions that can be computed from the solution
  vector to a system of linear equations.

.. currentmodule:: qiskit.algorithms.linear_solvers

Linear Solvers
==============

.. autosummary::
   :toctree: ../stubs/
   :nosignatures:

   LinearSolver
   LinearSolverResult
   HHL
   NumPyLinearSolver

Matrices
========

.. autosummary::
   :toctree: ../stubs/
   :nosignatures:

   LinearSystemMatrix
   NumPyMatrix
   TridiagonalToeplitz

Observables
===========

.. autosummary::
    :toctree: ../stubs/

    LinearSystemObservable
    AbsoluteAverage
    MatrixFunctional

"""

from .hhl import HHL
from .numpy_linear_solver import NumPyLinearSolver
from .linear_solver import LinearSolver, LinearSolverResult
from .matrices import LinearSystemMatrix, NumPyMatrix, TridiagonalToeplitz
from .observables import LinearSystemObservable, AbsoluteAverage, MatrixFunctional

__all__ = [
    "HHL",
    "NumPyLinearSolver",
    "LinearSolver",
    "LinearSolverResult",
    "LinearSystemMatrix",
    "NumPyMatrix",
    "TridiagonalToeplitz",
    "LinearSystemObservable",
    "AbsoluteAverage",
    "MatrixFunctional",
]


text:
#include "caffe2/operators/local_response_normalization_op.h"
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"

#include "caffe2/mkl/mkl_utils.h"

#ifdef CAFFE2_HAS_MKL_DNN

namespace caffe2 {
namespace mkl {

template <typename T>
class MKLLRNOp final : public LRNOpBase<T, MKLContext> {
 public:
  MKLLRNOp(const OperatorDef& operator_def, Workspace* ws)
      : LRNOpBase<T, MKLContext>(operator_def, ws) {}

  bool RunOnDeviceWithOrderNCHW() override;
  bool RunOnDeviceWithOrderNHWC() override;

 private:
  vector<TIndex> cached_input_dims_;
  LayoutWrapper<T> workspace_layout_;
  std::unique_ptr<MKLWorkspace<T>> workspace_buffer_;
  PrimitiveWrapper<T> primitive_;
  MKLMemory<T> buffer_;
  void* resources_[dnnResourceNumber] = {0};
};

template <>
bool MKLLRNOp<float>::RunOnDeviceWithOrderNCHW() {
  auto& X = OperatorBase::Input<MKLMemory<float>>(0);
  MKLMemory<float>* Y = OperatorBase::Output<MKLMemory<float>>(0);

  bool dims_changed;
  CHECK_INPUT_DIMS(X, dims_changed);
  if (dims_changed) {
    size_t dim = X.ndim();
    CAFFE_ENFORCE(4 == dim);

    // Create main primitive.
    primitive_.Reset(
        dnnLRNCreateForward_F32,
        nullptr,
        X.layout(),
        size_,
        alpha_,
        beta_,
        bias_);

    Y->Reset(X.dims(), primitive_, dnnResourceDst);
    buffer_.Reset(X.dims(), primitive_, dnnResourceDst, true);

    workspace_layout_.Reset(primitive_, dnnResourceWorkspace);
    workspace_buffer_ =
        caffe2::make_unique<MKLWorkspace<float>>(workspace_layout_);
  }

  // Try to share from the output: this allows us to avoid unnecessary copy
  // operations, if the output is already allocated and is having the same
  // layout as the buffer has.
  buffer_.ShareFrom(*Y);
  resources_[dnnResourceSrc] = X.buffer();
  resources_[dnnResourceDst] = buffer_.buffer();
  resources_[dnnResourceWorkspace] = workspace_buffer_->buffer();
  MKLDNN_SAFE_CALL(mkl::dnnExecute<float>(primitive_, resources_));
  buffer_.CopyTo(Y, primitive_, dnnResourceDst);
  return true;
}

template <>
bool MKLLRNOp<float>::RunOnDeviceWithOrderNHWC() {
  CAFFE_NOT_IMPLEMENTED;
}

} // namespace mkl

REGISTER_MKL_OPERATOR(LRN, mkl::MKLLRNOp<float>);

} // namespace caffe2

#endif // CAFFE2_HAS_MKL_DNN


text:
import {
  macroCondition,
  dependencySatisfies,
  importSync,
} from '@embroider/macros';

if (macroCondition(dependencySatisfies('ember-qunit', '*'))) {
  let { module, test } = importSync('qunit').default;

  module('Qunit | #2: Module With Multiple Tests');

  test('#1', function (assert) {
    assert.ok(true);
  });
  test('#2', function (assert) {
    assert.ok(true);
  });
  test('#3', function (assert) {
    assert.ok(true);
  });
  test('#4', function (assert) {
    assert.ok(true);
  });
  test('#5', function (assert) {
    assert.ok(true);
  });
  test('#6', function (assert) {
    assert.ok(true);
  });
  test('#7', function (assert) {
    assert.ok(true);
  });
  test('#8', function (assert) {
    assert.ok(true);
  });
  test('#9', function (assert) {
    assert.ok(true);
  });
}


text:
import Ember from 'ember';

import FormDataAdapterMixin from 'ember-cli-form-data/mixins/form-data-adapter';

var adapter;

module('FormDataAdapterMixin', {
  setup: function() {
    adapter = Ember.Object.extend({
      ajaxOptions: function(url, type, options) {
        return options;
      }
    }, FormDataAdapterMixin).create();

    window.FormData = function() {
      this.data = [];
      this.append = function(key, value) {
        var object = {};
        object[key] = value;
        this.data.push(object);
      };
    };
  }
});

test('Default FormData Types', function(assert) {
  assert.deepEqual(adapter.get('formDataTypes'), ['POST', 'PUT', 'PATCH']);
});

test('#ajaxOptions', function(assert) {
  var testFormData = new window.FormData();

  testFormData.append('post[id]', 1);
  testFormData.append('post[title]', 'Rails is Omakase');

  var options = {
    data: {
      post: {
        id: 1,
        title: 'Rails is Omakase'
      }
    }
  };

  var hash = adapter.ajaxOptions('/', 'POST', options);

  assert.deepEqual(hash.data, testFormData);
});

test("Don't modify the hash for requests outside formDataTypes", function(assert) {
  var options = {
    data: {
      post: {
        id: 1,
        title: 'Rails is Omakase'
      }
    }
  };

  var hash = adapter.ajaxOptions('/', 'GET', options);

  assert.deepEqual(hash.data, {
    post: {
      id: 1,
      title: 'Rails is Omakase'
    }
  });
});

test('Falsey key gets saved', function(assert) {
  var testFormData = new window.FormData();

  testFormData.append('post[preferred]', false);

  var options = {
    data: {
      post: {
        preferred: false
      }
    }
  };

  var hash = adapter.ajaxOptions('/', 'POST', options);

  assert.deepEqual(hash.data, testFormData);
});

test('Default disableRoot', function(assert) {
  assert.deepEqual(adapter.get('disableRoot'), false);
});

test('#ajaxOptions should exclude root when disableRoot is true', function(assert) {
  var testFormData = new window.FormData();

  // Setup expected form data; note the lack of the 'post' root (post[id])
  testFormData.append('id', 1);
  testFormData.append('title', 'Rails is Omakase');

  var options = {
    data: {
      post: {
        id: 1,
        title: 'Rails is Omakase'
      }
    }
  };

  adapter.set('disableRoot', true);

  var hash = adapter.ajaxOptions('/', 'POST', options);

  assert.deepEqual(hash.data, testFormData);
});


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>EuroZoneGlobal.com</title>
	<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>">

			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
				Toggle navigation

			</button>
			<a class="navbar-brand" href="<?php echo base_url(); ?>index.php/home">EuroZoneGlobal.com

				<?php if ($this->session->userdata('login')){ ?>

Hello <?php echo $this->session->userdata('uname'); ?>

<a href="<?php echo base_url(); ?>index.php/home/logout">Log Out

				<?php } else { ?>

<a href="<?php echo base_url(); ?>index.php/login">Login

<a href="<?php echo base_url(); ?>index.php/signup">Signup

				<?php } ?>

		<?php $attributes = array("name" => "loginform");
			echo form_open("login/index", $attributes);?>
			<legend>Login</legend>

				Email-ID
				<input class="form-control" name="email" placeholder="Enter Email-ID" type="text" value="<?php echo set_value('email'); ?>" />
				<?php echo form_error('email'); ?>

				Password
				<input class="form-control" name="password" placeholder="Password" type="password" value="<?php echo set_value('password'); ?>" />
				<?php echo form_error('password'); ?>

				<button name="submit" type="submit" class="btn btn-info">Login</button>
				<button name="cancel" type="reset" class="btn btn-info">Cancel</button>

		<?php echo form_close(); ?>
		<?php echo $this->session->flashdata('msg'); ?>

		New User? <a href="<?php echo base_url("index.php/signup"); ?>">Sign Up Here