text:
package wangmin.modbus.util;

import com.google.common.collect.Lists;
import net.wimpi.modbus.net.TCPMasterConnection;

import java.util.List;

/**
 * Created by wm on 2017/1/3.
 */
public class ModbusConnPool {
    private volatile boolean flag = true;

    private final String host;
    public String getHost() {return host;}
    private final int port;
    public int getPort() {return port;}

    private final List<TCPMasterConnection> availConns = Lists.newArrayList();
    private final List<TCPMasterConnection> usingConns = Lists.newArrayList();

    private TCPMasterConnection connOneWithRetry() throws Exception {
        int retry = 0;
        while (true) {
            try {
                return ModbusUtils.connectionModbusSlave(host, port);
            } catch (Exception e) {
                ++retry;
                if (retry >= 3) {
                    throw e;
                }
            }
        }
    }

    public ModbusConnPool(String host, int port, int initialConnectionCount) throws Exception {
        this.host = host;
        this.port = port;

        while (availConns.size() < initialConnectionCount) {
            TCPMasterConnection conn;
            try {
                conn = connOneWithRetry();
            } catch (Exception e) {
                if (!availConns.isEmpty()) {
                    return;
                } else {
                    throw e;
                }
            }

            availConns.add(conn);
        }
    }

    /**
     * 检查连接池中的可用连接的连接状态
     * */
    public synchronized void checkConnStatus() {
        if (!flag) return;

        if (!availConns.isEmpty()) {
            for (int i = availConns.size()-1; i >= 0; --i) {
                TCPMasterConnection conn = availConns.get(i);
                if (!conn.isConnected()) {
                    availConns.remove(i);
                }
            }
        }
    }

    /**
     * 从连接池获取一个连接
     * */
    public synchronized TCPMasterConnection getOneConn() {
        if (!flag) return null;

        if (!availConns.isEmpty()) {
            int lastIdx = availConns.size()-1;
            TCPMasterConnection conn = availConns.get(lastIdx);
            availConns.remove(lastIdx);

            usingConns.add(conn);

            return conn;
        } else {
            try {
                TCPMasterConnection conn = connOneWithRetry();
                usingConns.add(conn);

                return conn;
            } catch (Exception e) {
                return null;
            }
        }
    }

    /**
     * 归还连接到连接池
     * */
    public synchronized void returnOneConn(TCPMasterConnection conn) {
        availConns.add(conn);

        usingConns.remove(conn);
    }

    /**
     * 关闭连接池所有连接
     * */
    public void closeAllConn() {
        flag = false;

        // 先关闭可用连接
        synchronized (this) {
            for (int i = 0; i < availConns.size(); ++i) {
                availConns.get(i).close();
            }
            availConns.clear();

            if (usingConns.isEmpty())
                return;
        }

        // 等待3秒
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
        }

        // 强制关闭所有连接
        synchronized (this) {
            for (int i = 0; i < availConns.size(); ++i) {
                availConns.get(i).close();
            }
            for (int i = 0; i < usingConns.size(); ++i) {
                usingConns.get(i).close();
            }
        }
    }
}


text: package linux

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Rackspace
{
    public static class TestData
    {
        public static string GenerateName()
        {
            return $"ci-test-{Guid.NewGuid()}";
        }
    }
}


text:
<?php

namespace League\CommonMark\Inline\Parser;

use League\CommonMark\ContextInterface;
use League\CommonMark\Inline\Element\Html;
use League\CommonMark\InlineParserContext;
use League\CommonMark\Util\RegexHelper;

class RawHtmlParser extends AbstractInlineParser
{
    /**
     * @return string[]
     */
    public function getCharacters()
    {
        return ['<'];
    }

    /**
     * @param ContextInterface    $context
     * @param InlineParserContext $inlineContext
     *
     * @return bool
     */
    public function parse(ContextInterface $context, InlineParserContext $inlineContext)
    {
        $cursor = $inlineContext->getCursor();
        if ($m = $cursor->match(RegexHelper::getInstance()->getHtmlTagRegex())) {
            $inlineContext->getInlines()->add(new Html($m));

            return true;
        }

        return false;
    }
}


text:
/*
------------------------------------------------------------
Expanse
http://expanse.io
Content management for the web deisgner, by the web designer
Written, with love, by Ian Tearle @iantearle
Based on original work by Nate Cavanaugh and Jason Morrison
All rights reserved.

Javascript only CSS
============================================================
*/

/*
------------------------------------------------------------
Global styles
============================================================
*/
.hidden {
	display:none;
}

.visible {
	display:block;
}

.hilite {
}

#content .formatSettings {
}

.formatSettingsL {
}

/*
------------------------------------------------------------
Tooltips (w/ Javascript)
============================================================
*/
.hasHelp {
	display:none;
}

.helpContents {
	margin:0;
	padding:7px;
	position:absolute;
	top:-1000px;
	left:-1000px;
	border:1px solid #999;
	z-index:100;
	background-color:#fff;
	-moz-border-radius:5px;
	width:250px;
	font-size:12px;
}

.hasHelp {
	display:inline;
	cursor:pointer;
}

#categoriesList .hasHelp {
	padding-top:0;
	display:inline;
	cursor:pointer;
}

#vanilla .hasHelp {
	padding-top:.7em;
	display:inline;
	cursor:pointer;
	float:left;
	margin:.4em;
}

#bannedIPs.hasHelp,#bannedWords.hasHelp {
	padding-bottom:8em;
	display:inline;
	cursor:pointer;
}

blockquote.helpContents a {
	text-decoration:none;
}

/*
------------------------------------------------------------
Waiting Message Styles
============================================================
*/
#overlay {
	background:#000;
	filter:alpha(opacity=50);
	-moz-opacity:.5;
	opacity:.5;
	cursor:default;
}

.overlayHelp {
	margin:0 0 0 -125px;
	padding:7px;
	border:1px solid #999;
	z-index:100;
	background-color:#fff;
	-moz-border-radius:5px;
	width:250px;
	font-size:12px;
}

/*
------------------------------------------------------------
Container for Sizing links
============================================================
*/
#sizerContainer a,.sizerContainer a {
}

/*
-------------------------------------------------
Misc.
=================================================
*/
/*   Marked for deletion   //---------------------------*/
#itemList div.deleting {
	border:1px solid #c00;
	position: relative;
	background-color: #f2dede;
	background-image: none;
}
#itemList div.deleting>*:not(fieldset) {
	filter:alpha(opacity=50);
	-moz-opacity:.5;
	opacity:.5;
}

#itemList div.deleting * {
	color:#ccc;
}

#itemList div img.marked {
	display:none;
}

#itemList div.deleting img.marked {
	display:block;
	position:absolute;
	border:0;
	top:10px;
	left:50%;
	margin:0 0 0 -64px;
	background:none;
}


text:
namespace MvvmCmdr.DesktopSample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            DataContext = new MainWindowViewModel();

            InitializeComponent();
        }
    }
}


text:
class JobsController < ApplicationController
  before_filter :require_user

  def index
    @jobs = Job.paginate(:all, :page => params[:page], :order => "id DESC")
  end

  def show
    @job = Job.find(params[:id])
    if @job.data["error"]
      @error_message = @job.data["error"]["message"]
      @error_exit_code = @job.data["error"]["exit_code"]
    end
  end
  def update_status
    job = Job.find(params[:id])
    if job.aasm_current_state == :paused && params[:status] == 'pause'
      job.unpause
      params[:status] = 'waiting'
    elsif job.aasm_events_for_current_state.include? params[:status].intern
      eval("job.#{params[:status]}")
    else
      flash[:error] = "Job status could not be updated!"
      redirect_to jobs_path
      return
    end

    if job.save!
      flash[:notice] = "Job #{job.aasm_current_state}!"
    else
      flash[:error] = "Job status could not be updated!"
    end

    redirect_to jobs_path
  end

end


text:
package com.github.kawakicchi.developer.tools.rakrak.analyze.entity;

public class DDTitleEntity {

	private String value;
	private String lang;

	public void setValue(final String value) {
		this.value = value;
	}

	public String getValue() {
		return value;
	}

	public void setLang(final String lang) {
		this.lang = lang;
	}

	public String getLang() {
		return lang;
	}
}


text:
package org.drools.workbench.screens.testscenario.client.resources.images;

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;

public interface AuditEventsImages
        extends
        ClientBundle {

    public static AuditEventsImages INSTANCE = GWT.create(AuditEventsImages.class);

    @Source("audit_events/misc_event.gif")
    ImageResource miscEvent();

    @Source("audit_events/1.gif")
    ImageResource image1();

    @Source("audit_events/2.gif")
    ImageResource image2();

    @Source("audit_events/3.gif")
    ImageResource image3();

    @Source("audit_events/4.gif")
    ImageResource image4();

    @Source("audit_events/5.gif")
    ImageResource image5();

    @Source("audit_events/6.gif")
    ImageResource image6();

    @Source("audit_events/7.gif")
    ImageResource image7();

}


text:
class wxToolTip : public wxObject
{
public:
    // ctor & dtor
    wxToolTip(const wxString &rsTip);
    virtual ~wxToolTip();

    //
    // Accessors
    //
    inline const wxString& GetTip(void) const { return m_sText; }
    inline wxWindow*       GetWindow(void) const { return m_pWindow; }

           void            SetTip(const wxString& rsTip);
    inline void            SetWindow(wxWindow* pWin) { m_pWindow = pWin; }

    // controlling tooltip behaviour: globally change tooltip parameters
        // enable or disable the tooltips globally
    static void Enable(bool WXUNUSED(flag)) {}
        // set the delay after which the tooltip appears
    static void SetDelay(long WXUNUSED(milliseconds)) {}

    //
    // Implementation
    //
    void DisplayToolTipWindow(const wxPoint& rPos);
    void HideToolTipWindow(void);

private:
    void Create(const wxString &rsTip);

    HWND                            m_hWnd;
    wxString                        m_sText;           // tooltip text
    wxWindow*                       m_pWindow;         // window we're associated with
}; // end of CLASS wxToolTip

#endif // _WX_OS2_TOOLTIP_H_


text:
package soot.jimple.infoflow.taintWrappers;

import java.util.Set;

import soot.SootMethod;
import soot.jimple.Stmt;
import soot.jimple.infoflow.InfoflowManager;
import soot.jimple.infoflow.data.Abstraction;

/**
 * This interface declares methods to define classes and methods which should not
 * be analyzed directly. Analysis results are instead taken from an external model
 * containing method summaries (which improves performance and helps if the sources
 * are not available).
 *
 * Unless stated otherwise, all methods in this interface must be implemented
 * thread safe.
 *
 * @author Christian Fritz
 * @author Steven Arzt
 */
public interface ITaintPropagationWrapper {

