text:
package org.elasticsearch.xpack.core.action.util;

import org.elasticsearch.common.Strings;
import org.elasticsearch.common.regex.Regex;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Class for tracking the set of Ids returned from some
 * function a satisfy the required Ids as defined by an
 * expression that may contain wildcards.
 *
 * For example, given a set of Ids ["foo-1", "foo-2", "bar-1", bar-2"]:
 *

 *
The expression foo* would be satisfied by foo-1 and foo-2

 *
The expression bar-1 would be satisfied by bar-1

 *
The expression bar-1,car-1 would leave car-1 unmatched

 *
The expression * would be satisfied by anything or nothing depending on the
 *     value of {@code allowNoMatchForWildcards}

 *

 */
public final class ExpandedIdsMatcher {

    public static String ALL = "_all";

    /**
     * Split {@code expression} into tokens separated by a ','
     *
     * @param expression Expression containing zero or more ','s
     * @return Array of tokens
     */
    public static String[] tokenizeExpression(String expression) {
        return Strings.tokenizeToStringArray(expression, ",");
    }

    private final LinkedList<IdMatcher> requiredMatches;
    private final boolean onlyExact;

    /**
     * Generate the list of required matches from the expressions in {@code tokens}
     * and initialize.
     *
     * @param tokens List of expressions that may be wildcards or full Ids
     * @param allowNoMatchForWildcards If true then it is not required for wildcard
     *                                 expressions to match an Id meaning they are
     *                                 not returned in the list of required matches
     */
    public ExpandedIdsMatcher(String[] tokens, boolean allowNoMatchForWildcards) {
        requiredMatches = new LinkedList<>();

        if (Strings.isAllOrWildcard(tokens)) {
            // if allowNoJobForWildcards == true then any number
            // of jobs with any id is ok. Therefore no matches
            // are required

            if (allowNoMatchForWildcards == false) {
                // require something, anything to match
                requiredMatches.add(new WildcardMatcher("*"));
            }
            onlyExact = false;
            return;
        }

        boolean atLeastOneWildcard = false;

        if (allowNoMatchForWildcards) {
            // matches are not required for wildcards but
            // specific job Ids are
            for (String token : tokens) {
                if (Regex.isSimpleMatchPattern(token)) {
                    atLeastOneWildcard = true;
                } else {
                    requiredMatches.add(new EqualsIdMatcher(token));
                }
            }
        } else {
            // Matches are required for wildcards
            for (String token : tokens) {
                if (Regex.isSimpleMatchPattern(token)) {
                    requiredMatches.add(new WildcardMatcher(token));
                    atLeastOneWildcard = true;
                } else {
                    requiredMatches.add(new EqualsIdMatcher(token));
                }
            }
        }
        onlyExact = atLeastOneWildcard == false;
    }

    /**
     * For each {@code requiredMatchers} check there is an element
     * present in {@code ids} that matches. Once a match is made the
     * matcher is removed from {@code requiredMatchers}.
     */
    public void filterMatchedIds(Collection<String> ids) {
        for (String id: ids) {
            Iterator<IdMatcher> itr = requiredMatches.iterator();
            if (itr.hasNext() == false) {
                break;
            }
            while (itr.hasNext()) {
                if (itr.next().matches(id)) {
                    itr.remove();
                }
            }
        }
    }

    public boolean hasUnmatchedIds() {
        return requiredMatches.isEmpty() == false;
    }

    public List<String> unmatchedIds() {
        return requiredMatches.stream().map(IdMatcher::getId).collect(Collectors.toList());
    }

    public String unmatchedIdsString() {
        return requiredMatches.stream().map(IdMatcher::getId).collect(Collectors.joining(","));
    }

    /**
     * Whether ids are based on exact matchers or at least one contains a wildcard.
     *
     * @return true if only exact matches, false if at least one id contains a wildcard
     */
    public boolean isOnlyExact() {
        return onlyExact;
    }

    private abstract static class IdMatcher {
        protected final String id;

        IdMatcher(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        public abstract boolean matches(String jobId);
    }

    private static class EqualsIdMatcher extends IdMatcher {
        EqualsIdMatcher(String id) {
            super(id);
        }

        @Override
        public boolean matches(String id) {
            return this.id.equals(id);
        }
    }

    private static class WildcardMatcher extends IdMatcher {
        WildcardMatcher(String id) {
            super(id);
        }

        @Override
        public boolean matches(String id) {
            return Regex.simpleMatch(this.id, id);
        }
    }
}


text: const options={fix:!0};export default options;

redpajama_set_name: RedPajamaGithub


text:
layout: attachment
title: 0e519-introductionoftheachievementhabitbybernardroth
date:
type: attachment
published: false
status: inherit
categories: []
tags: []
meta:
  auto_import: http://static1.squarespace.com/static/554a7f8ae4b09f04577b0f3c/t/5598329ae4b01a6af58e6115/1436037786789/Introduction+of+The+Achievement+Habit+by+Bernard+Roth.pdf
author:
  login: scollinsptscd
  email: scollinsptscd@gmail.com
  display_name: scollinsptscd
  first_name: ''
  last_name: ''
---


text:
Assumes some environmental variables:
DWN_OAUTH_GOOGLE_KEY
DWN_OAUTH_GOOGLE_SECRET

https://jacobmartins.com/2016/02/29/getting-started-with-oauth2-in-go/


text:
package engine

import (
	"encoding/hex"
	"testing"

	"github.com/keybase/client/go/libkb"
	"github.com/stretchr/testify/require"
)

func persistDeviceCloneState(m libkb.MetaContext, d libkb.DeviceCloneState) error {
	return libkb.SetDeviceCloneState(m, d)
}

func runAndGetDeviceCloneState(m libkb.MetaContext) (d libkb.DeviceCloneState, err error) {
	_, _, err = libkb.UpdateDeviceCloneState(m)
	if err != nil {
		return d, err
	}
	d, _ = libkb.GetDeviceCloneState(m)
	return d, err
}

func assertIsValidToken(tc libkb.TestContext, token string) {
	_, err := hex.DecodeString(token)
	require.NoError(tc.T, err)
	require.Equal(tc.T, len(token), 32)
}

func assertSuccessfulRun(tc libkb.TestContext, d libkb.DeviceCloneState, err error) {
	require.NoError(tc.T, err)
	require.Equal(tc.T, d.Stage, "")
	assertIsValidToken(tc, d.Prior)
}

func TestDeviceCloneStateFirstRun(t *testing.T) {
	tc := SetupEngineTest(t, "DeviceCloneState")
	defer tc.Cleanup()
	_ = CreateAndSignupFakeUser(tc, "fu")
	m := NewMetaContextForTest(tc)

	d, err := runAndGetDeviceCloneState(m)
	assertSuccessfulRun(tc, d, err)
	require.Equal(tc.T, d.Clones, 1)
}

func TestDeviceCloneStateSuccessfulUpdate(t *testing.T) {
	tc := SetupEngineTest(t, "DeviceCloneState")
	defer tc.Cleanup()
	_ = CreateAndSignupFakeUser(tc, "fu")
	m := NewMetaContextForTest(tc)
	//setup: perform an initial run
	d0, err := runAndGetDeviceCloneState(m)
	require.NoError(tc.T, err)

	d, err := runAndGetDeviceCloneState(m)
	assertSuccessfulRun(tc, d, err)
	require.NotEqual(tc.T, d.Prior, d0.Prior)
	require.Equal(tc.T, d.Clones, 1)
}

func TestDeviceCloneStateRecoveryFromFailureBeforeServer(t *testing.T) {
	tc := SetupEngineTest(t, "DeviceCloneState")
	defer tc.Cleanup()
	_ = CreateAndSignupFakeUser(tc, "fu")
	m := NewMetaContextForTest(tc)
	// setup: persist tokens as if the process failed
	// before the server received the update
	d0 := libkb.DeviceCloneState{
		Prior:  libkb.DefaultCloneTokenValue,
		Stage:  "22222222222222222222222222222222",
		Clones: 1,
	}
	err := persistDeviceCloneState(m, d0)
	require.NoError(t, err)

	d, err := runAndGetDeviceCloneState(m)
	assertSuccessfulRun(tc, d, err)
	require.Equal(tc.T, d.Prior, d0.Stage)
	require.Equal(tc.T, d.Clones, 1)
}

func TestDeviceCloneStateRecoveryFromFailureAfterServer(t *testing.T) {
	tc := SetupEngineTest(t, "DeviceCloneState")
	defer tc.Cleanup()
	_ = CreateAndSignupFakeUser(tc, "fu")
	m := NewMetaContextForTest(tc)
	// setup: run twice. then reset the persistence to where it would have been
	// if the server got the second update but did not ack it successfully to the client.
	d0, err := runAndGetDeviceCloneState(m)
	require.NoError(t, err)
	d1, err := runAndGetDeviceCloneState(m)
	require.NoError(t, err)
	tmp := libkb.DeviceCloneState{Prior: d0.Prior, Stage: d1.Prior, Clones: 1}
	err = persistDeviceCloneState(m, tmp)
	require.NoError(t, err)

	d, err := runAndGetDeviceCloneState(m)
	assertSuccessfulRun(tc, d, err)
	require.Equal(tc.T, d.Prior, d1.Prior)
	require.Equal(tc.T, d.Clones, 1)
}

func TestDeviceCloneStateCloneDetected(t *testing.T) {
	tc := SetupEngineTest(t, "DeviceCloneState")
	defer tc.Cleanup()
	_ = CreateAndSignupFakeUser(tc, "fu")
	m := NewMetaContextForTest(tc)
	// setup: perform two runs, and then manually persist the earlier
	// prior token to simulate a subsequent run by a cloned device
	d0, err := runAndGetDeviceCloneState(m)
	require.NoError(tc.T, err)
	_, err = runAndGetDeviceCloneState(m)
	require.NoError(tc.T, err)
	err = persistDeviceCloneState(m, d0)
	require.NoError(t, err)

	before, after, err := libkb.UpdateDeviceCloneState(m)
	require.NoError(t, err)

	d, err := libkb.GetDeviceCloneState(m)
	assertSuccessfulRun(tc, d, err)
	require.NotEqual(tc.T, d.Prior, d0.Stage, "despite there being a clone, the prior still needs to change")
	require.Equal(tc.T, d.Clones, 2)
	require.Equal(tc.T, before, 1, "there was one clone before the test run")
	require.Equal(tc.T, after, 2, "there were two clones after the test run")
}

func TestDeviceCloneStateBeforeAndAfterOnFirstRun(t *testing.T) {
	tc := SetupEngineTest(t, "DeviceCloneState")
	defer tc.Cleanup()
	_ = CreateAndSignupFakeUser(tc, "fu")
	m := NewMetaContextForTest(tc)

	before, after, err := libkb.UpdateDeviceCloneState(m)
	require.NoError(tc.T, err)
	require.Equal(tc.T, before, 1, "there was one clone before the test run")
	require.Equal(tc.T, after, 1, "there was one clone after the test run")
}


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

import java.io.Serializable;

import org.camunda.bpm.engine.delegate.CaseExecutionListener;
import org.camunda.bpm.engine.delegate.DelegateCaseExecution;

/**
 * @author Roman Smirnov
 *
 */
public class CloseCaseExecutionListener implements CaseExecutionListener, Serializable {

  private static final long serialVersionUID = 1L;

  protected static String EVENT;
  protected static int COUNTER = 0;
  protected static String ON_CASE_EXECUTION_ID;

  public void notify(DelegateCaseExecution caseExecution) throws Exception {
    EVENT = caseExecution.getEventName();
    COUNTER = COUNTER + 1;
    ON_CASE_EXECUTION_ID = caseExecution.getId();
  }

  public static void clear() {
    EVENT = null;
    COUNTER = 0;
    ON_CASE_EXECUTION_ID = null;
  }

}


text:
<?php

namespace Morfeu\Bundle\EntityBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * GroupPermission
 *
 * @ORM\Table(name="group_permission", indexes={@ORM\Index(name="tenant_id", columns={"tenant_id"})})
 * @ORM\Entity
 */
class GroupPermission
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, precision=0, scale=0, nullable=false, unique=false)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text", precision=0, scale=0, nullable=false, unique=false)
     */
    private $description;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", precision=0, scale=0, nullable=true, unique=false)
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", precision=0, scale=0, nullable=true, unique=false)
     */
    private $updatedAt;

    /**
     * @var integer
     *
     * @ORM\Column(name="status", type="integer", precision=0, scale=0, nullable=false, unique=false)
     */
    private $status;

    /**
     * @var \Morfeu\Bundle\EntityBundle\Entity\Tenant
     *
     * @ORM\ManyToOne(targetEntity="Morfeu\Bundle\EntityBundle\Entity\Tenant")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="tenant_id", referencedColumnName="id", nullable=true)
     * })
     */
    private $tenant;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return GroupPermission
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return GroupPermission
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return GroupPermission
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return GroupPermission
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set status
     *
     * @param integer $status
     * @return GroupPermission
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return integer
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set tenant
     *
     * @param \Morfeu\Bundle\EntityBundle\Entity\Tenant $tenant
     * @return GroupPermission
     */
    public function setTenant(\Morfeu\Bundle\EntityBundle\Entity\Tenant $tenant = null)
    {
        $this->tenant = $tenant;

        return $this;
    }

    /**
     * Get tenant
     *
     * @return \Morfeu\Bundle\EntityBundle\Entity\Tenant
     */
    public function getTenant()
    {
        return $this->tenant;
    }
}