	/**
	 * This method is called before the taint propagation is started to give the taint wrapper
	 * the chance to initialize required components once Soot is running, but before it is
	 * queried for the first time.
	 *
	 * Note that this method is guaranteed to be called only once and only by a single thread.
	 * @param manager The manager object providing access to the data flow solver processing
	 * the IFDS edges and the interprocedural control flow graph
	 */
	public void initialize(InfoflowManager manager);

	/**
	 * Checks an invocation statement for black-box taint propagation. This allows
	 * the wrapper to artificially propagate taints over method invocations without
	 * requiring the analysis to look inside the method.
	 * @param stmt The invocation statement which to check for black-box taint propagation
	 * @param d1 The abstraction at the beginning of the method that calls the
	 * wrapped method
	 * @param taintedPath The tainted field or value to propagate
	 * @return The list of tainted values after the invocation statement referenced in {@link Stmt}
	 * has been executed
	 */
	public Set<Abstraction> getTaintsForMethod(Stmt stmt, Abstraction d1,
			Abstraction taintedPath);

	/**
	 * Gets whether the taints produced by this taint wrapper are exclusive, i.e. there are
	 * no other taints than those produced by the wrapper. In effect, this tells the analysis
	 * not to propagate inside the callee.
	 * @param stmt The call statement to check
	 * @param taintedPath The tainted field or value to propagate
	 * @return True if this taint wrapper is exclusive, otherwise false.
	 */
	public boolean isExclusive(Stmt stmt, Abstraction taintedPath);

	/**
	 * Gets the aliases that a summarized method generates for the given
	 * abstraction. Note that this is a may-alias problem.
	 * @param stmt The statement that calls the summarized method
	 * @param d1 The abstraction at the entry point of the method that calls the
	 * wrapped method
	 * @param taintedPath The abstraction for which the aliases shall be
	 * computed
	 * @return The set of aliases for the given abstraction or null if no such
	 * aliases exist
	 */
	public Set<Abstraction> getAliasesForMethod(Stmt stmt, Abstraction d1,
			Abstraction taintedPath);

	/**
	 * Checks whether this taint wrapper can in general produce artificial taints
	 * for the given callee. If an implementation returns "false" for a callee,
	 * all call sites for this callee might be removed if not needed elsewhere.
	 * @param method The method to check
	 * @return True if this taint wrapper can in general produce taints for the
	 * given method.
	 */
	public boolean supportsCallee(SootMethod method);

	/**
	 * Checks whether this taint wrapper can in general produce artificial taints
	 * for the given call site. If an implementation returns "false" for a call
	 * site, this call sites might be removed if not needed elsewhere.
	 * @param callSite The call site to check
	 * @return True if this taint wrapper can in general produce taints for the
	 * given call site.
	 */
	public boolean supportsCallee(Stmt callSite);

	/**
	 * Gets the number of times in which the taint wrapper was able to
	 * exclusively model a method call. This is equal to the number of times
	 * isExclusive() returned true.
	 * @return The number of method model requests that succeeded
	 */
	public int getWrapperHits();

	/**
	 * Gets the number of times in which the taint wrapper was NOT able to
	 * exclusively model a method call. This is equal to the number of times
	 * isExclusive() returned false.
	 * @return The number of method model requests that failed
	 */
	public int getWrapperMisses();

}


text:
/* */
"use strict";
var Observable_1 = require('../../Observable');
var reduce_1 = require('../../operator/reduce');
Observable_1.Observable.prototype.reduce = reduce_1.reduce;


text:
package org.apache.activemq.artemis.spi.core.protocol;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.activemq.artemis.api.core.BaseInterceptor;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.api.core.RoutingType;

public abstract class AbstractProtocolManager<P, I extends BaseInterceptor<P>, C extends RemotingConnection> implements ProtocolManager<I> {

   private final Map<SimpleString, RoutingType> prefixes = new HashMap<>();

   private String securityDomain;

   protected String invokeInterceptors(final List<I> interceptors, final P message, final C connection) {
      if (interceptors != null && !interceptors.isEmpty()) {
         for (I interceptor : interceptors) {
            try {
               if (!interceptor.intercept(message, connection)) {
                  return interceptor.getClass().getName();
               }
            } catch (Exception e) {
               ActiveMQServerLogger.LOGGER.failedToInvokeAnInterceptor(e);
            }
         }
      }

      return null;
   }

   @Override
   public void setAnycastPrefix(String anycastPrefix) {
      for (String prefix : anycastPrefix.split(",")) {
         prefixes.put(SimpleString.toSimpleString(prefix), RoutingType.ANYCAST);
      }
   }

   @Override
   public void setMulticastPrefix(String multicastPrefix) {
      for (String prefix : multicastPrefix.split(",")) {
         prefixes.put(SimpleString.toSimpleString(prefix), RoutingType.MULTICAST);
      }
   }

   @Override
   public Map<SimpleString, RoutingType> getPrefixes() {
      return prefixes;
   }

   @Override
   public String getSecurityDomain() {
      return securityDomain;
   }

   @Override
   public void setSecurityDomain(String securityDomain) {
      this.securityDomain = securityDomain;
   }
}


text:
@interface PodsDummy_Pods_OctoViewer : NSObject
@end
@implementation PodsDummy_Pods_OctoViewer
@end


text:
package net.ripe.db.whois.nrtm.client;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class SocketChannelFactoryTest {

    @Mock private SocketChannel socketChannel;

    @Test
    public void read_one_line() throws Exception {
        mockRead("aaa\n");

        SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel);

        assertThat(reader.readLine(), is("aaa"));
    }

    @Test
    public void read_empty_line() throws Exception {
        mockRead("\n");

        SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel);

        assertThat(reader.readLine(), is(""));
    }

    @Test
    public void read_multiple_lines() throws Exception {
        mockRead("aaa\nbbb\nccc\n");

        SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel);

        assertThat(reader.readLine(), is("aaa"));
        assertThat(reader.readLine(), is("bbb"));
        assertThat(reader.readLine(), is("ccc"));
    }

    @Test
    public void write_line() throws Exception {
        mockWrite("aaa\n");

        SocketChannelFactory.Writer writer = SocketChannelFactory.createWriter(socketChannel);

        writer.writeLine("aaa");
    }

    private void mockRead(final String data) throws IOException {
        when(socketChannel.read(any(ByteBuffer.class))).thenAnswer(new Answer<Integer> () {
            @Override
            public Integer answer(InvocationOnMock invocation) throws Throwable {
                byte[] dataBytes = data.getBytes();
                Object[] args = invocation.getArguments();
                final ByteBuffer byteBuffer = (ByteBuffer)args[0];
                // update buffer for read
                byteBuffer.put(dataBytes, 0, dataBytes.length);
                return dataBytes.length;
            }
        });
    }

    private void mockWrite(final String data) throws IOException {
        when(socketChannel.write(any(ByteBuffer.class))).thenAnswer(new Answer<Integer> () {
            @Override
            public Integer answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                final ByteBuffer byteBuffer = (ByteBuffer)args[0];
                // check bytes written to buffer
                final byte[] dataBytes = new byte[byteBuffer.remaining()];
                byteBuffer.get(dataBytes);
                assertThat(new String(dataBytes), is(data));
                return data.length();
            }
        });
    }
}


text:
package org.awardis.pride.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public abstract class Common {
    private Long id;
}


text:
import { Meteor } from 'meteor/meteor';
import { FlowRouter } from 'meteor/kadira:flow-router';

Meteor.startup(() => {
	if (FlowRouter.getQueryParam('resumeToken')) {
		Meteor.loginWithToken(FlowRouter.getQueryParam('resumeToken'), () => {
			FlowRouter.go('/home');
		});
	}
});


text:
using global::SharpDX.Direct3D11;
using SharpDX;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;