text:
ActiveRecord::Schema.define(version: 20140804055911) do

  create_table "identities", force: true do |t|
    t.string   "uid",                     null: false
    t.string   "provider",   default: "", null: false
    t.integer  "user_id"
    t.text     "raw"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "identities", ["uid", "provider"], name: "index_identities_on_uid_and_provider", unique: true, using: :btree
  add_index "identities", ["user_id"], name: "index_identities_on_user_id", using: :btree

  create_table "posts", force: true do |t|
    t.text     "content",       null: false
    t.integer  "user_id"
    t.integer  "topic_id"
    t.integer  "sequential_id", null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "posts", ["topic_id"], name: "index_posts_on_topic_id", using: :btree
  add_index "posts", ["user_id", "topic_id", "sequential_id"], name: "index_posts_on_user_id_and_topic_id_and_sequential_id", unique: true, using: :btree
  add_index "posts", ["user_id"], name: "index_posts_on_user_id", using: :btree

  create_table "queries", force: true do |t|
    t.string   "text",       default: "", null: false
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "queries", ["user_id"], name: "index_queries_on_user_id", using: :btree

  create_table "taggings", force: true do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context",       limit: 128
    t.datetime "created_at"
  end

  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true, using: :btree
  add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context", using: :btree

  create_table "tags", force: true do |t|
    t.string  "name"
    t.integer "taggings_count", default: 0
  end

  add_index "tags", ["name"], name: "index_tags_on_name", unique: true, using: :btree

  create_table "topics", force: true do |t|
    t.integer  "user_id"
    t.integer  "sequential_id", null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "topics", ["user_id", "sequential_id"], name: "index_topics_on_user_id_and_sequential_id", unique: true, using: :btree
  add_index "topics", ["user_id"], name: "index_topics_on_user_id", using: :btree

  create_table "users", force: true do |t|
    t.string   "username",               null: false
    t.integer  "locale",     default: 0, null: false
    t.text     "image"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree

end


text:
package com.baidu.oped.apm.rpc.stream;

import com.baidu.oped.apm.rpc.packet.stream.StreamCreateSuccessPacket;
import com.baidu.oped.apm.rpc.packet.stream.StreamResponsePacket;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;

/**
 * @author koo.taejin
 */
public class ServerStreamChannel extends StreamChannel {

    public ServerStreamChannel(Channel channel, int streamId, StreamChannelManager streamChannelManager) {
        super(channel, streamId, streamChannelManager);
    }

    public ChannelFuture sendData(byte[] payload) {
        assertState(StreamChannelStateCode.CONNECTED);

        StreamResponsePacket dataPacket = new StreamResponsePacket(getStreamId(), payload);
        return this.getChannel().write(dataPacket);
    }

    public ChannelFuture sendCreateSuccess() {
        assertState(StreamChannelStateCode.CONNECTED);

        StreamCreateSuccessPacket packet = new StreamCreateSuccessPacket(getStreamId());
        return this.getChannel().write(packet);
    }

    boolean changeStateConnectArrived() {
        return changeStateTo(StreamChannelStateCode.CONNECT_ARRIVED);
    }

}


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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical"
    >

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="@dimen/user_row_item_height"
      android:gravity="center_vertical"
      android:orientation="horizontal"
      >

    <com.alorma.github.ui.view.CircularImageView
        android:id="@+id/avatarAuthorImage"
        android:layout_width="@dimen/user_row_item_image_size"
        android:layout_height="@dimen/user_row_item_image_size"
        android:layout_marginEnd="@dimen/user_row_item_margin"
        android:layout_marginLeft="@dimen/user_row_item_margin"
        android:layout_marginRight="@dimen/user_row_item_margin"
        android:layout_marginStart="@dimen/user_row_item_margin"
        />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

      <TextView
          android:id="@+id/textAuthorLogin"
          style="@style/user_row_item"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_marginEnd="@dimen/user_row_item_margin"
          android:layout_marginRight="@dimen/user_row_item_margin"
          />

      <TextView
          android:id="@+id/userRepoOwner"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignEnd="@+id/textAuthorLogin"
          android:layout_alignParentEnd="true"
          android:layout_alignParentRight="true"
          android:layout_alignParentTop="true"
          android:layout_alignRight="@+id/textAuthorLogin"
          android:layout_marginEnd="@dimen/gapMedium"
          android:layout_marginRight="@dimen/gapMedium"
          android:layout_marginTop="@dimen/gapMedium"
          android:background="@drawable/private_label"
          android:gravity="center"
          android:padding="@dimen/gapSmall"
          android:text="@string/owner"
          android:textColor="@color/privateRepo"
          android:textSize="@dimen/textSizeXMicro"
          android:visibility="visible"
          />
    </RelativeLayout>
  </LinearLayout>

  <View
      android:id="@+id/divider"
      android:layout_width="match_parent"
      android:layout_height="@dimen/card_row_item_divider_height"
      android:layout_marginLeft="@dimen/card_row_item_divider_left_margin"
      android:layout_marginStart="@dimen/card_row_item_divider_left_margin"
      android:background="@drawable/divider_horizontal"
      />

</LinearLayout>


text:
<?php

	namespace Uneak\AssetsBundle\AssetType;

	use Uneak\AssetsBundle\AssetItem\Asset\Asset;
	use Uneak\AssetsBundle\AssetType\Guess\Guess;
	use Uneak\AssetsBundle\AssetType\Guess\TypeGuess;

	class ImageExternalAssetTypeGuesser implements AssetTypeGuesserInterface {

		/**
		 * @param $asset    Asset
		 *
		 * @return TypeGuess
		 */
		public function guessAsset(Asset $asset) {

			if (isset($asset['path'])) {
				$except = array("jpg", "jpeg", "png", "gif", "bmp");
				$check = preg_match('/^.*\.('.implode('|', $except).')$/i', $asset['path']);

				if ($check) {
					return new TypeGuess("image", Guess::VERY_HIGH_CONFIDENCE);
				}
			}

			return null;
		}

		/**
		 * @param $renderData    RenderDataInterface
		 *
		 *
		 * @return TypeGuess
		 */
		public function guessRenderData(RenderDataInterface $renderData) {
			// TODO: Implement guessRenderData() method.
		}
	}


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

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>pandas.DataFrame.nlargest — pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="pandas.DataFrame.notna" href="pandas.DataFrame.notna.html" />
    <link rel="prev" title="pandas.DataFrame.ne" href="pandas.DataFrame.ne.html" />

Navigation

          index

          modules |

          next |

          previous |

pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation »

API Reference »

pandas.DataFrame »

Table Of Contents

What's New

Installation

Contributing to pandas

Package overview

10 Minutes to pandas

Tutorials

Cookbook

Intro to Data Structures

Essential Basic Functionality

Working with Text Data

Options and Settings

Indexing and Selecting Data

MultiIndex / Advanced Indexing

Computational tools

Working with missing data

Group By: split-apply-combine

Merge, join, and concatenate

Reshaping and Pivot Tables

Time Series / Date functionality

Time Deltas

Categorical Data

Visualization

Styling

IO Tools (Text, CSV, HDF5, …)

Enhancing Performance

Sparse data structures

Frequently Asked Questions (FAQ)

rpy2 / R interface

pandas Ecosystem

Comparison with R / R libraries

Comparison with SQL

Comparison with SAS

Comparison with Stata

API Reference

Input/Output

General functions

Series

DataFrame

Constructor

Attributes and underlying data

Conversion

Indexing, iteration

Binary operator functions

Function application, GroupBy & Window

Computations / Descriptive Stats

Reindexing / Selection / Label manipulation

Missing data handling

Reshaping, sorting, transposing

pandas.DataFrame.pivot

pandas.DataFrame.pivot_table

pandas.DataFrame.reorder_levels

pandas.DataFrame.sort_values

pandas.DataFrame.sort_index

pandas.DataFrame.nlargest

pandas.DataFrame.nsmallest

pandas.DataFrame.swaplevel

pandas.DataFrame.stack

pandas.DataFrame.unstack

pandas.DataFrame.swapaxes

pandas.DataFrame.melt

pandas.DataFrame.squeeze

pandas.DataFrame.to_panel

pandas.DataFrame.to_xarray

pandas.DataFrame.T

pandas.DataFrame.transpose

Combining / joining / merging

Time series-related

Plotting

Serialization / IO / Conversion

Sparse

Panel

Index

Numeric Index

CategoricalIndex

IntervalIndex

MultiIndex

DatetimeIndex

TimedeltaIndex

PeriodIndex

Scalars

Frequencies

Window

GroupBy

Resampling

Style

Plotting

General utility functions

Extensions

Developer

Internals

Extending Pandas

Release Notes

Search

                <form class="search" action="../search.html" method="get">
                    <input type="text" name="q" size="18"/>
                    <input type="submit" value="Go"/>
                    <input type="hidden" name="check_keywords" value="yes"/>
                    <input type="hidden" name="area" value="default"/>
                </form>

                    Enter search terms or a module, class or function name.

pandas.DataFrame.nlargest¶

DataFrame.nlargest(n, columns, keep='first')[source]¶

Return the first n rows ordered by columns in descending order.

Return the first n rows with the largest values in columns, in
descending order. The columns that are not specified are returned as
well, but not used for ordering.

This method is equivalent to
df.sort_values(columns, ascending=False).head(n), but more
performant.

<col class="field-name" />
<col class="field-body" />

Parameters:
n : int

Number of rows to return.

columns : label or list of labels

Column label(s) to order by.

keep : {'first', 'last'}, default 'first'

Where there are duplicate values:

first : prioritize the first occurrence(s)

last : prioritize the last occurrence(s)

Returns:
DataFrame

The first n rows ordered by the given columns in descending
order.

See also

DataFrame.nsmallest

Return the first n rows ordered by columns in ascending order.

DataFrame.sort_values

Sort DataFrame by the values

DataFrame.head

Return the first n rows without re-ordering.

Notes

This function cannot be used with all column types. For example, when
specifying columns with object or category dtypes, TypeError is
raised.

Examples

>>> df = pd.DataFrame({'a': [1, 10, 8, 10, -1],
...                    'b': list('abdce'),
...                    'c': [1.0, 2.0, np.nan, 3.0, 4.0]})
>>> df
    a  b    c
0   1  a  1.0
1  10  b  2.0
2   8  d  NaN
3  10  c  3.0
4  -1  e  4.0

In the following example, we will use nlargest to select the three
rows having the largest values in column "a".

>>> df.nlargest(3, 'a')
    a  b    c
1  10  b  2.0
3  10  c  3.0
2   8  d  NaN

When using keep='last', ties are resolved in reverse order:

>>> df.nlargest(3, 'a', keep='last')
    a  b    c
3  10  c  3.0
1  10  b  2.0
2   8  d  NaN

To order by the largest values in column "a" and then "c", we can
specify multiple columns like in the next example.

>>> df.nlargest(3, ['a', 'c'])
    a  b    c
3  10  c  3.0
1  10  b  2.0
2   8  d  NaN

Attempting to use nlargest on non-numeric dtypes will raise a
TypeError:

>>> df.nlargest(3, 'b')
Traceback (most recent call last):
TypeError: Column 'b' has dtype object, cannot use method 'nlargest'

Navigation

          index

          modules |

          next |

          previous |

pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation »

API Reference »

pandas.DataFrame »

Scroll To Top


text:
<!DOCTYPE html>

    <title>GWAS Curation Tool</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

    <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.11/css/dataTables.bootstrap.min.css"/>

    <link href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" rel="stylesheet" />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>

    <link href="https://cdn.jsdelivr.net/bootstrap/3.3.5/css/bootstrap.min.css"
          th:href="@{https://cdn.jsdelivr.net/bootstrap/3.3.5/css/bootstrap.min.css}"
          rel="stylesheet"/>

    <link href="https://cdn.jsdelivr.net/bootstrap/3.3.5/css/bootstrap-theme.min.css"
          th:href="@{https://cdn.jsdelivr.net/bootstrap/3.3.5/css/bootstrap-theme.min.css}"
          rel="stylesheet"/>

    <link th:href="@{/css/jumbotron.css}" rel="stylesheet"/>
    <link th:href="@{/css/sticky-footer-navbar.css}" rel="stylesheet"/>

    <link rel="stylesheet" th:href="@{/css/goci-curation.css}"/>
    <link rel="stylesheet" th:href="@{/css/icons/flaticon.css}"/>
    <link rel="stylesheet" th:href="@{/css/goci-color-palette-1.css}"/>

Monthly Curator Totals

Yearly Curator Totals

Weekly Curator Totals

Overall Weekly progress

Open Targets Weekly progress

Studies Backlog Graph

Stats

                    Week Start Date
                    Created Publications
                    Created Publication IDs
                    Created Studies
                    Created Study IDs
                    Level 1 Completed Publications
                    Level 1 Completed Publication IDs
                    Level 1 Completed Studies
                    Level 1 Completed Study IDs
                    Level 2 Completed Publications
                    Level 2 Completed Publications IDs
                    Level 2 Completed Studies
                    Level 2 Completed Study IDs
                    Published Publications
                    Published Publication IDs
                    Published Studies
                    Published Study IDs

                        2022-22-22

                        NA

                    1000

                        NA

                        NA

                    1000

                        NA

                        NA

                    1000

                        NA

                        NA

                    1000

                        NA


text:
package com.missu.Activitys;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.missu.Bean.DaoSession;
import com.missu.Bean.QQMessage;
import com.missu.Bean.QQMessageType;
import com.missu.Bean.Users;
import com.missu.Bean.UsersDao;
import com.missu.R;
import com.missu.Util.QQConnection;

import java.io.IOException;

public class ChangePassActivity extends AppCompatActivity {

    EditText lastPass,newPass,confirmPass;
    Button confirm;
    ImApp app;
    QQConnection conn;
    DaoSession daoSession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_pass2);
        lastPass = (EditText)findViewById(R.id.et_changepass_oldpass);
        newPass = (EditText)findViewById(R.id.et_changepass_newpass);
        confirmPass = (EditText)findViewById(R.id.et_changepass_confirmpass);
        confirm = (Button)findViewById(R.id.btn_changepass_confirm);
        app = (ImApp) getApplication();
        daoSession = app.getDaoSession();

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lastPass.getText().toString().trim().equals("")){
                    Toast.makeText(ChangePassActivity.this,"原理的密码不能为空,请重新输入",Toast.LENGTH_SHORT).show();
                }
                if (newPass.getText().toString().trim().equals("")){
                    Toast.makeText(ChangePassActivity.this,"新密码不能为空,请重新输入",Toast.LENGTH_SHORT).show();
                }
                if (lastPass.getText().toString().equals(app.getPassword())){
                    if (newPass.getText().toString().equals(confirmPass.getText().toString())){
                        QQMessage message = new QQMessage();
                        message.type = QQMessageType.MSG_TYPE_UPDATE;
                        message.from = app.getMyAccount();

                        message.content = app.getMyAccount()+"#"+newPass.getText().toString()+"#"+ app.getNick() + "#" + app.getAvater()+"#"+app.getSex();
                        conn = app.getMyConn();
                        try {
                            conn.sendMessage(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Users users = daoSession.getUsersDao().queryBuilder().where(UsersDao.Properties.User_name.eq(app.getMyAccount())).unique();
                        Users user = new Users(users.getId(),users.getUser_name(),newPass.getText().toString(),users.getUser_nickname(),"true",users.getUser_profile());
                        daoSession.getUsersDao().update(user);
                        Toast.makeText(getApplicationContext(),"密码修改成功",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(ChangePassActivity.this,MyActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        Toast.makeText(ChangePassActivity.this,"两次输入的新密码不一致,请重新输入",Toast.LENGTH_SHORT).show();
                        newPass.setText("");
                        lastPass.setText("");
                    }
                }else{
                    Toast.makeText(ChangePassActivity.this,"你输入的原来的的密码不正确,请重新输入",Toast.LENGTH_SHORT).show();
                    lastPass.setText("");
                }
            }
        });

    }
    }


text:
package io.siddhi.core.util.statistics;

import io.siddhi.core.config.SiddhiAppContext;
import io.siddhi.core.event.Event;
import io.siddhi.query.api.definition.StreamDefinition;
import io.siddhi.query.api.expression.Expression;
import org.apache.log4j.Logger;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Log number of events received by each receiver
 **/
public class ReceivedEventCounter implements Runnable {
    private static final Logger log = Logger.getLogger(ReceivedEventCounter.class);
    private long totalEventCounter = 0;
    private long eventCounter = 0;
    private SiddhiAppContext siddhiAppContext;
    private ScheduledFuture scheduleLogger;
    private StreamDefinition streamDefinition;
    private int duration = 1;
    private long loggerExecutionInterval;

    public void init(SiddhiAppContext siddhiAppContext, StreamDefinition streamDefinition, int duration) {
        this.siddhiAppContext = siddhiAppContext;
        this.streamDefinition = streamDefinition;
        this.duration = duration;
        this.loggerExecutionInterval = Expression.Time.minute(duration).value();
    }

    public void countEvents(Object eventObject) {
        if (eventObject instanceof Event[]) {
            eventCounter = eventCounter + ((Event[]) eventObject).length;
            totalEventCounter = totalEventCounter + ((Event[]) eventObject).length;
        } else {
            eventCounter++;
            totalEventCounter++;
        }
    }

    @Override
    public void run() {
        log.info("Event received for Stream " + streamDefinition.getId() + " in siddhi App " +
                siddhiAppContext.getName() + " for last " + duration + " minute(s): " + eventCounter + ". " +
                "Total Events: " + totalEventCounter + ".");
        eventCounter = 0;
    }