#if !NETFX_CORE
namespace HelixToolkit.Wpf.SharpDX
#else
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#endif
{
    namespace Model.Scene
    {
        using Shaders;
        using Core;

        /// <summary>
        ///
        /// </summary>
        public class ViewBoxNode : ScreenSpacedNode
        {
            static readonly ILogger logger = Logger.LogManager.Create<ViewBoxNode>();
            #region Properties
            private TextureModel viewboxTexture;
            /// <summary>
            /// Gets or sets the view box texture.
            /// </summary>
            /// <value>
            /// The view box texture.
            /// </value>
            public TextureModel ViewBoxTexture
            {
                set
                {
                    if (Set(ref viewboxTexture, value))
                    {
                        UpdateTexture(value);
                    }
                }
                get
                {
                    return viewboxTexture;
                }
            }
            /// <summary>
            /// Gets or sets a value indicating whether [enable edge click].
            /// </summary>
            /// <value>
            ///   <c>true</c> if [enable edge click]; otherwise, <c>false</c>.
            /// </value>
            public bool EnableEdgeClick
            {
                set
                {
                    CornerModel.Visible = EdgeModel.Visible = value;
                }
                get
                {
                    return CornerModel.Visible;
                }
            }

            private Vector3 upDirection = new Vector3(0, 1, 0);
            /// <summary>
            /// Gets or sets up direction.
            /// </summary>
            /// <value>
            /// Up direction.
            /// </value>
            public Vector3 UpDirection
            {
                set
                {
                    if (Set(ref upDirection, value))
                    {
                        UpdateModel(value);
                    }
                }
                get
                {
                    return upDirection;
                }
            }
            #endregion

            #region Fields
            private const float size = 5;

            private static readonly Vector3[] xAligned = { new Vector3(0, -1, -1), new Vector3(0, 1, -1), new Vector3(0, -1, 1), new Vector3(0, 1, 1) }; //x
            private static readonly Vector3[] yAligned = { new Vector3(-1, 0, -1), new Vector3(1, 0, -1), new Vector3(-1, 0, 1), new Vector3(1, 0, 1) };//y
            private static readonly Vector3[] zAligned = { new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, -1, 0), new Vector3(1, 1, 0) };//z

            private static readonly Vector3[] cornerPoints =   {
                    new Vector3(-1,-1,-1 ), new Vector3(1, -1, -1), new Vector3(1, 1, -1), new Vector3(-1, 1, -1),
                    new Vector3(-1,-1,1 ),new Vector3(1,-1,1 ),new Vector3(1,1,1 ),new Vector3(-1,1,1 )};

            private static readonly Matrix[] cornerInstances;
            private static readonly Matrix[] edgeInstances;
            private static readonly Geometry3D cornerGeometry;
            private static readonly Geometry3D edgeGeometry;

            private readonly MeshNode ViewBoxMeshModel;
            private readonly InstancingMeshNode EdgeModel;
            private readonly InstancingMeshNode CornerModel;

            private bool isRightHanded = true;
            private List<HitTestResult> hitsInternal = new List<HitTestResult>();
            #endregion

            static ViewBoxNode()
            {
                var builder = new MeshBuilder(true, false);
                var cornerSize = size / 5;
                builder.AddBox(Vector3.Zero, cornerSize, cornerSize, cornerSize);
                cornerGeometry = builder.ToMesh();

                builder = new MeshBuilder(true, false);
                var halfSize = size / 2;
                var edgeSize = halfSize * 1.5f;
                builder.AddBox(Vector3.Zero, cornerSize, edgeSize, cornerSize);
                edgeGeometry = builder.ToMesh();

                cornerInstances = new Matrix[cornerPoints.Length];
                for (var i = 0; i < cornerPoints.Length; ++i)
                {
                    cornerInstances[i] = Matrix.Translation(cornerPoints[i] * size / 2 * 0.95f);
                }
                var count = xAligned.Length;
                edgeInstances = new Matrix[count * 3];

                for (var i = 0; i < count; ++i)
                {
                    edgeInstances[i] = Matrix.RotationZ((float)Math.PI / 2) * Matrix.Translation(xAligned[i] * halfSize * 0.95f);
                }
                for (var i = count; i < count * 2; ++i)
                {
                    edgeInstances[i] = Matrix.Translation(yAligned[i % count] * halfSize * 0.95f);
                }
                for (var i = count * 2; i < count * 3; ++i)
                {
                    edgeInstances[i] = Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(zAligned[i % count] * halfSize * 0.95f);
                }
            }

            public ViewBoxNode()
            {
                CameraType = ScreenSpacedCameraType.Perspective;
                RelativeScreenLocationX = 0.8f;
                ViewBoxMeshModel = new MeshNode() { EnableViewFrustumCheck = false, CullMode = CullMode.Back };
                var sampler = DefaultSamplers.LinearSamplerWrapAni1;
                sampler.BorderColor = Color.Gray;
                sampler.AddressU = sampler.AddressV = sampler.AddressW = TextureAddressMode.Border;
                this.AddChildNode(ViewBoxMeshModel);
                ViewBoxMeshModel.Material = new ViewCubeMaterialCore()
                {
                    DiffuseColor = Color.White,
                    DiffuseMapSampler = sampler
                };

                CornerModel = new InstancingMeshNode()
                {
                    EnableViewFrustumCheck = false,
                    Material = new DiffuseMaterialCore() { DiffuseColor = Color.Yellow },
                    Geometry = cornerGeometry,
                    Instances = cornerInstances,
                    Visible = false
                };
                this.AddChildNode(CornerModel);

                EdgeModel = new InstancingMeshNode()
                {
                    EnableViewFrustumCheck = false,
                    Material = new DiffuseMaterialCore() { DiffuseColor = Color.Silver },
                    Geometry = edgeGeometry,
                    Instances = edgeInstances,
                    Visible = false
                };
                this.AddChildNode(EdgeModel);
                UpdateModel(UpDirection);
            }

            protected override bool OnAttach(IEffectsManager effectsManager)
            {
                if (base.OnAttach(effectsManager))
                {
                    var material = (ViewBoxMeshModel.Material as ViewCubeMaterialCore);
                    if (material.DiffuseMap == null)
                    {
                        material.DiffuseMap = ViewBoxTexture ?? new TextureModel(BitmapExtensions.CreateViewBoxTexture(effectsManager,
                            "F", "B", "L", "R", "U", "D", Color.Red, Color.Red, Color.Blue, Color.Blue, Color.Green, Color.Green,
                            Color.White, Color.White, Color.White, Color.White, Color.White, Color.White), true);
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }

            protected override void OnCoordinateSystemChanged(bool e)
            {
                if (isRightHanded != e)
                {
                    isRightHanded = e;
                    UpdateModel(UpDirection);
                }
            }

            private void UpdateTexture(TextureModel texture)
            {
                if (ViewBoxMeshModel.Material is ViewCubeMaterialCore material)
                    material.DiffuseMap = texture;
            }

            protected void UpdateModel(Vector3 up)
            {
                var left = new Vector3(up.Y, up.Z, up.X);
                var front = Vector3.Cross(left, up);
                if (!isRightHanded)
                {
                    front *= -1;
                    left *= -1;
                }
                var builder = new MeshBuilder(true, true, false);
                builder.AddCubeFace(new Vector3(0, 0, 0), front, up, size, size, size);
                builder.AddCubeFace(new Vector3(0, 0, 0), -front, up, size, size, size);
                builder.AddCubeFace(new Vector3(0, 0, 0), left, up, size, size, size);
                builder.AddCubeFace(new Vector3(0, 0, 0), -left, up, size, size, size);
                builder.AddCubeFace(new Vector3(0, 0, 0), up, left, size, size, size);
                builder.AddCubeFace(new Vector3(0, 0, 0), -up, -left, size, size, size);

                var mesh = builder.ToMesh();
                CreateTextureCoordinates(mesh);

                var pts = new List<Vector3>();

                var center = up * -size / 2 * 1.1f;
                var phi = 24;
                for (var i = 0; i < phi; i++)
                {
                    double angle = 0 + (360 * i / (phi - 1));
                    var angleRad = angle / 180 * Math.PI;
                    var dir = (left * (float)Math.Cos(angleRad)) + (front * (float)Math.Sin(angleRad));
                    pts.Add(center + (dir * (size - 0.75f)));
                    pts.Add(center + (dir * (size + 1.1f)));
                }
                builder = new MeshBuilder(false, false, false);
                builder.AddTriangleStrip(pts);
                var pie = builder.ToMesh();
                var count = pie.Indices.Count;
                for (var i = 0; i < count;)
                {
                    var v1 = pie.Indices[i++];
                    var v2 = pie.Indices[i++];
                    var v3 = pie.Indices[i++];
                    pie.Indices.Add(v1);
                    pie.Indices.Add(v3);
                    pie.Indices.Add(v2);
                }
                var newMesh = MeshGeometry3D.Merge(new MeshGeometry3D[] { pie, mesh });

                if (!isRightHanded)
                {
                    for (var i = 0; i < newMesh.Positions.Count; ++i)
                    {
                        var p = newMesh.Positions[i];
                        p.Z *= -1;
                        newMesh.Positions[i] = p;
                    }
                }

                newMesh.TextureCoordinates = new Vector2Collection(Enumerable.Repeat(new Vector2(-1, -1), pie.Positions.Count));
                newMesh.Colors = new Color4Collection(Enumerable.Repeat(new Color4(1f, 1f, 1f, 1f), pie.Positions.Count));
                newMesh.TextureCoordinates.AddRange(mesh.TextureCoordinates);
                newMesh.Colors.AddRange(Enumerable.Repeat(new Color4(1, 1, 1, 1), mesh.Positions.Count));
                newMesh.Normals = newMesh.CalculateNormals();
                ViewBoxMeshModel.Geometry = newMesh;
            }

            private static void CreateTextureCoordinates(MeshGeometry3D mesh)
            {
                var faces = 6;
                var segment = 4;
                var inc = 1f / faces;

                for (var i = 0; i < mesh.TextureCoordinates.Count; ++i)
                {
                    mesh.TextureCoordinates[i] = new Vector2(mesh.TextureCoordinates[i].X * inc + inc * (int)(i / segment), mesh.TextureCoordinates[i].Y);
                }
            }

            protected override bool CanHitTest(HitTestContext context)
            {
                return context != null;
            }

            protected override bool OnHitTest(HitTestContext context, Matrix totalModelMatrix, ref List<HitTestResult> hits)
            {
                if (base.OnHitTest(context, totalModelMatrix, ref hitsInternal))
                {
                    if (logger.IsEnabled(LogLevel.Debug))
                    {
                        logger.LogDebug("View box hit.");
                    }
                    var hit = hitsInternal.OrderBy(x => x.Distance).FirstOrDefault();
                    if (hit == null)
                    { return false; }
                    Vector3 normal = Vector3.Zero;
                    int inv = isRightHanded ? 1 : -1;
                    if (hit.ModelHit == ViewBoxMeshModel)
                    {
                        normal = -hit.NormalAtHit * inv;
                        //Fix the normal if returned normal is reversed
                        if (Vector3.Dot(normal, context.RenderMatrices.CameraParams.LookAtDir) < 0)
                        {
                            normal *= -1;
                        }
                    }
                    else if (hit.Tag is int index)
                    {
                        if (hit.ModelHit == EdgeModel && index < edgeInstances.Length)
                        {
                            var transform = edgeInstances[index];
                            normal = -transform.TranslationVector;
                        }
                        else if (hit.ModelHit == CornerModel && index < cornerInstances.Length)
                        {
                            var transform = cornerInstances[index];
                            normal = -transform.TranslationVector;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                    normal.Normalize();
                    hit.NormalAtHit = normal;
                    hit.ModelHit = this;
                    hit.Tag = this.Tag;
                    hits.Add(hit);
                    hitsInternal.Clear();
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}


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

<TITLE>
Uses of Class org.apache.poi.poifs.property.PropertyTable (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.poi.poifs.property.PropertyTable

Packages that use PropertyTable

org.apache.poi.poifs.dev
DEV package serves two purposes.

Uses of PropertyTable in org.apache.poi.poifs.dev

Methods in org.apache.poi.poifs.dev with parameters of type PropertyTable

static void
POIFSHeaderDumper.displayPropertiesSummary(PropertyTable properties)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

                Copyright 2017 The Apache Software Foundation or
        its licensors, as applicable.


text:
'use strict';

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.static('./public'));

app.get('*', function(request, response) {
  response.sendFile('index.html', {root: '.'})
})
app.listen(PORT, function() {
  console.log('It\'s ALIVE!');
})


text:
'use strict';

let getVersionMethod = require('./getVersion');
let searchDocumentsMethod = require('./searchDocuments');
let getDocumentMethod = require('./getDocument');

module.exports = {
  getVersion: function (cbOk, cbFail) {
    getVersionMethod(cbOk, cbFail);
  },
  searchDocuments: function (query, cbOk, cbFail) {
    searchDocumentsMethod(query, cbOk, cbFail);
  },
  getDocument: function (docId, cbOk, cbFail) {
    getDocumentMethod(docId, cbOk, cbFail);
  }
};


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="google-site-verification" content="ZfPaSlr3bwFrxIPqW-2BYwe7bEGwZF8SaJ1kj8UX88A" />
  <title>MozillaTN</title>
  <link rel="shortcut icon" href="/assets/images/favicon.ico">
  <link rel="stylesheet" href="/assets/css/style.css">
  <link rel="alternate" type="application/rss+xml" title="My Blog" href="/rss.xml">
  <link rel="stylesheet" href="/assets/css/highlight.css">

         Home
            Blog
            Events
            Event Request

mozillatn

Mozilla Tamilnadu Community Website, highlights more about contributors contribution and tutorials to get started with Community contribution.

            Jun 17
            Weeks of Contribution 2016 - Localization
Mozilla Tamilnadu Community Localization event plans

            Jun 11
            Weeks of Contribution 2016 - FAQ
Summer Learning program by MozillaTN Community

            Jun 04
            Weeks of Contribution 2016
Summer Learning program by MozillaTN Community

            Apr 05
            Add yourself as Author
Add as author for Community Blog

            Mar 11
            Prasanth is budding FSA started contribution with Localization


text:
import chromosomer
from setuptools import setup, find_packages

setup(name='chromosomer',
      version=chromosomer.__version__,
      description='Reference-assisted chromosome assembly tool',

      author='Gaik Tamazian',
      author_email='gaik.tamazian@gmail.com',

      license='MIT',

      classifiers=[
          "Development Status :: 2 - Pre-Alpha",
          "License :: OSI Approved :: MIT License",
          "Environment :: Console",
          "Intended Audience :: Science/Research",
          "Natural Language :: English",
          "Operating System :: Unix",
          "Programming Language :: Python :: 2.7",
          "Topic :: Scientific/Engineering :: Bio-Informatics"
      ],

      packages=find_packages(exclude=['doc', 'tests*']),

      install_requires=['pyfaidx',
                        'future',
                        'bioformats'],

      entry_points={
          'console_scripts': [
              'chromosomer = chromosomer.cli:chromosomer']
      },
      )


text:
package org.apache.solr.search.facet;

import java.io.IOException;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.PriorityQueue;
import org.apache.solr.search.DocIterator;

final class UnionDocIterator extends SweepDocIterator {

  private final int maxIdx;
  private final SubIterStruct baseSub;
  private boolean collectBase;
  private final PriorityQueue<SubIterStruct> queue;
  private SubIterStruct top;
  private int docId = -1;

  private static final class SubIterStruct {
    private final DocIterator sub;
    private final int index;
    private int docId;

    public SubIterStruct(DocIterator sub, int index) throws IOException {
      this.sub = sub;
      this.index = index;
      nextDoc();
    }

    public void nextDoc() {
      docId = sub.hasNext() ? sub.nextDoc() : DocIdSetIterator.NO_MORE_DOCS;
    }
  }

  UnionDocIterator(DocIterator[] subIterators, int baseIdx) throws IOException {
    super(subIterators.length);
    this.maxIdx = size - 1;
    queue =
        new PriorityQueue<>(size) {
          @Override
          protected boolean lessThan(SubIterStruct a, SubIterStruct b) {
            return a.docId < b.docId;
          }
        };
    SubIterStruct tmpBase = null;
    int i = maxIdx;
    do {
      SubIterStruct subIterStruct = new SubIterStruct(subIterators[i], i);
      queue.add(subIterStruct);
      if (i == baseIdx) {
        tmpBase = subIterStruct;
      }
    } while (i-- > 0);
    this.baseSub = tmpBase;
    top = queue.top();
  }

  @Override
  public int nextDoc() {
    if (top.docId == docId) {
      do {
        top.nextDoc();
      } while ((top = queue.updateTop()).docId == docId);
    }
    collectBase = false;
    return docId = top.docId;
  }

  @Override
  public boolean hasNext() {
    if (top.docId == docId) {
      do {
        top.nextDoc();
      } while ((top = queue.updateTop()).docId == docId);
    }
    return top.docId != DocIdSetIterator.NO_MORE_DOCS;
  }

  @Override
  public boolean collectBase() {
    assert top.docId != docId : "must call registerCounts() before collectBase()";
    return collectBase;
  }

  @Override
  public int registerCounts(SegCounter segCounts) {
    int i = -1;
    do {
      if (!collectBase && top == baseSub) {
        collectBase = true;
      }
      segCounts.map(top.index, ++i);
      top.nextDoc();
    } while ((top = queue.updateTop()).docId == docId);
    return i;
  }
}


text:
from django.contrib import admin

from comp.extra.quotes.models import Quote

class QuoteAdmin(admin.ModelAdmin):
    list_display  = ('title', 'author', 'publish', 'allow_comments')
    list_filter   = ('publish',)
    search_fields = ('title', 'quote', 'author')
    prepopulated_fields = {'slug': ('title',)}
    fieldsets = ((None,
                  {'fields': ('title', 'slug', 'quote', 'author', 'url_source',
                              'allow_comments', 'publish',)}),)

admin.site.register(Quote, QuoteAdmin)


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/cdm/win/media_foundation_cdm_session.h"

#include <memory>

#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/scoped_co_mem.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/cdm_key_information.h"
#include "media/base/win/mf_helpers.h"

namespace media {

namespace {

using Microsoft::WRL::ClassicCom;
using Microsoft::WRL::ComPtr;
using Microsoft::WRL::MakeAndInitialize;
using Microsoft::WRL::RuntimeClass;
using Microsoft::WRL::RuntimeClassFlags;

MF_MEDIAKEYSESSION_TYPE ToMFSessionType(CdmSessionType session_type) {
  switch (session_type) {
    case CdmSessionType::kTemporary:
      return MF_MEDIAKEYSESSION_TYPE_TEMPORARY;
    case CdmSessionType::kPersistentLicense:
      return MF_MEDIAKEYSESSION_TYPE_PERSISTENT_LICENSE;
  }
}

// The strings are defined in https://www.w3.org/TR/eme-initdata-registry/
LPCWSTR InitDataTypeToString(EmeInitDataType init_data_type) {
  switch (init_data_type) {
    case EmeInitDataType::UNKNOWN:
      return L"unknown";
    case EmeInitDataType::WEBM:
      return L"webm";
    case EmeInitDataType::CENC:
      return L"cenc";
    case EmeInitDataType::KEYIDS:
      return L"keyids";
  }
}

CdmMessageType ToCdmMessageType(MF_MEDIAKEYSESSION_MESSAGETYPE message_type) {
  switch (message_type) {
    case MF_MEDIAKEYSESSION_MESSAGETYPE_LICENSE_REQUEST:
      return CdmMessageType::LICENSE_REQUEST;
    case MF_MEDIAKEYSESSION_MESSAGETYPE_LICENSE_RENEWAL:
      return CdmMessageType::LICENSE_RENEWAL;
    case MF_MEDIAKEYSESSION_MESSAGETYPE_LICENSE_RELEASE:
      return CdmMessageType::LICENSE_RELEASE;
    case MF_MEDIAKEYSESSION_MESSAGETYPE_INDIVIDUALIZATION_REQUEST:
      return CdmMessageType::INDIVIDUALIZATION_REQUEST;
  }
}

CdmKeyInformation::KeyStatus ToCdmKeyStatus(MF_MEDIAKEY_STATUS status) {
  switch (status) {
    case MF_MEDIAKEY_STATUS_USABLE:
      return CdmKeyInformation::KeyStatus::USABLE;
    case MF_MEDIAKEY_STATUS_EXPIRED:
      return CdmKeyInformation::KeyStatus::EXPIRED;
    case MF_MEDIAKEY_STATUS_OUTPUT_DOWNSCALED:
      return CdmKeyInformation::KeyStatus::OUTPUT_DOWNSCALED;
    // This is for legacy use and should not happen in normal cases. Map it to
    // internal error in case it happens.
    case MF_MEDIAKEY_STATUS_OUTPUT_NOT_ALLOWED:
      return CdmKeyInformation::KeyStatus::INTERNAL_ERROR;
    case MF_MEDIAKEY_STATUS_STATUS_PENDING:
      return CdmKeyInformation::KeyStatus::KEY_STATUS_PENDING;
    case MF_MEDIAKEY_STATUS_INTERNAL_ERROR:
      return CdmKeyInformation::KeyStatus::INTERNAL_ERROR;
    case MF_MEDIAKEY_STATUS_RELEASED:
      return CdmKeyInformation::KeyStatus::RELEASED;
    case MF_MEDIAKEY_STATUS_OUTPUT_RESTRICTED:
      return CdmKeyInformation::KeyStatus::OUTPUT_RESTRICTED;
  }
}

CdmKeysInfo ToCdmKeysInfo(const MFMediaKeyStatus* key_statuses, int count) {
  CdmKeysInfo keys_info;
  keys_info.reserve(count);
  for (int i = 0; i < count; ++i) {
    const auto& key_status = key_statuses[i];

    if (key_status.cbKeyId != sizeof(GUID)) {
      DLOG(ERROR) << __func__ << ": Key ID with unsupported size ignored";
      continue;
    }

    GUID* key_id_guid = reinterpret_cast<GUID*>(key_status.pbKeyId);
    keys_info.push_back(std::make_unique<CdmKeyInformation>(
        ByteArrayFromGUID(*key_id_guid),
        ToCdmKeyStatus(key_status.eMediaKeyStatus),
        /*system_code=*/0));
  }
  return keys_info;
}

class SessionCallbacks final
    : public RuntimeClass<RuntimeClassFlags<ClassicCom>,
                          IMFContentDecryptionModuleSessionCallbacks> {
 public:
  SessionCallbacks() { DVLOG_FUNC(1); }
  SessionCallbacks(const SessionCallbacks&) = delete;
  SessionCallbacks& operator=(const SessionCallbacks&) = delete;
  ~SessionCallbacks() override { DVLOG_FUNC(1); }

  using MessageCB =
      base::RepeatingCallback<void(CdmMessageType message_type,
                                   const std::vector<uint8_t>& message)>;
  using KeysChangeCB = base::RepeatingClosure;

  HRESULT RuntimeClassInitialize(MessageCB message_cb,
                                 KeysChangeCB keys_change_cb) {
    message_cb_ = std::move(message_cb);
    keys_change_cb_ = std::move(keys_change_cb);
    return S_OK;
  }

  // IMFContentDecryptionModuleSessionCallbacks implementation

  STDMETHODIMP KeyMessage(MF_MEDIAKEYSESSION_MESSAGETYPE message_type,
                          const BYTE* message,
                          DWORD message_size,
                          LPCWSTR destination_url) final {
    DVLOG_FUNC(2) << ": message size=" << message_size;
    message_cb_.Run(ToCdmMessageType(message_type),
                    std::vector<uint8_t>(message, message + message_size));
    return S_OK;
  }

  STDMETHODIMP KeyStatusChanged() final {
    DVLOG_FUNC(2);
    keys_change_cb_.Run();
    return S_OK;
  }

 private:
  MessageCB message_cb_;
  KeysChangeCB keys_change_cb_;
};

}  // namespace

MediaFoundationCdmSession::MediaFoundationCdmSession(
    const std::string& uma_prefix,
    const SessionMessageCB& session_message_cb,
    const SessionKeysChangeCB& session_keys_change_cb,
    const SessionExpirationUpdateCB& session_expiration_update_cb)
    : uma_prefix_(uma_prefix),
      session_message_cb_(session_message_cb),
      session_keys_change_cb_(session_keys_change_cb),
      session_expiration_update_cb_(session_expiration_update_cb) {
  DVLOG_FUNC(1);
}

MediaFoundationCdmSession::~MediaFoundationCdmSession() {
  DVLOG_FUNC(1);
}

HRESULT MediaFoundationCdmSession::Initialize(
    IMFContentDecryptionModule* mf_cdm,
    CdmSessionType session_type) {
  DVLOG_FUNC(1);

  ComPtr<SessionCallbacks> session_callbacks;
  auto weak_this = weak_factory_.GetWeakPtr();

  // Use BindToCurrentLoop() because the callbacks can be fired on different
  // threads by |mf_cdm_session_|.
  RETURN_IF_FAILED(MakeAndInitialize<SessionCallbacks>(
      &session_callbacks,
      BindToCurrentLoop(base::BindRepeating(
          &MediaFoundationCdmSession::OnSessionMessage, weak_this)),
      BindToCurrentLoop(base::BindRepeating(
          &MediaFoundationCdmSession::OnSessionKeysChange, weak_this))));

  // |mf_cdm_session_| holds a ref count to |session_callbacks|.
  RETURN_IF_FAILED(mf_cdm->CreateSession(ToMFSessionType(session_type),
                                         session_callbacks.Get(),
                                         &mf_cdm_session_));

  return S_OK;
}

HRESULT MediaFoundationCdmSession::GenerateRequest(
    EmeInitDataType init_data_type,
    const std::vector<uint8_t>& init_data,
    SessionIdCB session_id_cb) {
  DVLOG_FUNC(1);
  DCHECK(session_id_.empty() && !session_id_cb_);

  session_id_cb_ = std::move(session_id_cb);

  RETURN_IF_FAILED(WithUmaReported(
      mf_cdm_session_->GenerateRequest(
          InitDataTypeToString(init_data_type), init_data.data(),
          base::checked_cast<DWORD>(init_data.size())),
      "GenerateRequest"));
  return S_OK;
}

HRESULT MediaFoundationCdmSession::Load(const std::string& session_id) {
  DVLOG_FUNC(1);
  RETURN_IF_FAILED(WithUmaReported(E_NOTIMPL, "LoadSession"));
  return S_OK;
}

HRESULT
MediaFoundationCdmSession::Update(const std::vector<uint8_t>& response) {
  DVLOG_FUNC(1);
  RETURN_IF_FAILED(WithUmaReported(
      mf_cdm_session_->Update(reinterpret_cast<const BYTE*>(response.data()),
                              base::checked_cast<DWORD>(response.size())),
      "UpdateSession"));
  RETURN_IF_FAILED(UpdateExpirationIfNeeded());
  return S_OK;
}

HRESULT MediaFoundationCdmSession::Close() {
  DVLOG_FUNC(1);
  RETURN_IF_FAILED(WithUmaReported(mf_cdm_session_->Close(), "CloseSession"));
  return S_OK;
}

HRESULT MediaFoundationCdmSession::Remove() {
  DVLOG_FUNC(1);
  RETURN_IF_FAILED(WithUmaReported(mf_cdm_session_->Remove(), "RemoveSession"));
  RETURN_IF_FAILED(UpdateExpirationIfNeeded());
  return S_OK;
}

HRESULT MediaFoundationCdmSession::WithUmaReported(HRESULT hr,
                                                   const std::string& api) {
  base::UmaHistogramSparse(uma_prefix_ + api, hr);
  return hr;
}

void MediaFoundationCdmSession::OnSessionMessage(
    CdmMessageType message_type,
    const std::vector<uint8_t>& message) {
  DVLOG_FUNC(2);

  if (session_id_.empty() && !session_id_cb_) {
    DLOG(ERROR) << "Unexpected session message";
    return;
  }

  // If |session_id_| has not been set, set it now.
  if (session_id_.empty() && !SetSessionId())
    return;

  DCHECK(!session_id_.empty());
  session_message_cb_.Run(session_id_, message_type, message);
}

void MediaFoundationCdmSession::OnSessionKeysChange() {
  DVLOG_FUNC(2);

  if (session_id_.empty()) {
    DLOG(ERROR) << "Unexpected session keys change ignored";
    return;
  }

  base::win::ScopedCoMem<MFMediaKeyStatus> key_statuses;

  UINT count = 0;
  if (FAILED(mf_cdm_session_->GetKeyStatuses(&key_statuses, &count))) {
    DLOG(ERROR) << __func__ << ": Failed to get key statuses";
    return;
  }

  // TODO(xhwang): Investigate whether we need to set |has_new_usable_key|.
  session_keys_change_cb_.Run(session_id_, /*has_new_usable_key=*/true,
                              ToCdmKeysInfo(key_statuses.get(), count));

  // ScopedCoMem<MFMediaKeyStatus> only releases memory for |key_statuses|. We
  // need to manually release memory for |pbKeyId| here.
  for (UINT i = 0; i < count; ++i) {
    const auto& key_status = key_statuses[i];
    if (key_status.pbKeyId)
      CoTaskMemFree(key_status.pbKeyId);
  }
}

bool MediaFoundationCdmSession::SetSessionId() {
  DCHECK(session_id_.empty() && session_id_cb_);

  base::win::ScopedCoMem<wchar_t> session_id;
  HRESULT hr = mf_cdm_session_->GetSessionId(&session_id);
  if (FAILED(hr) || !session_id) {
    bool success = std::move(session_id_cb_).Run("");
    DCHECK(!success) << "Empty session ID should not be accepted";
    return false;
  }

  auto session_id_str = base::WideToUTF8(session_id.get());
  if (session_id_str.empty()) {
    bool success = std::move(session_id_cb_).Run("");
    DCHECK(!success) << "Empty session ID should not be accepted";
    return false;
  }

  bool success = std::move(session_id_cb_).Run(session_id_str);
  if (!success) {
    DLOG(ERROR) << "Session ID " << session_id_str << " rejected";
    return false;
  }

  DVLOG_FUNC(1) << "session_id_=" << session_id_str;
  session_id_ = session_id_str;
  return true;
}

HRESULT MediaFoundationCdmSession::UpdateExpirationIfNeeded() {
  DCHECK(!session_id_.empty());

  // Media Foundation CDM follows the EME spec where Time generally represents
  // an instant in time with millisecond accuracy.
  double new_expiration_ms = 0.0;
  RETURN_IF_FAILED(mf_cdm_session_->GetExpiration(&new_expiration_ms));
  auto new_expiration = base::Time::FromJsTime(new_expiration_ms);

  if (new_expiration == expiration_)
    return S_OK;

  DVLOG(2) << "New session expiration: " << new_expiration;
  expiration_ = new_expiration;
  session_expiration_update_cb_.Run(session_id_, expiration_);
  return S_OK;
}

}  // namespace media


text:
(function() {
	'use strict';

	angular
		.module('greyjays.evaluations')
		.directive("adminPosition", adminPosition);

	/**
	 * GUI de gestion CRUD des positions
	 * @desc <admin-position items="" le-service=""></admin-position>
	 * @returns {directive}
	 */

	/** @ngInject */
	function adminPosition() {
		var directive = {
			restrict: 'E',
			scope: {
				items: '=',
				leService: '='
			},
			templateUrl: 'app/components/adminPosition/adminPosition.tpl.html',
			link: linkF
		};
		return directive;

		function linkF(scope) {

			scope.affichage = {
				"add" : false,
				"upd" : false,
				"liste": true
			};
			scope.items = scope.items || [];
			scope.itemAdd = {};

			/**
			 * Affichaer la GUI d'ajout
			 */
			scope.afficherAjout = function() {
				scope.alertesPosition=false;
				scope.itemAdd = {};
				scope.affichage = {
					"add" : true,
					"upd" : false,
					"liste": false
				};
			};

			/**
			 * Afficher la GUI de modification
			 * @param {Object} it - position à modifier
			 */
			scope.afficherModification = function(it) {
				scope.alertesPosition=false;
				scope.itemAdd = {
					"id": it.id,
					"libelle": it.libelle,
					"description": it.description
				};
				scope.affichage = {
					"add" : false,
					"upd" : true,
					"liste": false
				};
			};

			/**
			 * Enregistrer
			 * @param {boolean} estValide -
			 */
			scope.enregistrer = function(estValide) {
				scope.alertesPosition=true;
				if (estValide) {
					var itemAjout = {};
					itemAjout=scope.itemAdd;
					if (typeof scope.itemAdd.id !== 'undefined') {
						itemAjout.id=scope.itemAdd.id;
					}
					scope.leService.save(itemAjout);
					scope.affichage = {
						"add" : false,
						"upd" : false,
						"liste": true
					};
				} else {
					return false;
				}
			};

			/**
			 * Masquer les interfaces add et upd
			 */
			scope.annuler = function() {
				scope.affichage = {
					"add" : false,
					"upd" : false,
					"liste": true
				};
			};

			/**
			 * Effacer un joueur
			 * @param {Object} itemDel - position à supprimer
			 */
			scope.effacer = function(itemDel) {
				scope.leService.delete(itemDel.id);
			};

		}
	}

})();


text:
---
title: Promise Reject
---
## Promise Reject

 A ```Promise.reject``` function returns an error condition to the calling function. It takes a single parameter, an Error object or value, as the reason for rejection.

Chaining a catch function at the end of a Promise caller will allow you to catch the error condition.

```javascript
promiseCallingFunction(paramList)
  .then( ... )
  ...
  .then( ... )
  .catch( function(err) { // catch function
    /*
     * this is where you can access the reason for the rejection
     */
  });
```


text:
from __future__ import print_function
from __future__ import absolute_import

from commoncode.system import on_windows

DEFAULT_TIMEOUT = 120  # seconds

"""
This modules povides an interruptible() function to run a callable and
stop it after a timeout with a windows and POSIX implementation.

Call `func` function with `args` and `kwargs` arguments and return a
tuple of (success, return value). `func` is invoked through an OS-
specific wrapper and will be interrupted if it does not return within
`timeout` seconds.

`func` returned results must be pickable.
`timeout` in seconds defaults to DEFAULT_TIMEOUT.

`args` and `kwargs` are passed to `func` as *args and **kwargs.

In the returned tuple of (success, value), success is True or False. If
success is True, the call was successful and the second item in the
tuple is the returned value of `func`.

If success is False, the call did not complete within `timeout`
seconds and was interrupted. In this case, the second item in the
tuple is an error message string.
"""

class TimeoutError(Exception):
    pass

if not on_windows:
    """
    Some code based in part and inspired from the RobotFramework and
    heavily modified.

    Copyright 2008-2015 Nokia Networks
    Copyright 2016-     Robot Framework Foundation

    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.
    """

    import signal

    def interruptible(func, args=None, kwargs=None, timeout=DEFAULT_TIMEOUT):
        """
        POSIX, signals-based interruptible runner.
        """

        def handler(signum, frame):
            raise TimeoutError

        try:
            signal.signal(signal.SIGALRM, handler)
            signal.setitimer(signal.ITIMER_REAL, timeout)
            return True, func(*(args or ()), **(kwargs or {}))
        except TimeoutError:
            return False, ('ERROR: Processing interrupted: timeout after '
                           '%(timeout)d seconds.' % locals())
        finally:
            signal.setitimer(signal.ITIMER_REAL, 0)

else:
    """
    Run a function in an interruptible thread with a timeout.
    Based on an idea of dano "Dan O'Reilly"
    http://stackoverflow.com/users/2073595/dano
    But not code has been reused from this post.
    """

    import ctypes
    import multiprocessing
    import Queue
    try:
        import thread
    except ImportError:
        import _thread as thread

    def interruptible(func, args=None, kwargs=None, timeout=DEFAULT_TIMEOUT):
        """
        Windows, threads-based interruptible runner. It can work also on
        POSIX, but is not reliable and works only if everything is pickable.
        """
        # We run `func` in a thread and run a loop until timeout
        results = Queue.Queue()

        def runner():
            results.put(func(*(args or ()), **(kwargs or {})))

        tid = thread.start_new_thread(runner, ())

        try:
            res = results.get(timeout=timeout)
            return True, res
        except (Queue.Empty, multiprocessing.TimeoutError):
            return False, ('ERROR: Processing interrupted: timeout after '
                           '%(timeout)d seconds.' % locals())
        finally:
            try:
                async_raise(tid, Exception)
            except (SystemExit, ValueError):
                pass

    def async_raise(tid, exctype=Exception):
        """
        Raise an Exception in the Thread with id `tid`. Perform cleanup if
        needed.

        Based on Killable Threads By Tomer Filiba
        from http://tomerfiliba.com/recipes/Thread2/
        license: public domain.
        """
        assert isinstance(tid, int), 'Invalid  thread id: must an integer'

        tid = ctypes.c_long(tid)
        exception = ctypes.py_object(Exception)
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, exception)
        if res == 0:
            raise ValueError('Invalid thread id.')
        elif res != 1:
            # if it returns a number greater than one, you're in trouble,
            # and you should call it again with exc=NULL to revert the effect
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
            raise SystemError('PyThreadState_SetAsyncExc failed.')


text:
layout: post
title: Hands-on with Coral USB Accelerator (for Raspberry Pi)
tags:
- google
- coral
- tpu
- raspberry pi
published: true
---

[Coral](https://coral.withgoogle.com/) launched [dev board](https://coral.withgoogle.com/products/dev-board/) and [usb accelerator](https://coral.withgoogle.com/products/accelerator/) a couple of weeks ago and they are now available on the store.

I though the usb accelerator would be enough for me, so I ordered one of it and tested on my Raspberry Pi 3B+.

----

## 1. Purchase

Fortunately, the shipping and delivery fee to my country was *zero* on Mouser.

Ordered on Saturday and received on Monday.

What an amazing delivery!

## 2. Unboxing

![coral_box](https://user-images.githubusercontent.com/185988/54582450-174ad800-4a54-11e9-80d3-2aa5d2b7a57c.jpg)

![coral_box_contents](https://user-images.githubusercontent.com/185988/54582451-174ad800-4a54-11e9-9dde-d40ad99a511d.jpg)

![coral_box_contents_rear](https://user-images.githubusercontent.com/185988/54582453-174ad800-4a54-11e9-8327-fb1b1e6db5e8.jpg)

![coral_box_opened](https://user-images.githubusercontent.com/185988/54582454-17e36e80-4a54-11e9-9708-80378bfc7e8f.jpg)

![coral_manual](https://user-images.githubusercontent.com/185988/54582456-17e36e80-4a54-11e9-9d33-02cdf171d8f3.jpg)

## 3. Configuration

Following [this guide](https://coral.withgoogle.com/tutorials/accelerator/), I downloaded and unzipped [edgetpu_api.tar.gz](https://coral.withgoogle.com/tutorials/accelerator/)

and executed `python-tflite-source/install.sh`.

It installed several packages, changed udev rules, and copied library files.

The guide advices to plug in & out the usb accelerator, but to make sure, I just rebooted the machine.

## 4. Test

In the `edgetpu` directory, ran following command:

{% highlight bash %}
python3 demo/classify_image.py \
--model test_data/mobilenet_v2_1.0_224_inat_bird_quant_edgetpu.tflite \
--label test_data/inat_bird_labels.txt \
--image test_data/parrot.jpg
{% endhighlight %}

and got almost the same result:

{% highlight bash %}
W0320 09:13:03.732145    6245 package_registry.cc:65] Minimum runtime version required by package (5) is lower than expected (10).
---------------------------
Ara macao (Scarlet Macaw)
Score :  0.61328125
---------------------------
Platycercus elegans (Crimson Rosella)
Score :  0.15234375
{% endhighlight %}

There was a warning message: `Minimum runtime version required by package (5) is lower than expected (10).`.

It doesn't seem like a critical issue, but needs to be fixed sooner or later.

## 5. What now?

So, I got the usb accelerator and made sure it runs ok on my Raspberry Pi, but what to do now?

Maybe I need to learn TensorFlow Lite and related stuffs, train my own models, and build some applications with them.


text:
title: March
call_to_action: Contact
background_image_path:
large_header: false
show_in_navigation: true
navigation_order: 4
---

Get an introduction to some industry topics and stay informed with our in-depth advice articles.

✎ Update Advice Posts

	{% for post in paginator.posts %}
		{% include post-summary.html post=post %}
	{% endfor %}

{% if paginator.total_pages > 1 %}

		{% if paginator.previous_page %}
			← Newer
		{% elsif paginator.next_page %}

		{% endif %}

		{{ paginator.page }} of {{ paginator.total_pages }}

		{% if paginator.next_page %}
			Older →
		{% elsif paginator.previous_page %}

		{% endif %}

{% endif %}


text:
var express = require('express');
var router = express.Router();

/* GET groups listing. */
router.get('/', function(req, res, next) {
	res.sendFile('groups.html');
});

module.exports = router;


text:
const PIXI = require("pixi.js");
const fieldTypes = require("../../shared/fieldTypes.json");
const marker = require("../../shared/marker.js");
const stage = new PIXI.Container();
var inside = marker();

const sprites = [];
const types = [];
var base, width, height;

function init(_base, _width, _height) {

  width = _width;
  height = _height;
  base = _base;

  var i, p;
  for (i = 0; i < _width; i++) {
    sprites.push(new Array(_height));
    types.push(new Array(_height).fill(0));
  }

  for(i=0; i<_width;i++) {
    for(p=0; p<_height; p++) {
        sprites[i][p] = _addField(i,p);
    }
  }
  base.add(stage);
}

function textures() {
  var textures = [];
  for(var i=0; i<fieldTypes.length; i++) {
    if(i!==0) {
      textures.push(fieldTypes[i].inside.texture);
    }
    textures.push(fieldTypes[i].outside.texture);
  }
  return textures;
}

function center(x, y) {
  stage.x = x;
  stage.y = y;
}

function _addField(x,y) {
  var sprite = new PIXI.Sprite(
    PIXI.loader.resources[fieldTypes[0].outside.texture].texture
  );
  sprite.x = x*base._resolution;
  sprite.y = y*base._resolution;
  sprite.width = base._resolution;
  sprite.height = base._resolution;
  stage.addChild(sprite);
  return sprite;
}

function update (x,y,type,_inside) {
  sprites[x][y].texture = PIXI.loader.resources[fieldTypes[type][_inside ? "inside" : "outside"].texture].texture;
  types[x][y] = type;
  if(_inside) {
    inside.add(x,y);
  } else {
    inside.remove(x,y);
  }
}

function insight () {
  var newInside = marker();

  base.players.getView(width,height,(x,y) => {
    newInside.add(x,y);
    inside.remove(x,y);
  });

  var nowOutside = inside.list();
  var nowInside = newInside.list();

  var i, pos;
  for(i=0; i<nowOutside.length; i++) {
    pos = nowOutside[i];
    update(pos[0],pos[1],types[pos[0]][pos[1]],false);
  }
  for(i=0; i<nowInside.length; i++) {
    pos = nowInside[i];
    update(pos[0],pos[1],types[pos[0]][pos[1]],true);
  }
  inside = newInside;
}

module.exports = {
  init : init,
  insight : insight,
  update : update,
  center : center,
  textures : textures
};


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Redirecting…</title>
<link rel="canonical" href="http://gdfe.co/">
<meta http-equiv="refresh" content="0; url=http://gdfe.co/">

Redirecting…

Click here if you are not redirected.


text:
package nz.org.winters.legodisplaysequencer.views;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;

import nz.org.winters.legodisplaysequencer.caches.SequenceThreadCache;
import nz.org.winters.legodisplaysequencer.sequence.SequenceThread;

/**
 * Created by mathew on 16/04/17.
 * In project lego-train-remote-controller
 */

@SuppressWarnings("unused")
public class SequenceThreadSelector extends android.support.v7.widget.AppCompatSpinner {
  private String toSelectKey;
  private StoppableListAdapter<SequenceThread> adapter;

  public SequenceThreadSelector(Context context) {
    super(context);
  }

  public SequenceThreadSelector(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  public void onAttachedToWindow(){
    super.onAttachedToWindow();
    adapter = SequenceThreadCache.getInstance().getAdapter(getContext(),android.R.layout.simple_list_item_activated_1);
    setAdapter(adapter);
    if(!TextUtils.isEmpty(toSelectKey)){
      setSelectedKey(toSelectKey);
    }
  }

  @Override
  public void onDetachedFromWindow(){
    super.onDetachedFromWindow();
   adapter.stop();
  }

  public String getSelectedKey() {
    if (getSelectedItemPosition() > -1) {
      return ((SequenceThread) getSelectedItem()).getKey();
    }
    return null;
  }

  public void setSelectedKey(String key) {
    if(getAdapter() != null) {
      for (int i = 0; i < getCount(); i++) {
        if (((SequenceThread) getItemAtPosition(i)).getKey().compareTo(key) == 0) {
          setSelection(i);
          break;
        }
      }
    }else{
      toSelectKey = key;
    }
  }
}


text:
package gov.nih.nci.integration.caaers.invoker;

import gov.nih.nci.integration.caaers.CaAERSAdverseEventServiceWSClient;
import gov.nih.nci.integration.caaers.CaAERSParticipantServiceWSClient;
import gov.nih.nci.integration.caaers.ClientPasswordCallback;
import gov.nih.nci.integration.exception.IntegrationError;
import gov.nih.nci.integration.exception.IntegrationException;
import gov.nih.nci.integration.transformer.XSLTTransformer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * This class is used to read the caAERS configurations
 *
 * @author Vinodh
 *
 */
@Configuration
public class CaAERSConfig {

    @Value("${caaers.client.user}")
    private String userName;

    @Value("${caaers.client.psswd}")
    private String password;

    @Value("${caaers.registration.service.url}")
    private String registrationServiceUrl;

    @Value("${caaers.adverseevent.service.url}")
    private String adverseEventServiceUrl;

    @Value("${caaers.retry.count}")
    private String retryCountStr;

    @Value("${integration.transformer.xsl.baseClassPath}")
    private String baseXSLPath;

    @Value("${caaers.participant.xsl}")
    private String caaersParticipantXsl;

    @Value("${caaers.adverseevent.xsl}")
    private String caaersAdverseEventXsl;

    @Autowired
    private XSLTTransformer xsltTransformerParticipant;

    @Autowired
    private XSLTTransformer xsltTransformerAdverseEvent;

    private static final Logger LOG = LoggerFactory.getLogger(CaAERSConfig.class);

    private static final String PROTOTYPE = "prototype";

    /**
     * To get clientPasswordCallback
     *
     * @return ClientPasswordCallback object
     */
    @Bean
    public ClientPasswordCallback clientPasswordCallback() {
        return new ClientPasswordCallback(userName, password);
    }

    /**
     * To get CaAERSParticipantServiceWSClient
     *
     * @return CaAERSParticipantServiceWSClient object
     * @throws IntegrationException - IntegrationException
     */
    @Bean
    public CaAERSParticipantServiceWSClient caAERSParticipantServiceWSClient() throws IntegrationException {
        return new CaAERSParticipantServiceWSClient(registrationServiceUrl + "?wsdl", userName,
                clientPasswordCallback());
    }

    /**
     * To get CaAERSAdverseEventServiceWSClient
     *
     * @return CaAERSAdverseEventServiceWSClient
     * @throws IntegrationException - IntegrationException
     */
    @Bean
    public CaAERSAdverseEventServiceWSClient caAERSAdverseEventServiceWSClient() throws IntegrationException {
        return new CaAERSAdverseEventServiceWSClient(adverseEventServiceUrl + "?wsdl", userName,
                clientPasswordCallback());
    }

    /**
     * To get CaAERSRegistrationServiceInvocationStrategy
     *
     * @return CaAERSRegistrationServiceInvocationStrategy object
     * @throws IntegrationException - IntegrationException
     */
    @Bean
    @Scope(PROTOTYPE)
    public CaAERSRegistrationServiceInvocationStrategy caAersRegistrationServiceInvocationStrategy()
            throws IntegrationException {

        try {
            xsltTransformerParticipant.initTransformer(caaersParticipantXsl, baseXSLPath);
            return new CaAERSRegistrationServiceInvocationStrategy(xsltTransformerParticipant,
                    caAERSParticipantServiceWSClient(), Integer.parseInt(retryCountStr));
        } catch (NumberFormatException e) {
            LOG.error("CaAERSConfig..NumberFormatException inside caAersRegistrationServiceInvocationStrategy. ", e);
            throw new IntegrationException(IntegrationError._1051, e, (Object) null);
        }
    }

    /**
     * To get CaAERSUpdateRegistrationServiceInvocationStrategy
     *
     * @return CaAERSUpdateRegistrationServiceInvocationStrategy obejct
     * @throws IntegrationException - IntegrationException
     */
    @Bean
    @Scope(PROTOTYPE)
    public CaAERSUpdateRegistrationServiceInvocationStrategy caAersUpdateRegistrationServiceInvocationStrategy()
            throws IntegrationException {

        try {
            xsltTransformerParticipant.initTransformer(caaersParticipantXsl, baseXSLPath);
            return new CaAERSUpdateRegistrationServiceInvocationStrategy(xsltTransformerParticipant,
                    caAERSParticipantServiceWSClient(), Integer.parseInt(retryCountStr));
        } catch (NumberFormatException e) {
            LOG.error("NumberFormatException inside caAersUpdateRegistrationServiceInvocationStrategy. ", e);
            throw new IntegrationException(IntegrationError._1051, e, (Object) null);
        }
    }

    /**
     * To get CaAERSAdverseEventServiceInvocationStrategy
     *
     * @return CaAERSAdverseEventServiceInvocationStrategy object
     * @throws IntegrationException - IntegrationException
     */
    @Bean
    @Scope(PROTOTYPE)
    public CaAERSAdverseEventServiceInvocationStrategy caAersAdverseEventServiceInvocationStrategy()
            throws IntegrationException {

        try {
            xsltTransformerAdverseEvent.initTransformer(caaersAdverseEventXsl, baseXSLPath);
            return new CaAERSAdverseEventServiceInvocationStrategy(xsltTransformerAdverseEvent,
                    caAERSAdverseEventServiceWSClient(), Integer.parseInt(retryCountStr));
        } catch (NumberFormatException e) {
            LOG.error("NumberFormatException inside caAersAdverseEventServiceInvocationStrategy. ", e);
            throw new IntegrationException(IntegrationError._1051, e, (Object) null);
        }
    }

  }


text:
#import "MSGraphODataEntities.h"

@implementation MSGraphDeviceRegisteredOwnersCollectionWithReferencesRequestBuilder : MSCollectionRequestBuilder

- (MSGraphDeviceRegisteredOwnersCollectionWithReferencesRequest*) request
{
    return [self requestWithOptions:nil];
}

- (MSGraphDeviceRegisteredOwnersCollectionWithReferencesRequest *)requestWithOptions:(NSArray *)options
{
    return [[MSGraphDeviceRegisteredOwnersCollectionWithReferencesRequest alloc] initWithURL:self.requestURL options:options client:self.client];
}
- (MSGraphDirectoryObjectRequestBuilder *)directoryObject:(NSString *)directoryObject
{
    return [[MSGraphDirectoryObjectRequestBuilder alloc] initWithURL:[self.requestURL URLByAppendingPathComponent:directoryObject]
                                                   client:self.client];
}
- (MSGraphDeviceRegisteredOwnersCollectionReferencesRequestBuilder *) references
{
    return [[MSGraphDeviceRegisteredOwnersCollectionReferencesRequestBuilder alloc] initWithURL:[self.requestURL URLByAppendingPathComponent:@"$ref"] client:self.client];
}

@end


text:
namespace DenarnaPosojila.Forms
{
    partial class UserManagment
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UserManagment));
            System.Windows.Forms.Label sifraOsebeLabel;
            System.Windows.Forms.Label uporabnikLabel;
            System.Windows.Forms.Label gesloLabel;
            System.Windows.Forms.Label isAdminLabel;
            System.Windows.Forms.Label isLoginLabel;
            this.bazaDataSet = new DenarnaPosojila.Data.PosojilaDataSet();
            this.uporabnikiTableAdapter = new DenarnaPosojila.Data.PosojilaDataSetTableAdapters.UporabnikiTableAdapter();
            this.tableAdapterManager = new DenarnaPosojila.Data.PosojilaDataSetTableAdapters.TableAdapterManager();
            this.uporabnikiBindingNavigator = new System.Windows.Forms.BindingNavigator(this.components);
            this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton();
            this.uporabnikiBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel();
            this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton();
            this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton();
            this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton();
            this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator();
            this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox();
            this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton();
            this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton();
            this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.uporabnikiBindingNavigatorSaveItem = new System.Windows.Forms.ToolStripButton();
            this.sifraOsebeTextBox = new System.Windows.Forms.TextBox();
            this.uporabnikTextBox = new System.Windows.Forms.TextBox();
            this.gesloTextBox = new System.Windows.Forms.TextBox();
            this.isAdminCheckBox = new System.Windows.Forms.CheckBox();
            this.isLoginCheckBox = new System.Windows.Forms.CheckBox();
            sifraOsebeLabel = new System.Windows.Forms.Label();
            uporabnikLabel = new System.Windows.Forms.Label();
            gesloLabel = new System.Windows.Forms.Label();
            isAdminLabel = new System.Windows.Forms.Label();
            isLoginLabel = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.bazaDataSet)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.uporabnikiBindingNavigator)).BeginInit();
            this.uporabnikiBindingNavigator.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.uporabnikiBindingSource)).BeginInit();
            this.SuspendLayout();
            //
            // bazaDataSet
            //
            this.bazaDataSet.DataSetName = "BazaDataSet";
            this.bazaDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
            //
            // uporabnikiTableAdapter
            //
            this.uporabnikiTableAdapter.ClearBeforeFill = true;
            //
            // tableAdapterManager
            //
            this.tableAdapterManager.BackupDataSetBeforeUpdate = false;
            this.tableAdapterManager.NastavitveTableAdapter = null;
            this.tableAdapterManager.OsebaTableAdapter = null;
            this.tableAdapterManager.PosojilaTableAdapter = null;
            this.tableAdapterManager.PostaTableAdapter = null;
            this.tableAdapterManager.UpdateOrder = DenarnaPosojila.Data.PosojilaDataSetTableAdapters.TableAdapterManager.UpdateOrderOption.InsertUpdateDelete;
            this.tableAdapterManager.UporabnikiTableAdapter = this.uporabnikiTableAdapter;
            this.tableAdapterManager.ValuteTableAdapter = null;
            //
            // uporabnikiBindingNavigator
            //
            this.uporabnikiBindingNavigator.AddNewItem = this.bindingNavigatorAddNewItem;
            this.uporabnikiBindingNavigator.BindingSource = this.uporabnikiBindingSource;
            this.uporabnikiBindingNavigator.CountItem = this.bindingNavigatorCountItem;
            this.uporabnikiBindingNavigator.CountItemFormat = "od {0}";
            this.uporabnikiBindingNavigator.DeleteItem = this.bindingNavigatorDeleteItem;
            this.uporabnikiBindingNavigator.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.bindingNavigatorMoveFirstItem,
            this.bindingNavigatorMovePreviousItem,
            this.bindingNavigatorSeparator,
            this.bindingNavigatorPositionItem,
            this.bindingNavigatorCountItem,
            this.bindingNavigatorSeparator1,
            this.bindingNavigatorMoveNextItem,
            this.bindingNavigatorMoveLastItem,
            this.bindingNavigatorSeparator2,
            this.bindingNavigatorAddNewItem,
            this.bindingNavigatorDeleteItem,
            this.uporabnikiBindingNavigatorSaveItem});
            this.uporabnikiBindingNavigator.Location = new System.Drawing.Point(0, 0);
            this.uporabnikiBindingNavigator.MoveFirstItem = this.bindingNavigatorMoveFirstItem;
            this.uporabnikiBindingNavigator.MoveLastItem = this.bindingNavigatorMoveLastItem;
            this.uporabnikiBindingNavigator.MoveNextItem = this.bindingNavigatorMoveNextItem;
            this.uporabnikiBindingNavigator.MovePreviousItem = this.bindingNavigatorMovePreviousItem;
            this.uporabnikiBindingNavigator.Name = "uporabnikiBindingNavigator";
            this.uporabnikiBindingNavigator.PositionItem = this.bindingNavigatorPositionItem;
            this.uporabnikiBindingNavigator.Size = new System.Drawing.Size(415, 25);
            this.uporabnikiBindingNavigator.TabIndex = 0;
            this.uporabnikiBindingNavigator.Text = "bindingNavigator1";
            //
            // bindingNavigatorAddNewItem
            //
            this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.bindingNavigatorAddNewItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image")));
            this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem";
            this.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = true;
            this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(23, 22);
            this.bindingNavigatorAddNewItem.Text = "Add new";
            //
            // uporabnikiBindingSource
            //
            this.uporabnikiBindingSource.DataMember = "Uporabniki";
            this.uporabnikiBindingSource.DataSource = this.bazaDataSet;
            //
            // bindingNavigatorCountItem
            //
            this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem";
            this.bindingNavigatorCountItem.Size = new System.Drawing.Size(38, 22);
            this.bindingNavigatorCountItem.Text = "od {0}";
            this.bindingNavigatorCountItem.ToolTipText = "Total number of items";
            //
            // bindingNavigatorDeleteItem
            //
            this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.bindingNavigatorDeleteItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image")));
            this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem";
            this.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = true;
            this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(23, 22);
            this.bindingNavigatorDeleteItem.Text = "Delete";
            //
            // bindingNavigatorMoveFirstItem
            //
            this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image")));
            this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem";
            this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true;
            this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22);
            this.bindingNavigatorMoveFirstItem.Text = "Move first";
            //
            // bindingNavigatorMovePreviousItem
            //
            this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image")));
            this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem";
            this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true;
            this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22);
            this.bindingNavigatorMovePreviousItem.Text = "Move previous";
            //
            // bindingNavigatorSeparator
            //
            this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator";
            this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25);
            //
            // bindingNavigatorPositionItem
            //
            this.bindingNavigatorPositionItem.AccessibleName = "Position";
            this.bindingNavigatorPositionItem.AutoSize = false;
            this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem";
            this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 23);
            this.bindingNavigatorPositionItem.Text = "0";
            this.bindingNavigatorPositionItem.ToolTipText = "Current position";
            //
            // bindingNavigatorSeparator1
            //
            this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1";
            this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25);
            //
            // bindingNavigatorMoveNextItem
            //
            this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image")));
            this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem";
            this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true;
            this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22);
            this.bindingNavigatorMoveNextItem.Text = "Move next";
            //
            // bindingNavigatorMoveLastItem
            //
            this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image")));
            this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem";
            this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true;
            this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22);
            this.bindingNavigatorMoveLastItem.Text = "Move last";
            //
            // bindingNavigatorSeparator2
            //
            this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2";
            this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25);
            //
            // uporabnikiBindingNavigatorSaveItem
            //
            this.uporabnikiBindingNavigatorSaveItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.uporabnikiBindingNavigatorSaveItem.Image = ((System.Drawing.Image)(resources.GetObject("uporabnikiBindingNavigatorSaveItem.Image")));
            this.uporabnikiBindingNavigatorSaveItem.Name = "uporabnikiBindingNavigatorSaveItem";
            this.uporabnikiBindingNavigatorSaveItem.Size = new System.Drawing.Size(23, 22);
            this.uporabnikiBindingNavigatorSaveItem.Text = "Save Data";
            this.uporabnikiBindingNavigatorSaveItem.Click += new System.EventHandler(this.uporabnikiBindingNavigatorSaveItem_Click);
            //
            // sifraOsebeLabel
            //
            sifraOsebeLabel.AutoSize = true;
            sifraOsebeLabel.Location = new System.Drawing.Point(12, 37);
            sifraOsebeLabel.Name = "sifraOsebeLabel";
            sifraOsebeLabel.Size = new System.Drawing.Size(65, 13);
            sifraOsebeLabel.TabIndex = 1;
            sifraOsebeLabel.Text = "Sifra Osebe:";
            //
            // sifraOsebeTextBox
            //
            this.sifraOsebeTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.uporabnikiBindingSource, "SifraOsebe", true));
            this.sifraOsebeTextBox.Location = new System.Drawing.Point(83, 34);
            this.sifraOsebeTextBox.Name = "sifraOsebeTextBox";
            this.sifraOsebeTextBox.Size = new System.Drawing.Size(104, 20);
            this.sifraOsebeTextBox.TabIndex = 2;
            //
            // uporabnikLabel
            //
            uporabnikLabel.AutoSize = true;
            uporabnikLabel.Location = new System.Drawing.Point(12, 63);
            uporabnikLabel.Name = "uporabnikLabel";
            uporabnikLabel.Size = new System.Drawing.Size(59, 13);
            uporabnikLabel.TabIndex = 3;
            uporabnikLabel.Text = "Uporabnik:";
            //
            // uporabnikTextBox
            //
            this.uporabnikTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.uporabnikiBindingSource, "Uporabnik", true));
            this.uporabnikTextBox.Location = new System.Drawing.Point(83, 60);
            this.uporabnikTextBox.Name = "uporabnikTextBox";
            this.uporabnikTextBox.Size = new System.Drawing.Size(104, 20);
            this.uporabnikTextBox.TabIndex = 4;
            //
            // gesloLabel
            //
            gesloLabel.AutoSize = true;
            gesloLabel.Location = new System.Drawing.Point(12, 89);
            gesloLabel.Name = "gesloLabel";
            gesloLabel.Size = new System.Drawing.Size(37, 13);
            gesloLabel.TabIndex = 5;
            gesloLabel.Text = "Geslo:";
            //
            // gesloTextBox
            //
            this.gesloTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.uporabnikiBindingSource, "Geslo", true));
            this.gesloTextBox.Location = new System.Drawing.Point(83, 86);
            this.gesloTextBox.Name = "gesloTextBox";
            this.gesloTextBox.PasswordChar = '*';
            this.gesloTextBox.Size = new System.Drawing.Size(104, 20);
            this.gesloTextBox.TabIndex = 6;
            //
            // isAdminLabel
            //
            isAdminLabel.AutoSize = true;
            isAdminLabel.Location = new System.Drawing.Point(12, 117);
            isAdminLabel.Name = "isAdminLabel";
            isAdminLabel.Size = new System.Drawing.Size(39, 13);
            isAdminLabel.TabIndex = 7;
            isAdminLabel.Text = "Admin:";
            //
            // isAdminCheckBox
            //
            this.isAdminCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.uporabnikiBindingSource, "IsAdmin", true));
            this.isAdminCheckBox.Location = new System.Drawing.Point(83, 112);
            this.isAdminCheckBox.Name = "isAdminCheckBox";
            this.isAdminCheckBox.Size = new System.Drawing.Size(104, 24);
            this.isAdminCheckBox.TabIndex = 8;
            this.isAdminCheckBox.UseVisualStyleBackColor = true;
            //
            // isLoginLabel
            //
            isLoginLabel.AutoSize = true;
            isLoginLabel.Location = new System.Drawing.Point(12, 147);
            isLoginLabel.Name = "isLoginLabel";
            isLoginLabel.Size = new System.Drawing.Size(42, 13);
            isLoginLabel.TabIndex = 9;
            isLoginLabel.Text = "Prijava:";
            //
            // isLoginCheckBox
            //
            this.isLoginCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.uporabnikiBindingSource, "IsLogin", true));
            this.isLoginCheckBox.Location = new System.Drawing.Point(83, 142);
            this.isLoginCheckBox.Name = "isLoginCheckBox";
            this.isLoginCheckBox.Size = new System.Drawing.Size(104, 24);
            this.isLoginCheckBox.TabIndex = 10;
            this.isLoginCheckBox.UseVisualStyleBackColor = true;
            //
            // UserManagment
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(415, 306);
            this.Controls.Add(sifraOsebeLabel);
            this.Controls.Add(this.sifraOsebeTextBox);
            this.Controls.Add(uporabnikLabel);
            this.Controls.Add(this.uporabnikTextBox);
            this.Controls.Add(gesloLabel);
            this.Controls.Add(this.gesloTextBox);
            this.Controls.Add(isAdminLabel);
            this.Controls.Add(this.isAdminCheckBox);
            this.Controls.Add(isLoginLabel);
            this.Controls.Add(this.isLoginCheckBox);
            this.Controls.Add(this.uporabnikiBindingNavigator);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "UserManagment";
            this.Text = "Uporabniki";
            this.Load += new System.EventHandler(this.UserManagment_Load);
            ((System.ComponentModel.ISupportInitialize)(this.bazaDataSet)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.uporabnikiBindingNavigator)).EndInit();
            this.uporabnikiBindingNavigator.ResumeLayout(false);
            this.uporabnikiBindingNavigator.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.uporabnikiBindingSource)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private Data.PosojilaDataSet bazaDataSet;
        private Data.PosojilaDataSetTableAdapters.UporabnikiTableAdapter uporabnikiTableAdapter;
        private Data.PosojilaDataSetTableAdapters.TableAdapterManager tableAdapterManager;
        private System.Windows.Forms.BindingNavigator uporabnikiBindingNavigator;
        private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem;
        private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem;
        private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem;
        private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem;
        private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem;
        private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator;
        private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem;
        private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1;
        private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem;
        private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem;
        private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2;
        private System.Windows.Forms.ToolStripButton uporabnikiBindingNavigatorSaveItem;
        private System.Windows.Forms.BindingSource uporabnikiBindingSource;
        private System.Windows.Forms.TextBox sifraOsebeTextBox;
        private System.Windows.Forms.TextBox uporabnikTextBox;
        private System.Windows.Forms.TextBox gesloTextBox;
        private System.Windows.Forms.CheckBox isAdminCheckBox;
        private System.Windows.Forms.CheckBox isLoginCheckBox;
    }
}


text:
package ca.uhn.fhir.jpa.z;

import org.junit.Test;
import org.springframework.test.annotation.DirtiesContext;

import ca.uhn.fhir.jpa.dao.dstu2.BaseJpaDstu2Test;

public class ZContextCloserDstu2Test extends BaseJpaDstu2Test {

	/**
	 *  this is just here to close the context when this package's test are done
	 */
	@Test
	@DirtiesContext()
	public void testCloseContext() {
		// nothing
	}

}