    public void scheduleEventCounterLogger() {
        if (scheduleLogger != null) {
            scheduleLogger.cancel(true);
        }
        scheduleLogger = siddhiAppContext.getScheduledExecutorService().
                scheduleWithFixedDelay(this, loggerExecutionInterval, loggerExecutionInterval,
                        TimeUnit.MILLISECONDS);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Novitates Mycologicae 177 (1939)

#### Original name
Orbilia algiseda Velen.

### Remarks
null


text:
package June2021AppleLeetcode;

public class _1207UniqueNumberOfOccurrences {
	public static void main(String[] args) {
		System.out.println(uniqueOccurrences(new int[] { 1, 2, 2, 1, 1, 3 }));
		System.out.println(uniqueOccurrences(new int[] { 1, 2 }));
	}

	public static boolean uniqueOccurrences(int[] arr) {

	}
}


text:
============================================
Configure Identity service for token binding
============================================

Token binding embeds information from an external authentication
mechanism, such as a Kerberos server or X.509 certificate, inside a
token. By using token binding, a client can enforce the use of a
specified external authentication mechanism with the token. This
additional security mechanism ensures that if a token is stolen, for
example, it is not usable without external authentication.

You configure the authentication types for a token binding in the
``keystone.conf`` file:

.. code-block:: ini

   [token]
   bind = kerberos

or

.. code-block:: ini

   [token]
   bind = x509

Currently ``kerberos`` and ``x509`` are supported.

To enforce checking of token binding, set the ``enforce_token_bind``
option to one of these modes:

- ``disabled``
    Disables token bind checking.

- ``permissive``
    Enables bind checking. If a token is bound to an unknown
    authentication mechanism, the server ignores it. The default is this
    mode.

- ``strict``
    Enables bind checking. If a token is bound to an unknown
    authentication mechanism, the server rejects it.

- ``required``
    Enables bind checking. Requires use of at least authentication
    mechanism for tokens.

- ``kerberos``
    Enables bind checking. Requires use of kerberos as the authentication
    mechanism for tokens:

    .. code-block:: ini

       [token]
       enforce_token_bind = kerberos

- ``x509``
    Enables bind checking. Requires use of X.509 as the authentication
    mechanism for tokens:

    .. code-block:: ini

       [token]
       enforce_token_bind = x509


text:
package org.onosproject.net.intent;

import com.google.common.annotations.Beta;

/**
 * Intent identifier suitable as an external key.
 *
This class is immutable.

 */
@Beta
public final class IntentId {

    private final long value;

    /**
     * Creates an intent identifier from the specified string representation.
     *
     * @param value long value
     * @return intent identifier
     */
    public static IntentId valueOf(long value) {
        return new IntentId(value);
    }

    /**
     * Constructor for serializer.
     */
    IntentId() {
        this.value = 0;
    }

    /**
     * Constructs the ID corresponding to a given long value.
     *
     * @param value the underlying value of this ID
     */
    IntentId(long value) {
        this.value = value;
    }

    /**
     * Returns the backing value.
     *
     * @return the value
     */
    public long fingerprint() {
        return value;
    }

    @Override
    public int hashCode() {
        return Long.hashCode(value);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof IntentId)) {
            return false;
        }
        IntentId that = (IntentId) obj;
        return this.value == that.value;
    }

    @Override
    public String toString() {
        return "0x" + Long.toHexString(value);
    }

}


text:
sap.ui.define([
  "sap/ui/core/UIComponent"
],
function (UIComponent) {
  "use strict";
  var component = UIComponent.extend("jubilant.Component", {
    metadata : {
      manifest: "json"
    },
    init : function () {
      UIComponent.prototype.init.apply(this, arguments);
    }
  });
  return component;
});


text:
from django.core.exceptions import ValidationError
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _

from zerver.decorator import require_realm_admin
from zerver.lib.actions import do_add_realm_filter, do_remove_realm_filter
from zerver.lib.request import has_request_variables, REQ
from zerver.lib.response import json_success, json_error
from zerver.models import realm_filters_for_realm, UserProfile, RealmFilter

# Custom realm filters
def list_filters(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
    filters = realm_filters_for_realm(user_profile.realm_id)
    return json_success({'filters': filters})

@require_realm_admin
@has_request_variables
def create_filter(request: HttpRequest, user_profile: UserProfile, pattern: str=REQ(),
                  url_format_string: str=REQ()) -> HttpResponse:
    try:
        filter_id = do_add_realm_filter(
            realm=user_profile.realm,
            pattern=pattern,
            url_format_string=url_format_string
        )
        return json_success({'id': filter_id})
    except ValidationError as e:
        return json_error(e.messages[0], data={"errors": dict(e)})

@require_realm_admin
def delete_filter(request: HttpRequest, user_profile: UserProfile,
                  filter_id: int) -> HttpResponse:
    try:
        do_remove_realm_filter(realm=user_profile.realm, id=filter_id)
    except RealmFilter.DoesNotExist:
        return json_error(_('Filter not found'))
    return json_success()


text:
require "spec_helper"

describe FacetParser do
  context "with a select facet definition" do
    let(:facet_definition) do
      {
        "type" => "text",
        "filterable" => true,
        "display_as_result_metadata" => true,
        "name" => "Case type",
        "key" => "case_type",
        "preposition" => "of type",
        "allowed_values" => [
          {
            "label" => "Airport price control reviews",
            "value" => "airport-price-control-reviews",
          },
          {
            "label" => "Market investigations",
            "value" => "market-investigations",
          },
          {
            "label" => "Remittals",
            "value" => "remittals",
          },
        ],
      }
    end
    subject { FacetParser.parse(facet_definition, {}) }

    specify { expect(subject).to be_a OptionSelectFacet }
    specify { expect(subject.name).to eql("Case type") }
    specify { expect(subject.key).to eql("case_type") }
    specify { expect(subject.preposition).to eql("of type") }

    it "should build a list of allowed values" do
      expect(subject.allowed_values[0]["label"]).to eql("Airport price control reviews")
      expect(subject.allowed_values[0]["value"]).to eql("airport-price-control-reviews")
      expect(subject.allowed_values[2]["label"]).to eql("Remittals")
      expect(subject.allowed_values[2]["value"]).to eql("remittals")
    end
  end
end


text:
<html>
<body>
<script src="/js-test-resources/js-test.js"></script>
<script>
if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

performance.addEventListener('resourcetimingbufferfull', function(event) {
  document.body.innerHTML = "PASS. No crash when stop loading on resource timing buffer full.";
  setTimeout("testRunner.notifyDone()", 0);
});

performance.setResourceTimingBufferSize(1);
</script>
</body>
</html>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="nisrulz.github.example.usingfragmentsforresponsivelayout.MainActivity"
    >
  <FrameLayout
      android:id="@+id/fragment_detail_placeholder"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_gravity="center"
      >
  </FrameLayout>

</LinearLayout>


text:
import { randomBytes } from "crypto";

let i = 1;

// @jed's brilliantly short UUID v4 generator
// https://gist.github.com/jed/982883
export default function uuid({ opts }) {
  const { uuidPrefix } = opts;
  if (uuidPrefix) {
    return uuidPrefix + i++;
  }

  return "00000000-0000-4000-8000-000000000000".replace(/[08]/g, randomizer);
}

function randomizer(bit) {
  return (bit ^ randomBytes(1)[0] % 16 >> bit / 4).toString(16);
}


text:
Boostrap Page Personal For Andres jimenez Diseñador Web,
Aj-Studio.com


text:
namespace IoT {
namespace Modbus {

ModbusMaster::ModbusMaster()
{
}

ModbusMaster::~ModbusMaster()
{
}

} } // namespace IoT::Modbus


text:
using System.Reflection;

#region Company Info

// Set the CompanyName, LegalCopyright, and LegalTrademark fields
// You shouldn't have to mess with these
[assembly: AssemblyCompany("blowery.org")]
[assembly: AssemblyCopyright("Copyright (c) 2002 Ben Lowery")]

#endregion

#region Product Info

// Set the ProductName and ProductVersion fields
// AssemblyProduct should be a descriptive name for the product that includes this assembly
//  If this is a generic library that's going to be used by a whole bunch of stuff,
//  just make the name the same as the Assembly's name.  This isn't really used by
//  anything except Windows Explorer's properties tab, so it's not a big deal if you mess it up
//  See pg. 60 of Richter for more info.
[assembly: AssemblyProduct("HttpCompressionModule")]
#endregion

#region Version and Identity Info

// AssemblyInformationalVersion should be the version of the product that is including this
//  assembly.  Again, if this assembly isn't being included in a "product", just make this
//  the same as the FileVersion and be done with it.  See pg 60 of Richter for more info.
[assembly: AssemblyInformationalVersion("1.1.0.0")]

// Set the FileVersion, AssemblyVersion, FileDescription, and Comments fields
// AssemblyFileVersion is stored in the Win32 version resource.  It's ignored by the CLR,
//  we typically use it to store the build and revision bits every time a build
//  is performed.  Unfortunately, the c# compiler doesn't do this automatically,
//  so we'll have to work out another way to do it.
[assembly: AssemblyFileVersion("1.1.0.0")]

// AssemblyVersion is the version used by the CLR as part of the strong name for
//  an assembly.  You don't really want to mess with this unless you're
//  making changes that add / remove / change functionality within the library.
//  For bugfixes, don't mess with this.
//
//  Do this:
//   [assembly: AssemblyVersion("0.82.0.1709")]
//
//  Don't do this:
//   [assembly: AssemblyVersion("0.82.0.1709")]
//  as it breaks all the other assemblies that reference this one every time
//  you build the project.
[assembly: AssemblyVersion("0.82.0.1709")]

// Title is just for inspection utilities and isn't really used for much
//  Generally just set this to the name of the file containing the
//  manifest, sans extension.  I.E. for BensLibrary.dll, name it BensLibrary
[assembly: AssemblyTitle("HttpCompressionModule")]

// Description is just for inspection utilities and isn't really that important.
//  It's generally a good idea to write a decent description so that you
//  don't end up looking like a tool when your stuff shows up in an inspector.
[assembly: AssemblyDescription("An HttpModule that compresses the output")]

#endregion

#region Culture Info

// Set the assembly's culture affinity.  Generally don't want to set this
// unless you're building an resource only assembly.  Assemblies that contain
// code should always be culture neutral
[assembly: AssemblyCulture("")]

#endregion

#region Assembly Signing Info

#if !StronglyNamedAssembly

// Weakly named assemblies are never signed
[assembly: AssemblyDelaySign(false)]

#else

  // Strongly named assemblies are usually delay signed while building and
  // completely signed using sn.exe's -R or -Rc switch

  #if !SignedUsingACryptoServiceProvider

  // Give the name of the file that contains the public/private key pair.
  // If delay signing, only the public key is used
  [assembly: AssemblyKeyFile(THE_KEY_FILE_RELATIVE_TO_THIS_FILE)]

  // Note:  If AssemblyKeyFile and AssemblyKeyName are both specified,
  // here's what happens...
  // 1) If the container exists, the key file is ignored
  // 2) If the container doesn't exist, the keys from the key
  //    file are copied in the container and the assembly is signed

  #else

  // Give the name of the cryptographic service provider (CSP) container
  // that contains the public/private key pair
  // If delay signing, only the public key is used
  [assembly: AssemblyKeyName(THE_KEY_CONTAINER_IN_CSP)]

  #endif

#endif

#endregion


text:
#ifndef SkTextFormatParams_DEFINES
#define SkTextFormatParams_DEFINES

#include "SkScalar.h"
#include "SkTypes.h"

// Fraction of the text size to lower a strike through line below the baseline.
#define kStdStrikeThru_Offset       (-SK_Scalar1 * 6 / 21)
// Fraction of the text size to lower a underline below the baseline.
#define kStdUnderline_Offset        (SK_Scalar1 / 9)
// Fraction of the text size to use for a strike through or under-line.
#define kStdUnderline_Thickness     (SK_Scalar1 / 18)

// The fraction of text size to embolden fake bold text scales with text size.
// At 9 points or below, the stroke width is increased by text size / 24.
// At 36 points and above, it is increased by text size / 32.  In between,
// it is interpolated between those values.
static const SkScalar kStdFakeBoldInterpKeys[] = {
    SK_Scalar1*9,
    SK_Scalar1*36,
};
static const SkScalar kStdFakeBoldInterpValues[] = {
    SK_Scalar1/24,
    SK_Scalar1/32,
};
static_assert(SK_ARRAY_COUNT(kStdFakeBoldInterpKeys) == SK_ARRAY_COUNT(kStdFakeBoldInterpValues),
              "mismatched_array_size");
static const int kStdFakeBoldInterpLength = SK_ARRAY_COUNT(kStdFakeBoldInterpKeys);

#endif  //SkTextFormatParams_DEFINES


text:
(function ($){
    $(function() {
        $('#openmodal').click(function(){
            $('#isamodal').modal("show");
        });
    });

    // ISA Modal Hide Script
    $(function(){
        $('#closemodal').click(function(){
            $('#isamodal').modal("hide");
        });
    });

    //SWE modal Shown script
    $(function(){
        $('#swemodal').on('shown.bs.modal',function(){
            alert('The modal is open');
        });
    });

        //SWE modal Hidden script
    $(function(){
        $('#swemodal').on('hidden.bs.modal',function(){
            alert('The modal is closed');
        });
    });

}(jQuery));


text:
#include "graycom.h"
#include "CTime.h"

#ifndef _WIN32
#include <sys/time.h>

LONGLONG GetTickCount()
{
	struct timeval tv;
	gettimeofday( &tv, NULL );
	return (LONGLONG) (((LONGLONG) tv.tv_sec * 1000) + ((LONGLONG) tv.tv_usec/1000));
}
#endif

//**************************************************************
// -CGTime - absolute time

CGTime::CGTime(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec,
			   int nDST)
{
	struct tm atm;
	atm.tm_sec = nSec;
	atm.tm_min = nMin;
	atm.tm_hour = nHour;
	atm.tm_mday = nDay;
	atm.tm_mon = nMonth - 1;        // tm_mon is 0 based
	atm.tm_year = nYear - 1900;     // tm_year is 1900 based
	atm.tm_isdst = nDST;
	m_time = mktime(&atm);
}

CGTime::CGTime( struct tm atm )
{
	m_time = mktime(&atm);
}

CGTime CGTime::GetCurrentTime()	// static
{
	// return the current system time
	return CGTime(::time(NULL));
}

struct tm* CGTime::GetLocalTm(struct tm* ptm) const
{
	if (ptm != NULL)
	{
		struct tm* ptmTemp = localtime(&m_time);
		if (ptmTemp == NULL)
			return NULL;    // indicates the m_time was not initialized!

		*ptm = *ptmTemp;
		return ptm;
	}
	else
		return localtime(&m_time);
}

////////////////////////////////////////////////////////////////////////////
// String formatting

#ifndef maxTimeBufferSize
	#define maxTimeBufferSize 128
#endif

#ifdef _WIN32
void __cdecl invalidParameterHandler(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved)
{
	// bad format has been specified
	UNREFERENCED_PARAMETER(expression);
	UNREFERENCED_PARAMETER(function);
	UNREFERENCED_PARAMETER(file);
	UNREFERENCED_PARAMETER(line);
	UNREFERENCED_PARAMETER(pReserved);
	DEBUG_ERR(("Invalid time format specified.\n"));
}
#endif

void FormatDateTime(TCHAR * pszTemp, LPCTSTR pszFormat, const struct tm * ptmTemp)
{
	ASSERT(pszTemp != NULL);
	ASSERT(pszFormat != NULL);
	ASSERT(ptmTemp != NULL);

#ifdef _WIN32
	// on windows we need to set the invalid parameter handler, or else the program will terminate when a bad format is encountered
	_invalid_parameter_handler oldHandler, newHandler;
	newHandler = static_cast<_invalid_parameter_handler>(invalidParameterHandler);
#ifndef __MINGW32__
	oldHandler = _set_invalid_parameter_handler(newHandler);
#endif  // __MINGW32__
	try
	{
#endif

	if (strftime( pszTemp, maxTimeBufferSize, pszFormat, ptmTemp) == 0)
		pszTemp[0] = '\0';

#ifdef _WIN32
	}
	catch (...)
	{
		// since VS2010, it seems an exception gets thrown for invalid format strings too
		pszTemp[0] = '\0';
	}

	// restore previous parameter handler

#ifndef __MINGW32__
	_set_invalid_parameter_handler(oldHandler);
#endif  // __MINGW32__
#endif
}

LPCTSTR CGTime::Format(LPCTSTR pszFormat) const
{
	TCHAR * pszTemp = Str_GetTemp();

	if ( pszFormat == NULL )
	{
		pszFormat = "%Y/%m/%d %H:%M:%S";
	}

	struct tm* ptmTemp = localtime(&m_time);
	if (ptmTemp == NULL )
	{
		pszTemp[0] = '\0';
		return( pszTemp );
	}

	FormatDateTime(pszTemp, pszFormat, ptmTemp);
	return pszTemp;
}

LPCTSTR CGTime::FormatGmt(LPCTSTR pszFormat) const
{
	TCHAR * pszTemp = Str_GetTemp();
	if ( pszFormat == NULL )
	{
		pszFormat = "%a, %d %b %Y %H:%M:%S GMT";
	}

	struct tm* ptmTemp = gmtime(&m_time);
	if (ptmTemp == NULL )
	{
		pszTemp[0] = '\0';
		return( pszTemp );
	}

	FormatDateTime(pszTemp, pszFormat, ptmTemp);
	return pszTemp;
}

//**************************************************************

bool CGTime::Read(TCHAR *pszVal)
{
	ADDTOCALLSTACK("CGTime::Read");
	// Read the full date format.

	TCHAR *ppCmds[10];
	size_t iQty = Str_ParseCmds( pszVal, ppCmds, COUNTOF(ppCmds), "/,: \t");
	if ( iQty < 6 )
		return false;

	struct tm atm;
	atm.tm_wday = 0;    // days since Sunday - [0,6]
	atm.tm_yday = 0;    // days since January 1 - [0,365]
	atm.tm_isdst = 0;   // daylight savings time flag

	// Saves: "1999/8/1 14:30:18"
	atm.tm_year = ATOI(ppCmds[0]) - 1900;
	atm.tm_mon = ATOI(ppCmds[1]) - 1;
	atm.tm_mday = ATOI(ppCmds[2]);
	atm.tm_hour = ATOI(ppCmds[3]);
	atm.tm_min = ATOI(ppCmds[4]);
	atm.tm_sec = ATOI(ppCmds[5]);
	m_time = mktime(&atm);

	return true;
}


text:
namespace carto {

    LineRenderer::LineRenderer() :
        _mapRenderer(),
        _elements(),
        _tempElements(),
        _drawDataBuffer(),
        _lineDrawDataBuffer(),
        _prevBitmap(nullptr),
        _colorBuf(),
        _coordBuf(),
        _normalBuf(),
        _texCoordBuf(),
        _indexBuf(),
        _textureCache(),
        _shader(),
        _a_color(0),
        _a_coord(0),
        _a_normal(0),
        _a_texCoord(0),
        _u_gamma(0),
        _u_dpToPX(0),
        _u_unitToDP(0),
        _u_mvpMat(0),
        _u_tex(0),
        _mutex()
    {
    }

    LineRenderer::~LineRenderer() {
    }

    void LineRenderer::setComponents(const std::weak_ptr<Options>& options, const std::weak_ptr<MapRenderer>& mapRenderer) {
        std::lock_guard<std::mutex> lock(_mutex);

        _mapRenderer = mapRenderer;
        _textureCache.reset();
        _shader.reset();
    }

    void LineRenderer::offsetLayerHorizontally(double offset) {
        // Offset current draw data batch horizontally by the required amount
        std::lock_guard<std::mutex> lock(_mutex);

        for (const std::shared_ptr<Line>& element : _elements) {
            element->getDrawData()->offsetHorizontally(offset);
        }
    }

    void LineRenderer::onDrawFrame(float deltaSeconds, const ViewState& viewState) {
        std::lock_guard<std::mutex> lock(_mutex);

        if (_elements.empty()) {
            // Early return, to avoid calling glUseProgram etc.
            return;
        }

        if (!initializeRenderer()) {
            return;
        }

        glDisable(GL_CULL_FACE);

        bind(viewState);

        // Draw, batch by bitmap
        for (const std::shared_ptr<Line>& element : _elements) {
            addToBatch(element->getDrawData(), viewState);
        }
        drawBatch(viewState);

        unbind();

        glEnable(GL_CULL_FACE);

        GLContext::CheckGLError("LineRenderer::onDrawFrame");
    }

    void LineRenderer::addElement(const std::shared_ptr<Line>& element) {
        if (element->getDrawData()) {
            _tempElements.push_back(element);
        }
    }

    void LineRenderer::refreshElements() {
        std::lock_guard<std::mutex> lock(_mutex);
        _elements.clear();
        _elements.swap(_tempElements);
    }

    void LineRenderer::updateElement(const std::shared_ptr<Line>& element) {
        std::lock_guard<std::mutex> lock(_mutex);
        if (std::find(_elements.begin(), _elements.end(), element) == _elements.end()) {
            if (element->getDrawData()) {
                _elements.push_back(element);
            }
        }
    }

    void LineRenderer::removeElement(const std::shared_ptr<Line>& element) {
        std::lock_guard<std::mutex> lock(_mutex);
        _elements.erase(std::remove(_elements.begin(), _elements.end(), element), _elements.end());
    }

    void LineRenderer::calculateRayIntersectedElements(const std::shared_ptr<VectorLayer>& layer, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) const {
        std::lock_guard<std::mutex> lock(_mutex);

        std::vector<MapPos> worldCoords;
        for (const std::shared_ptr<Line>& element : _elements) {
            FindElementRayIntersection(element, element->getDrawData(), layer, ray, viewState, results);
        }
    }

    void LineRenderer::BuildAndDrawBuffers(GLuint a_color,
                                           GLuint a_coord,
                                           GLuint a_normal,
                                           GLuint a_texCoord,
                                           std::vector<unsigned char>& colorBuf,
                                           std::vector<float>& coordBuf,
                                           std::vector<float>& normalBuf,
                                           std::vector<float>& texCoordBuf,
                                           std::vector<unsigned short>& indexBuf,
                                           std::vector<const LineDrawData*>& drawDataBuffer,
                                           const ViewState& viewState)
    {
        // Get bitmap
        std::shared_ptr<Bitmap> bitmap = drawDataBuffer.front()->getBitmap();

        // Calculate buffer size
        std::size_t totalCoordCount = 0;
        std::size_t totalIndexCount = 0;
        for (const LineDrawData* drawData : drawDataBuffer) {
            for (std::size_t i = 0; i < drawData->getCoords().size(); i++) {
                const std::vector<cglib::vec3<double>*>& coords = drawData->getCoords()[i];
                const std::vector<unsigned int>& indices = drawData->getIndices()[i];

                totalCoordCount += coords.size();
                totalIndexCount += indices.size();
            }
        }

        // Resize the buffers, if necessary
        if (coordBuf.size() < totalCoordCount * 3) {
            colorBuf.resize(std::min(totalCoordCount * 4, GLContext::MAX_VERTEXBUFFER_SIZE * 4));
            coordBuf.resize(std::min(totalCoordCount * 3, GLContext::MAX_VERTEXBUFFER_SIZE * 3));
            normalBuf.resize(std::min(totalCoordCount * 4, GLContext::MAX_VERTEXBUFFER_SIZE * 4));
            texCoordBuf.resize(std::min(totalCoordCount * 2, GLContext::MAX_VERTEXBUFFER_SIZE * 2));
        }

        if (indexBuf.size() < totalIndexCount) {
            indexBuf.resize(std::min(totalIndexCount, GLContext::MAX_VERTEXBUFFER_SIZE));
        }

        // Calculate and draw buffers
        cglib::vec3<double> cameraPos = viewState.getCameraPos();
        std::size_t colorIndex = 0;
        std::size_t coordIndex = 0;
        std::size_t normalIndex = 0;
        std::size_t texCoordIndex = 0;
        std::size_t indexIndex = 0;
        float texCoordYScale = (bitmap->getHeight() > 1 ? 1.0f / viewState.getUnitToDPCoef() : 1.0f);
        for (const LineDrawData* drawData : drawDataBuffer) {
            // Draw data vertex info may be split into multiple buffers, draw each one
            for (std::size_t i = 0; i < drawData->getCoords().size(); i++) {

                // Check for possible overflow in the buffer
                const std::vector<unsigned int>& indices = drawData->getIndices()[i];
                if (indexIndex + indices.size() > GLContext::MAX_VERTEXBUFFER_SIZE) {
                    // If it doesn't fit, stop and draw the buffers
                    glVertexAttribPointer(a_color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colorBuf.data());
                    glVertexAttribPointer(a_coord, 3, GL_FLOAT, GL_FALSE, 0, coordBuf.data());
                    glVertexAttribPointer(a_normal, 4, GL_FLOAT, GL_FALSE, 0, normalBuf.data());
                    glVertexAttribPointer(a_texCoord, 2, GL_FLOAT, GL_FALSE, 0, texCoordBuf.data());
                    glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indexIndex), GL_UNSIGNED_SHORT, indexBuf.data());
                    // Start filling buffers from the beginning
                    colorIndex = 0;
                    coordIndex = 0;
                    normalIndex = 0;
                    texCoordIndex = 0;
                    indexIndex = 0;
                }

                // Indices
                std::size_t indexOffset = coordIndex / 3;
                std::vector<unsigned int>::const_iterator iit;
                for (iit = indices.begin(); iit != indices.end(); ++iit) {
                    indexBuf[indexIndex] = static_cast<unsigned short>(indexOffset + *iit);
                    indexIndex++;
                }

                // Coords, tex coords and colors
                Color color = drawData->getColor();
                float normalScale = drawData->getNormalScale();

                // If subpixel width is requested, adjust normal scale and fade color
                if (normalScale < 0.5f) {
                    float c = normalScale / 0.5f;
                    color = Color(
                        static_cast<unsigned char>(color.getR() * c),
                        static_cast<unsigned char>(color.getG() * c),
                        static_cast<unsigned char>(color.getB() * c),
                        static_cast<unsigned char>(color.getA() * c)
                    );
                    normalScale = 0.5f;
                }
                const std::vector<cglib::vec3<double>*>& coords = drawData->getCoords()[i];
                const std::vector<cglib::vec4<float> >& normals = drawData->getNormals()[i];
                const std::vector<cglib::vec2<float> >& texCoords = drawData->getTexCoords()[i];
                auto cit = coords.begin();
                auto nit = normals.begin();
                auto tit = texCoords.begin();
                for ( ; cit != coords.end(); ++cit, ++nit, ++tit) {
                    // Colors
                    colorBuf[colorIndex + 0] = color.getR();
                    colorBuf[colorIndex + 1] = color.getG();
                    colorBuf[colorIndex + 2] = color.getB();
                    colorBuf[colorIndex + 3] = color.getA();
                    colorIndex += 4;

                    // Coords
                    const cglib::vec3<double>& pos = **cit;
                    coordBuf[coordIndex + 0] = static_cast<float>(pos(0) - cameraPos(0));
                    coordBuf[coordIndex + 1] = static_cast<float>(pos(1) - cameraPos(1));
                    coordBuf[coordIndex + 2] = static_cast<float>(pos(2) - cameraPos(2));
                    coordIndex += 3;

                    // Normals
                    const cglib::vec4<float>& normal = *nit;
                    normalBuf[normalIndex + 0] = normal(0) * normalScale;
                    normalBuf[normalIndex + 1] = normal(1) * normalScale;
                    normalBuf[normalIndex + 2] = normal(2) * normalScale;
                    normalBuf[normalIndex + 3] = normal(3);
                    normalIndex += 4;

                    // Tex coords
                    const cglib::vec2<float>& texCoord = *tit;
                    texCoordBuf[texCoordIndex + 0] = texCoord(0);
                    texCoordBuf[texCoordIndex + 1] = texCoord(1) * texCoordYScale;
                    texCoordIndex += 2;
                }
            }
        }

        // Draw the final batch
        if (indexIndex > 0) {
            glVertexAttribPointer(a_color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colorBuf.data());
            glVertexAttribPointer(a_coord, 3, GL_FLOAT, GL_FALSE, 0, coordBuf.data());
            glVertexAttribPointer(a_normal, 4, GL_FLOAT, GL_FALSE, 0, normalBuf.data());
            glVertexAttribPointer(a_texCoord, 2, GL_FLOAT, GL_FALSE, 0, texCoordBuf.data());
            glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indexIndex), GL_UNSIGNED_SHORT, indexBuf.data());
        }
    }

    bool LineRenderer::FindElementRayIntersection(const std::shared_ptr<VectorElement>& element,
                                                  const std::shared_ptr<LineDrawData>& drawData,
                                                  const std::shared_ptr<VectorLayer>& layer,
                                                  const cglib::ray3<double>& ray,
                                                  const ViewState& viewState,
                                                  std::vector<RayIntersectedElement>& results)
    {
        std::vector<cglib::vec3<double> > worldCoords;

        for (std::size_t i = 0; i < drawData->getCoords().size(); i++) {
            // Resize the buffer for calculated world coordinates
            const std::vector<cglib::vec3<double>*>& coords = drawData->getCoords()[i];
            worldCoords.clear();
            worldCoords.reserve(coords.size());

            // Calculate world coordinates and bounding box
            cglib::bbox3<double> bounds = cglib::bbox3<double>::smallest();
            const std::vector<cglib::vec4<float> >& normals = drawData->getNormals()[i];
            auto cit = coords.begin();
            auto nit = normals.begin();
            for ( ; cit != coords.end() && nit != normals.end(); ++cit, ++nit) {
                const cglib::vec3<double>& pos = **cit;
                const cglib::vec4<float>& normal = *nit;
                cglib::vec3<double> worldCoord = pos + cglib::vec3<double>(normal(0) * normal(3), normal(1) * normal(3), normal(2) * normal(3)) * static_cast<double>(viewState.getUnitToDPCoef() * drawData->getClickScale());
                bounds.add(worldCoord);
                worldCoords.push_back(worldCoord);
            }

            // Bounding box check
            if (!cglib::intersect_bbox(bounds, ray)) {
                continue;
            }

            // Click test
            const std::vector<unsigned int>& indices = drawData->getIndices()[i];
            const cglib::vec3<double>* prevPos = nullptr;
            for (std::size_t i = 0; i < indices.size(); i += 3) {
                // Figure out the start and end point of the current line segment
                const cglib::vec3<double>* pos = prevPos;
                for (std::size_t j = 0; j < 3; j++) {
                    const cglib::vec3<double>* nextPos = coords[indices[i + j]];
                    if (nextPos != pos) {
                        prevPos = pos;
                        pos = nextPos;
                    }
                }
                if (!pos || !prevPos) {
                    continue;
                }

                // Test a line triangle against the click position
                double t = 0;
                if (cglib::intersect_triangle(worldCoords[indices[i + 0]], worldCoords[indices[i + 1]], worldCoords[indices[i + 2]], ray, &t)) {
                    cglib::vec3<double> dp = ray(t) - *prevPos;
                    cglib::vec3<double> ds = *pos - *prevPos;
                    cglib::vec3<double> pos = *prevPos + ds * std::max(0.0, std::min(1.0, cglib::dot_product(dp, ds) / cglib::norm(ds)));
                    results.push_back(RayIntersectedElement(std::static_pointer_cast<VectorElement>(element), layer, ray(t), pos, layer->isZBuffering()));
                    return true;
                }
            }
        }
        return false;
    }

    bool LineRenderer::initializeRenderer() {
        if (_shader && _shader->isValid() && _textureCache && _textureCache->isValid()) {
            return true;
        }

        if (auto mapRenderer = _mapRenderer.lock()) {
            _textureCache = mapRenderer->getGLResourceManager()->create<BitmapTextureCache>(TEXTURE_CACHE_SIZE);

            _shader = mapRenderer->getGLResourceManager()->create<Shader>("line", LINE_VERTEX_SHADER, LINE_FRAGMENT_SHADER);

            // Get shader variables locations
            _a_color = _shader->getAttribLoc("a_color");
            _a_coord = _shader->getAttribLoc("a_coord");
            _a_normal = _shader->getAttribLoc("a_normal");
            _a_texCoord = _shader->getAttribLoc("a_texCoord");
            _u_gamma = _shader->getUniformLoc("u_gamma");
            _u_dpToPX = _shader->getUniformLoc("u_dpToPX");
            _u_unitToDP = _shader->getUniformLoc("u_unitToDP");
            _u_mvpMat = _shader->getUniformLoc("u_mvpMat");
            _u_tex = _shader->getUniformLoc("u_tex");
        }

       return _shader && _shader->isValid() && _textureCache && _textureCache->isValid();
    }

    void LineRenderer::bind(const ViewState& viewState) {
        // Prepare for drawing
        glUseProgram(_shader->getProgId());
        // Coords, texCoords, colors
        glEnableVertexAttribArray(_a_color);
        glEnableVertexAttribArray(_a_coord);
        glEnableVertexAttribArray(_a_normal);
        glEnableVertexAttribArray(_a_texCoord);
        // Scale, gamma
        glUniform1f(_u_gamma, 0.5f);
        glUniform1f(_u_dpToPX, viewState.getDPToPX());
        glUniform1f(_u_unitToDP, viewState.getUnitToDPCoef());
        // Matrix
        const cglib::mat4x4<float>& mvpMat = viewState.getRTEModelviewProjectionMat();
        glUniformMatrix4fv(_u_mvpMat, 1, GL_FALSE, mvpMat.data());
        // Texture
        glUniform1i(_u_tex, 0);
    }

    void LineRenderer::unbind() {
        // Disable bound arrays
        glDisableVertexAttribArray(_a_color);
        glDisableVertexAttribArray(_a_coord);
        glDisableVertexAttribArray(_a_normal);
        glDisableVertexAttribArray(_a_texCoord);
    }

    bool LineRenderer::isEmptyBatch() const {
        return _drawDataBuffer.empty();
    }

    void LineRenderer::addToBatch(const std::shared_ptr<LineDrawData>& drawData, const ViewState& viewState) {
        const Bitmap* bitmap = drawData->getBitmap().get();

        if (_prevBitmap && (_prevBitmap != bitmap)) {
            drawBatch(viewState);
        }

        _lineDrawDataBuffer.push_back(drawData.get());
        _drawDataBuffer.push_back(std::move(drawData));
        _prevBitmap = bitmap;
    }

    void LineRenderer::drawBatch(const ViewState& viewState) {
        if (_lineDrawDataBuffer.empty()) {
            return;
        }

        // Bind texture
        const std::shared_ptr<Bitmap>& bitmap = _lineDrawDataBuffer.front()->getBitmap();
        std::shared_ptr<Texture> texture = _textureCache->get(bitmap);
        if (!texture) {
            texture = _textureCache->create(bitmap, true, true);
        }
        glBindTexture(GL_TEXTURE_2D, texture->getTexId());

        BuildAndDrawBuffers(_a_color, _a_coord, _a_normal, _a_texCoord, _colorBuf, _coordBuf, _normalBuf,_texCoordBuf, _indexBuf, _lineDrawDataBuffer, viewState);

        _lineDrawDataBuffer.clear();
        _drawDataBuffer.clear();
        _prevBitmap = nullptr;
    }

    const std::string LineRenderer::LINE_VERTEX_SHADER = R"GLSL(
        #version 100
        attribute vec3 a_coord;
        attribute vec4 a_normal;
        attribute vec2 a_texCoord;
        attribute vec4 a_color;
        uniform float u_gamma;
        uniform float u_dpToPX;
        uniform float u_unitToDP;
        uniform mat4 u_mvpMat;
        varying lowp vec4 v_color;
        varying vec2 v_texCoord;
        varying float v_dist;
        varying float v_width;
        void main() {
            float width = length(a_normal.xyz) * u_dpToPX;
            float roundedWidth = width + 1.0;
            vec3 pos = a_coord + u_unitToDP * roundedWidth / width * (a_normal.xyz * a_normal.w);
            v_color = a_color;
            v_texCoord = a_texCoord;
            v_dist = a_normal.w * roundedWidth * u_gamma;
            v_width = 1.0 + (width - 1.0) * u_gamma;
            gl_Position = u_mvpMat * vec4(pos, 1.0);
        }
    )GLSL";

    const std::string LineRenderer::LINE_FRAGMENT_SHADER = R"GLSL(
        #version 100
        precision mediump float;
        uniform sampler2D u_tex;
        varying lowp vec4 v_color;
        #ifdef GL_FRAGMENT_PRECISION_HIGH
        varying highp vec2 v_texCoord;
        varying highp float v_dist;
        varying highp float v_width;
        #else
        varying mediump vec2 v_texCoord;
        varying mediump float v_dist;
        varying mediump float v_width;
        #endif
        void main() {
            lowp float a = clamp(v_width - abs(v_dist), 0.0, 1.0);
            gl_FragColor = texture2D(u_tex, v_texCoord) * v_color * a;
        }
    )GLSL";

    const unsigned int LineRenderer::TEXTURE_CACHE_SIZE = 1 * 1024 * 1024;

}


text:
var RecordingsRouter = Backbone.Router.extend({
  lastFetch: null,
  routes: {
    "/recordings": "index",
    "/recordings/:chanid/:timestamp": "show"
  },

  index: function() {
    var recordings = new Recordings();
    recordings.comparator = function(model) {
      return model.get('recstartts').getTime() * -1;
    }
    var context = this;

    var setView = function() {
    }

    // If we have already fetched the recordings, the view would already have been rendered, so we can take no action.
    // We'll work out how to update the list (hopefully by pushing) later.
    if(this.lastFetch === null) {
      recordings.fetch({
        success: function(collection) {
          context.lastFetch = collection;

          var recordingsView = new RecordingsView({
            el: '#recordings-index',
            collection: context.lastFetch
          });
          recordingsView.render();
        },
        error: function(error) {
          alert(error);
        }
      });
    }
  },

  show: function(chanid, timestamp) {
    if(this.lastFetch === null) {
      var recordings = new Recordings();
      var context = this;

      recordings.fetch({
        success: function(collection) {
          context.lastFetch = collection;
        }
      });
    }

    var model = this.lastFetch.get(chanid + "_" + timestamp);
    var recordingView = new RecordingView({
      el: '#recordings-show',
      model: model
    });
    recordingView.render();
  }
});
var recordingsRouter = new RecordingsRouter();


text:
package com.jnape.palatable.lambda.functor.builtin;

import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.traitor.annotations.TestTraits;
import com.jnape.palatable.traitor.framework.Subjects;
import com.jnape.palatable.traitor.runners.Traits;
import org.junit.Test;
import org.junit.runner.RunWith;
import testsupport.traits.ApplicativeLaws;
import testsupport.traits.Equivalence;
import testsupport.traits.FunctorLaws;
import testsupport.traits.MonadLaws;
import testsupport.traits.MonadRecLaws;
import testsupport.traits.MonadWriterLaws;

import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;
import static com.jnape.palatable.lambda.functor.builtin.Writer.listen;
import static com.jnape.palatable.lambda.functor.builtin.Writer.tell;
import static com.jnape.palatable.lambda.functor.builtin.Writer.writer;
import static com.jnape.palatable.lambda.monoid.builtin.Join.join;
import static com.jnape.palatable.traitor.framework.Subjects.subjects;
import static org.junit.Assert.assertEquals;
import static testsupport.traits.Equivalence.equivalence;

@RunWith(Traits.class)
public class WriterTest {

    @TestTraits({FunctorLaws.class, ApplicativeLaws.class, MonadLaws.class, MonadRecLaws.class, MonadWriterLaws.class})
    public Subjects<Equivalence<Writer<String, ?>>> testSubject() {
        Fn1<Writer<String, ?>, Object> runWriter = w -> w.runWriter(join());
        return subjects(equivalence(tell("foo"), runWriter),
                        equivalence(listen(1), runWriter),
                        equivalence(writer(tuple(1, "foo")), runWriter));
    }

    @Test
    public void tellListenInteraction() {
        assertEquals(tuple(1, "hello, world!"),
                     tell("hello, ")
                             .discardL(listen(1))
                             .discardR(tell("world!"))
                             .runWriter(join()));
    }
}


text:
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { DataService } from '../../shared/services/data.service';
import { IDivision } from '../../shared/interfaces';

@Component({
    selector: 'my-division-list',
    templateUrl: './list-division.component.html',
    styleUrls: ['./list-division.component.css']
})
export class DivisionListComponent implements OnInit {
    private divisions: IDivision[];
    private slice: string;

    constructor(private dataService: DataService,
        private location: Location){

    }

    ngOnInit() {
        this.slice = '/';
        this.getData();
    }

    getData() {
        this.dataService.getDivisions().subscribe((result: IDivision[]) => {
            this.divisions = result;
        }, error => console.error('Error: ' + error));
    }

    onGoBack() {
        this.location.back();
    }

    onRefreshData() {
        this.getData();
    }
}


text:
from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', RedirectView.as_view(url='/search/')),
    # url(r'^beeradvocate_crawl/', include('beeradvocate_crawl.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^search/', include('haystack.urls')),

)


text:
This set of tasks perform file copy related actions

## File Copy with Filters

This task finds all the files that match a given pattern via a recursive search of the source folder. The selected files are the copied to the single target folder e.g. find all the DACPAC file and place them in the **.\drops\db folder**

This task was developed as a short term fix around the time of TFS 2015.1. In this and earlier versions of vNext build the 'Publish Build Artifacts' searched for files, copied them to the staging folder and then onto the drops location. In later versions these steps are split into two task, one to build the folder structure, the other to move the content. This split functionality is what this task was designed to assist with.

The reason to use still use this task over the built in one is that it flattens folder structures by default. Useful to get all the files of a single type into a single folder.

### Usage

- Source Folder e.g. $(build.sourcesdirectory)
- Target Folder e.g. $(build.artifactstagingdirectory)\$(ArtifactName)\BlackMarble.Victory.Services.DACPackage_Packaged
- File types e.g. *.dacpac
- Filter on e.g. a PowerShell filter

In effect this task wrappers [Get-ChildItem](https://technet.microsoft.com/en-us/library/hh849800.aspx), see this commands online documentation for the filtering options

This tasks would usually be followed by a 'Publish Build Artifacts' task to move the contents to the build drop.

## GetArtifactFromUncShareTask

# IMPORTANT

**THIS TASK CAN ONLY COPY BUILD ARTIFACTS FROM UNC FILESHARE BASED BUILD DROP LOCATIONS.**

You will get an error in the form

> Cannot access source path [#/475339/atrifact]** if you try to use it with a server build drop

***

With the advent of TFS 2015.2 RC (and the associated VSTS release) we have seen the short term removal of the 'External TFS Build' option for the Release Management artifacts source. This causes me a bit of a problem as I wanted to try out the new on premises vNext based Release Management features on 2015.2, but don't want to place the RC on my production server (though there is go live support). Also the ability to get artifacts from an on premises TFS instance when using VSTS open up a number of scenarios, something I know some of my clients had been investigating.

To get around this blocker I have written a vNext build task that does the getting of a build artifact from the UNC drop. It supports both XAML and vNext builds. Thus replacing the built in artifact linking features.

## Usage
To use the new task:

- Get the task from my vNextBuild repo (build using the instructions on the repo's wiki) and install it on your TFS 2015.2 instance (also use the notes on the repo's wiki).
- In your build, disable the auto getting of the artifacts for the environment (though in some scenarios you might choose to use both the built in linking and my custom task)
- Add the new task to your environment's release process, the parameters are
    - TFS Uri – the Uri of the TFS server inc. The TPC name
    - Team Project – the project containing the source build
    - Build Definition name – name of the build (can be XAML or vNext)
    - Artifact name – the name of the build artifact (seems to be 'drop' if a XAML build)
    - Build Number – default is to get the latest successful completed build, but you can pass a specific build number
    - Username/Password – if you don't want to use default credentials (the user the build agent is running as), these are the ones used. These are passed as 'basic auth' so can be used against an on prem TFS (if basic auth is enabled in IIS)  or VSTS (with alternate credentials enabled).

When the task runs it should drop artifacts in the same location as the standard mechanism, so can be picked up by any other tasks on the release pipeline using a path similar to **$(System.DefaultWorkingDirectory)\buildname\drop**

## Limitations
The task in its current form does not provide any linking of artifacts to the build reports, or allow the selection of build versions when the release is created. This removing audit trail features.

However, it does provide a means to get a pair of TFS servers working together, so can certainly enable some R&D scenarios while we await 2015.2 to RTM and/or the 'official' linking of External TFS builds as artifact

## Update XML file

This task edits the value if an attribute in a XML file based on a XPath filter

The prime use for this is to set environment specific value in web.config or app.config files

### Usage

- Filename e.g. $(SYSTEM.ARTIFACTSDIRECTORY)/myfile.dll.config [can include wildcards $(SYSTEM.ARTIFACTSDIRECTORY)/*.config]
- XPath e.g. /configuration/appSettings/add[@key='A variable']
- Attribute e.g. value [optional: if left blank the InnerText on the selected node will be updated]
- Value e.g. 'the new value'
- Recurse e.g. True (whether any wildcards in the filename should be searched for recursivally)


text:
package org.apache.shardingsphere.sharding.api.sharding;

import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmPropertiesAware;

/**
 * Sharding auto table algorithm.
 */
public interface ShardingAutoTableAlgorithm extends ShardingSphereAlgorithmPropertiesAware {

    /**
     * Get auto tables amount.
     *
     * @return the auto tables amount
     */
    int getAutoTablesAmount();
}


text:
In this benchmark we explore optimizing the block consisting of 4 LSTM layers forllowed by a pooling done on the sequence, followed by 4 other LSTM layers. We propose a version on mutli GPU, and compare it to a single GPU version implemented using Nvidia's cuDNN library.

The following figure shows the 4LSTM-MaxPool-4LSTM block, and our optimization approach based on :

1. Tranforming loops to discover fusable operators.
2. Fusing the 4LSTM, MaxPool and 4LSTM parts.
3. Applying Loop Skewing and parallelization on the outer loops.

`Note that this approach didn't yield good results and is almost 4x slower than the cuDNN version.`

![Multi GPU 4LSTM-MaxPool-4LSTM Architecture](imgs/multigpu_lstm.png "Multi GPU 4LSTM-MaxPool-4LSTM")

## Folder Structure
The folder contains these files :
 1. `configuration.h` : which contains constants to be set for the block.
 2. `cudnn_functions.cu` : contains functions used to construct the architecture using cuDNN.
 3. `cuda_wrappers.cpp` : contains wrappers for cuda functions.
 4. `multi_gpu_deepspeech_kernels.cu` : contains the Multi GPU version kernels.
 5. `deepspeech_wrapper_comparison.cu` : contains the MultiGPU version as well as a call to the cuDNN version + comparison of execution times and output results.

## How to Run
 Ton compile the code you need to use 3 GPUs, for that.
### Set the Environment
Set the `CUDA_VISIBLE_DEVICES` environment variable to 0,1,2 (for using GPU devices 0, 1 and 2), this allows the code to have access to the GPUs of your choice, you can execute `nvidia-smi` to check what devices are free.
```
export CUDA_VISIBLE_DEVICES=0,1,2
```
### Compile and Run the Code
For that, run :
```
nvcc -std=c++11 deepspeech_wrapper_comparison.cu -lcublas -lcudnn -Xcompiler -fopenmp
```
This will compile the code and generate the `a.out` executable file.

Run the code :
```
./a.out
```
This will execute both the Multi GPU and the cuDNN versions and give their execution times. Note that you can tune the `GEMM_BATCH` parameter in the `configuration.h` file to get the best execution time for Multi GPU, `GEMM_BATCH` has to be a multiple of `SEQ_LENGTH/2`

If `CHECK_ERROR_DIFFERENCE` is set to 1 in the `configuration.h` file, a comparison of the outputs (cuDNN's and MultiGPU's) will be made. In this case, it's possible to see how in the first sequences we have a small difference in the output values, these differences get bigger as we go forward in the sequences, this is caused by numerical instability due to floating point calculations.


text:
module AdminBrokenLinksReportingHelper
  def govspeak_with_links(*links)
    "Some content with links: ##{build_links(links).join(' ')}"
  end

  def build_links(links)
    links.each_with_index.map { |link, i| "[Link #{i}](#{link})" }
  end
end

World(AdminBrokenLinksReportingHelper)


text: elm make Main.elm --output ../public/generated-app.js


text:
<?php

namespace TmlpStats\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;
use TmlpStats as Models;
use TmlpStats\Api;
use TmlpStats\Domain;

class UpdatePromise extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'data:fix-promise {centerId} {game} {date} {new}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update promise value in all stashes and active reports';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $centerId = $this->argument('centerId');
        $center = Models\Center::find($centerId);
        if (!$center) {
            $this->line("Unable to find center {$centerId}.");
            return false;
        }

        $gameStr = strtoupper($this->argument('game'));
        $game = strtolower($gameStr);
        if (!in_array($game, Domain\Scoreboard::GAME_KEYS)) {
            $this->line("{$game} is not a valid game.");
            return false;
        }

        try{
            $dateStr = $this->argument('date');
            $reportingDate = Carbon::parse($dateStr)->startOfDay();
        } catch(\Exception $e) {
            $this->line("{$dateStr} is not a valid date.");
            return false;
        }

        $new = $this->argument('new');
        if (!is_numeric($new)) {
            $this->line("New value '{$new}' is not a valid number.");
            return false;
        }

        $this->line("Updating {$gameStr} promise for {$center->name} on {$dateStr}");

        // Update official scoreboard
        $csds = Models\CenterStatsData::promise()
            ->byCenter($center)
            ->reportingDate($reportingDate)
            ->official()
            ->with('statsReport')
            ->get();

        if ($csds->isEmpty()) {
            $this->line("Unable to find promise for {$dateStr}.");
            return false;
        }

        // If we have more than 1, there was a new promise.
        // Find the one from the most recent reporting date
        $csd = $csds[0];
        if (count($csds) > 1) {
            foreach ($csds as $c) {
                if ($c->statsReport->reportingDate->gt($csd->statsReport->reportingDate)) {
                    $csd = $c;
                }
            }
        }

        if ($csd->$game == $new) {
            $this->line("Stats report value already set to {$new}.");
            return true;
        }

        // Get the original scoreboard for calculating points change
        // This is the week the promise is for, whereas $csd->statsReport is the week the pormise was made
        $weeksReport = Models\StatsReport::byCenter($center)
            ->reportingDate($csd->reportingDate)
            ->official()
            ->first();

        $originalScoreboard = null;
        if ($weeksReport) {
            $originalScoreboard = App::make(Api\LocalReport::class)->getWeekScoreboard($weeksReport);
        }

        $this->line("Changing promise {$csd->id} made on stats report {$csd->statsReportId} from {$csd->reportingDate->toDateString()} from {$csd->$game} to {$new}");
        $csd->$game = $new;
        $csd->save();

        // Update stashes
        $stash = Models\SubmissionData::centerDate($center, $csd->reportingDate)
            ->typeId('scoreboard_week', $reportingDate->toDateTimeString())
            ->first();

        if ($stash) {
            $sb = Domain\Scoreboard::fromArray($stash->data);

            $stashedValue = $sb->game($game)->promise();
            if ($stashedValue != $new) {
                $this->line("Changing stash {$stash->id} from {$stashedValue} to {$new}");
                $sb->setValue($game, 'promise', $new);
                $stash->data = $sb->toNewArray();
                $stash->save();
            } else {
                $this->line("Stashed value already set to {$new}.");
            }
        } else {
            $this->line("No stashes found.");
        }

        // Did this impact the scoreboard points/rating?
        $newScoreboard = null;
        if ($weeksReport) {
            App::make(Api\Context::class)->clearEncapsulations(); // clear the cache
            $newScoreboard = App::make(Api\LocalReport::class)->getWeekScoreboard($weeksReport);
        }

        if (!$weeksReport) {
            $this->line("No report submitted for {$dateStr} so points were not affected.");
        } elseif ($newScoreboard->points() != $originalScoreboard->points()) {
            $ratingMsg = '';
            if ($newScoreboard->rating() != $originalScoreboard->rating()) {
                $ratingMsg = " and rating {$originalScoreboard->rating()} to {$newScoreboard->rating()}";
            }
            $this->line("New promise changed points from {$originalScoreboard->points()} to {$newScoreboard->points()}{$ratingMsg}.");
        } else {
            $this->line("New promise did not change the points or rating.");
        }
    }
}