text:
* [
      ResearchKit
      /
      ResearchKit
](https://github.com/ResearchKit/ResearchKit):
      ResearchKit is an open source software framework that makes it easy to create apps for medical research or for other research projects.

* [
      hackers-painters
      /
      samurai-native
](https://github.com/hackers-painters/samurai-native):
      Bring web standards to native platform

* [
      JadenGeller
      /
      Helium
](https://github.com/JadenGeller/Helium):
      A floating browser window for OS X

* [
      AFNetworking
      /
      AFNetworking
](https://github.com/AFNetworking/AFNetworking):
      A delightful iOS and OS X networking framework

* [
      jamztang
      /
      CSStickyHeaderFlowLayout
](https://github.com/jamztang/CSStickyHeaderFlowLayout):
      UICollectionView replacement of UITableView. Do even more like Parallax Header, Sticky Section Header. Made for iOS 7.

* [
      hyperoslo
      /
      Sync
](https://github.com/hyperoslo/Sync):
      Modern JSON synchronization to Core Data

* [
      Yalantis
      /
      Context-Menu.iOS
](https://github.com/Yalantis/Context-Menu.iOS):
* [
      ResearchKit
      /
      AppCore
](https://github.com/ResearchKit/AppCore):
      Core code shared by the initial ResearchKit apps.

* [
      bryankeller
      /
      BLKFlexibleHeightBar
](https://github.com/bryankeller/BLKFlexibleHeightBar):
      Create condensing header bars like those seen in the Facebook, Square Cash, and Safari iOS apps.

* [
      rs
      /
      SDWebImage
](https://github.com/rs/SDWebImage):
      Asynchronous image downloader with cache support with an UIImageView category

* [
      ChenYilong
      /
      CollectionViewClassifyMenu
](https://github.com/ChenYilong/CollectionViewClassifyMenu):
      CollectionView做的两级菜单,可以折叠第二级菜单

* [
      jdg
      /
      MBProgressHUD
](https://github.com/jdg/MBProgressHUD):
      MBProgressHUD + Customizations

* [
      ReactiveCocoa
      /
      ReactiveCocoa
](https://github.com/ReactiveCocoa/ReactiveCocoa):
      A framework for composing and transforming streams of values

* [
      stepanhruda
      /
      ios-simulator-app-installer
](https://github.com/stepanhruda/ios-simulator-app-installer):
      Create an OS X app that installs your iOS app into iOS Simulator

* [
      nicklockwood
      /
      iCarousel
](https://github.com/nicklockwood/iCarousel):
      A simple, highly customisable, data-driven 3D carousel for iOS and Mac OS

* [
      SnapKit
      /
      Masonry
](https://github.com/SnapKit/Masonry):
      Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout

* [
      CoderMJLee
      /
      MJRefresh
](https://github.com/CoderMJLee/MJRefresh):
      The easiest way to use pull-to-refresh

* [
      romaonthego
      /
      RESideMenu
](https://github.com/romaonthego/RESideMenu):
      iOS 7/8 style side menu with parallax effect.

* [
      jessesquires
      /
      JSQMessagesViewController
](https://github.com/jessesquires/JSQMessagesViewController):
      An elegant messages UI library for iOS

* [
      erica
      /
      NSDate-Extensions
](https://github.com/erica/NSDate-Extensions):
      Practical real-world dates

* [
      mogujie
      /
      TeamTalk
](https://github.com/mogujie/TeamTalk):
      TeamTalk is a solution for enterprise IM

* [
      ccgus
      /
      fmdb
](https://github.com/ccgus/fmdb):
      A Cocoa / Objective-C wrapper around SQLite

* [
      realm
      /
      realm-cocoa
](https://github.com/realm/realm-cocoa):
      Realm is a mobile database: a replacement for Core Data & SQLite

* [
      mwaterfall
      /
      MWPhotoBrowser
](https://github.com/mwaterfall/MWPhotoBrowser):
      A simple iOS photo browser with optional grid view, captions and selections.

* [
      Mantle
      /
      Mantle
](https://github.com/Mantle/Mantle):
      Model framework for Cocoa and Cocoa Touch

#### go
* [
      knadh
      /
      niltalk
](https://github.com/knadh/niltalk):
      A simple multi-room disposable chat service written in Go that uses WebSockets for communication.

* [
      docker
      /
      docker
](https://github.com/docker/docker):
      Docker - the open-source application container engine

* [
      likexian
      /
      stathub-go
](https://github.com/likexian/stathub-go):
      A smart Hub for holding server Stat

* [
      syncthing
      /
      syncthing
](https://github.com/syncthing/syncthing):
      Open Source Continuous File Synchronization

* [
      github
      /
      git-lfs
](https://github.com/github/git-lfs):
      Git extension for versioning large files

* [
      letsencrypt
      /
      boulder
](https://github.com/letsencrypt/boulder):
      An ACME-based CA, written in Go.

* [
      GoogleCloudPlatform
      /
      kubernetes
](https://github.com/GoogleCloudPlatform/kubernetes):
      Container Cluster Manager from Google

* [
      dshills
      /
      goauto
](https://github.com/dshills/goauto):
      Go package for building automation tools

* [
      dghubble
      /
      sling
](https://github.com/dghubble/sling):
      A Go REST client library for creating and sending requests.

* [
      DavidHuie
      /
      httpq
](https://github.com/DavidHuie/httpq):
      Buffer HTTP requests and replay them later

* [
      avelino
      /
      awesome-go
](https://github.com/avelino/awesome-go):
      A curated list of awesome Go frameworks, libraries and software

* [
      labstack
      /
      echo
](https://github.com/labstack/echo):
      Fast HTTP router and micro web framework

* [
      golang
      /
      go
](https://github.com/golang/go):
      The Go programming language

* [
      astaxie
      /
      build-web-application-with-golang
](https://github.com/astaxie/build-web-application-with-golang):
      A golang ebook intro how to build a web with golang

* [
      square
      /
      certstrap
](https://github.com/square/certstrap):
      Tools to bootstrap CAs, certificate requests, and signed certificates.

* [
      square
      /
      p2
](https://github.com/square/p2):
      Platypus Platform: Tools for Scalable Deployment

* [
      influxdb
      /
      influxdb
](https://github.com/influxdb/influxdb):
      Scalable datastore for metrics, events, and real-time analytics

* [
      inconshreveable
      /
      ngrok
](https://github.com/inconshreveable/ngrok):
      Introspected tunnels to localhost

* [
      tj
      /
      robo
](https://github.com/tj/robo):
      Simple YAML-based task runner written in Go.

* [
      justinas
      /
      nosurf
](https://github.com/justinas/nosurf):
      CSRF protection middleware for Go.

* [
      gizak
      /
      termui
](https://github.com/gizak/termui):
      Golang terminal dashboard

* [
      limetext
      /
      lime
](https://github.com/limetext/lime):
      Open source API-compatible alternative to the text editor Sublime Text

* [
      google
      /
      cadvisor
](https://github.com/google/cadvisor):
      Analyzes resource usage and performance characteristics of running containers.

* [
      github
      /
      hub
](https://github.com/github/hub):
      hub helps you win at git.

* [
      spf13
      /
      hugo
](https://github.com/spf13/hugo):
      A Fast and Flexible Static Site Generator built with love by spf13 in GoLang

#### javascript
* [
      bevacqua
      /
      dragula
](https://github.com/bevacqua/dragula):
      Drag and drop so simple it hurts

* [
      box
      /
      t3js
](https://github.com/box/t3js):
      A minimal component-based JavaScript framework

* [
      callmecavs
      /
      layzr.js
](https://github.com/callmecavs/layzr.js):
      A small, fast, modern, and dependency-free library for lazy loading images.

* [
      ecomfe
      /
      fontmin
](https://github.com/ecomfe/fontmin):
      Minify font seamlessly

* [
      airbnb
      /
      javascript
](https://github.com/airbnb/javascript):
      JavaScript Style Guide

* [
      facebook
      /
      react-native
](https://github.com/facebook/react-native):
      A framework for building native apps with React.

* [
      getify
      /
      You-Dont-Know-JS
](https://github.com/getify/You-Dont-Know-JS):
      A book series on JavaScript. @YDKJS on twitter.

* [
      caolan
      /
      highland
](https://github.com/caolan/highland):
      High-level streams library for Node.js and the browser

* [
      mbostock
      /
      d3
](https://github.com/mbostock/d3):
      A JavaScript visualization library for HTML and SVG.

* [
      angular
      /
      angular.js
](https://github.com/angular/angular.js):
      HTML enhanced for web apps

* [
      facebook
      /
      react
](https://github.com/facebook/react):
      A declarative, efficient, and flexible JavaScript library for building user interfaces.

* [
      iliakan
      /
      javascript-nodejs
](https://github.com/iliakan/javascript-nodejs):
      JavaScript.ru on IO.JS

* [
      driftyco
      /
      ionic
](https://github.com/driftyco/ionic):
      Advanced HTML5 mobile development framework and SDK. Build incredible hybrid apps with web technologies you already know and love. Best friends with AngularJS.

* [
      tsx
      /
      shireframe
](https://github.com/tsx/shireframe):
      Declarative wireframes for programmers, based on web technologies. Pull requests are welcome!

* [
      gorhill
      /
      uBlock
](https://github.com/gorhill/uBlock):
      uBlock Origin - An efficient blocker for Chromium and Firefox. Fast and lean.

* [
      lovelle
      /
      jquery-chat
](https://github.com/lovelle/jquery-chat):
      100% Javascript realtime chat like facebook/gmail web style built with jQuery UI + Node.js + Socket.IO

* [
      angular
      /
      angular
](https://github.com/angular/angular):
* [
      babel
      /
      babel
](https://github.com/babel/babel):
      Babel is a compiler for writing next generation JavaScript.

* [
      phoboslab
      /
      wipeout
](https://github.com/phoboslab/wipeout):
      WipEout (PSX) Model Viewer in WebGL/Three.js

* [
      uber
      /
      node-stap
](https://github.com/uber/node-stap):
      Tools for analyzing Node.js programs with SystemTap

* [
      webpack
      /
      webpack
](https://github.com/webpack/webpack):
      Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jade, coffee, css, less, ... and your custom stuff.

* [
      gulpjs
      /
      gulp
](https://github.com/gulpjs/gulp):
      The streaming build system

* [
      analog-nico
      /
      hpp
](https://github.com/analog-nico/hpp):
      Express middleware to protect against HTTP Parameter Pollution attacks

* [
      meteor
      /
      meteor
](https://github.com/meteor/meteor):
      Meteor, an ultra-simple, database-everywhere, data-on-the-wire, pure-Javascript web framework.

* [
      martinandert
      /
      react-inline
](https://github.com/martinandert/react-inline):
      Transform inline styles defined in JavaScript modules into static CSS code and class names so they become available to the `className` prop of React elements.

#### ruby
* [
      eliotsykes
      /
      rspec-rails-examples
](https://github.com/eliotsykes/rspec-rails-examples):
      RSpec cheatsheet & Rails app: Learn how to expertly test Rails apps from a model codebase

* [
      FlyoverWorks
      /
      storytime
](https://github.com/FlyoverWorks/storytime):
      Storytime is a Rails 4+ CMS and blogging engine, with a core focus on content. It is built and maintained by @flyoverworks.

* [
      rails
      /
      rails
](https://github.com/rails/rails):
      Ruby on Rails

* [
      KrauseFx
      /
      fastlane
](https://github.com/KrauseFx/fastlane):
      Connect all iOS deployment tools into one streamlined workflow

* [
      Homebrew
      /
      homebrew
](https://github.com/Homebrew/homebrew):
      The missing package manager for OS X.

* [
      chrisvfritz
      /
      isabella
](https://github.com/chrisvfritz/isabella):
      A voice-computing assistant built in Ruby.

* [
      solnic
      /
      transproc
](https://github.com/solnic/transproc):
      Transform Ruby objects in functional style

* [
      rapid7
      /
      metasploit-framework
](https://github.com/rapid7/metasploit-framework):
      Metasploit Framework

* [
      altmetric
      /
      embiggen
](https://github.com/altmetric/embiggen):
      A Ruby library to expand shortened URLs

* [
      jekyll
      /
      jekyll
](https://github.com/jekyll/jekyll):
      Jekyll is a blog-aware, static site generator in Ruby

* [
      discourse
      /
      discourse
](https://github.com/discourse/discourse):
      A platform for community discussion. Free, open, simple.

* [
      janlelis
      /
      sig
](https://github.com/janlelis/sig):
      Ensures sane method arguments & results for Ruby

* [
      gitlabhq
      /
      gitlabhq
](https://github.com/gitlabhq/gitlabhq):
      GitLab is version control for your server

* [
      jnunemaker
      /
      flipper
](https://github.com/jnunemaker/flipper):
      feature flipping for ANYTHING

* [
      thoughtbot
      /
      guides
](https://github.com/thoughtbot/guides):
      A guide for programming in style.

* [
      edelpero
      /
      lupa
](https://github.com/edelpero/lupa):
      Lupa lets you create simple, robust and scaleable search filters with ease using regular Ruby classes and object oriented design patterns.

* [
      alt3
      /
      cakebox
](https://github.com/alt3/cakebox):
      Multi-Framework PHP Development Environment

* [
      ruby
      /
      ruby
](https://github.com/ruby/ruby):
      The Ruby Programming Language

* [
      sass
      /
      sass
](https://github.com/sass/sass):
      Sass makes CSS fun again.

* [
      rails-api
      /
      rails-api
](https://github.com/rails-api/rails-api):
      Rails for API only applications

* [
      elastic
      /
      logstash
](https://github.com/elastic/logstash):
      logstash - logs/event transport, processing, management, search.

* [
      cantino
      /
      huginn
](https://github.com/cantino/huginn):
      Build agents that monitor and act on your behalf. Your agents are standing by!

* [
      caskroom
      /
      homebrew-cask
](https://github.com/caskroom/homebrew-cask):
      A CLI workflow for the administration of Mac applications distributed as binaries

* [
      progrium
      /
      ruby-jwt
](https://github.com/progrium/ruby-jwt):
      JSON Web Token implementation in Ruby

* [
      spree
      /
      spree
](https://github.com/spree/spree):
      Spree is a complete open source e-commerce solution for Ruby on Rails.


text:
package it.unimi.dsi.fastutil.io;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

/** Simple, fast and repositionable byte array input stream that multiplexes its content among several arrays.
 *
 * This class is significantly slower than {@link FastByteArrayInputStream},
 * but it can hold 256 PiB of data. The relevant constructor is {@link #FastMultiByteArrayInputStream(InputStream, long)},
 * which fetches a stream and loads it into a sequence of byte arrays.
 *
 * @author Sebastiano Vigna
 * @author Paolo Boldi
s */

public class FastMultiByteArrayInputStream extends MeasurableInputStream implements RepositionableStream {

	/** The number of bits of an array slice index. */
	public static final int SLICE_BITS = 30;

	/** The maximum length of an array slice. */
	public static final int SLICE_SIZE = 1 << SLICE_BITS;

	/** The mask to retrieve a slice offset. */
	public static final int SLICE_MASK = SLICE_SIZE - 1;

	/** The array of arrays backing the input stream, plus an additional {@code null} entry. */
	public byte[][] array;

	/** The current array. */
	public byte[] current;

	/** The number of valid bytes in {@link #array}. */
	public long length;

	/** The current position. */
	private long position;

	/** Creates a new multi-array input stream loading it from a measurable input stream.
	 *
	 * @param is the input stream that will fill the array.
	 */

	public FastMultiByteArrayInputStream(final MeasurableInputStream is) throws IOException {
		this(is, is.length());
	}

	/** Creates a new multi-array input stream loading it from an input stream.
	 *
	 * @param is the input stream that will fill the array.
	 * @param size the number of bytes to be read from {@code is}.
	 */

	public FastMultiByteArrayInputStream(final InputStream is, long size) throws IOException {
		length = size;
		array = new byte[(int)((size + SLICE_SIZE - 1) / SLICE_SIZE) + 1][];

		for(int i = 0; i < array.length - 1; i++) {
			array[i] = new byte[size >= SLICE_SIZE ? SLICE_SIZE : (int)size];
			// It is important *not* to use is.read() directly because of bug #6478546
			if (read(is, array[i]) != array[i].length) throw new EOFException();
			size -= array[i].length;
		}

		current = array[0];
	}

  private static long read(final InputStream is, final byte[] a) throws IOException {
    if (a.length == 0) return 0L;

    int read = 0, result;
    do {
      result = is.read(a, read, Math.min(a.length - read, 1024 * 1024));
      if (result < 0) return read;
      read += result;
    } while(read < a.length);

    return read;
  }

  /** Creates a new multi-array input stream sharing the backing arrays of another multi-array input stream.
	 *
	 * @param is the multi-array input stream to replicate.
	 */
	public FastMultiByteArrayInputStream(final FastMultiByteArrayInputStream is) {
		this.array = is.array;
		this.length = is.length;
		this.current = array[0];
	}

	/** Creates a new multi-array input stream using a given array.
	 *
	 * @param array the backing array.
	 */
	public FastMultiByteArrayInputStream(final byte[] array) {
		if (array.length == 0) this.array = new byte[1][];
		else {
			this.array = new byte[2][];
			this.array[0] = array;
			this.length = array.length;
			this.current = array;
		}
	}

	/** Returns the number of bytes that can be read (or skipped over) from this input stream without blocking.
	 *
	 * <p>Note that this number may be smaller than the number of bytes actually
	 * available from the stream if this number exceeds {@link Integer#MAX_VALUE}.
	 *
	 * @return the minimum among the number of available bytes and {@link Integer#MAX_VALUE}.
	 */

	@Override
	public int available() {
		return (int)Math.min(Integer.MAX_VALUE, length - position);
	}

	@Override
	public long skip(long n) {
		if (n > length - position) n = length - position;
		position += n;
		updateCurrent();
		return n;
	}

	@Override
	public int read() {
		if (length == position) return -1;
		final int disp = (int)(position++ & SLICE_MASK);
		if (disp == 0) updateCurrent();
		return current[disp] & 0xFF;
	}

	@Override
	public int read(final byte[] b, int offset, final int length) {
		final long remaining = this.length - position;
		if (remaining == 0) return length == 0 ? 0 : -1;
		int n = (int)Math.min(length, remaining);
		final int m = n;

		for(;;) {
			final int disp = (int)(position & SLICE_MASK);
			if (disp == 0) updateCurrent();
			final int res = Math.min(n, current.length - disp);
			System.arraycopy(current, disp, b, offset, res);

			n -= res;
			position += res;
			if (n == 0) return m;
			offset += res;
		}
	}

	private void updateCurrent() {
		current = array[(int)(position >>> SLICE_BITS)];
	}

	@Override
	public long position() {
		return position;
	}

	@Override
	public void position(final long newPosition) {
		position = Math.min(newPosition, length);
		updateCurrent();
	}

	@Override
	public long length() throws IOException {
		return length;
	}

	/** NOP. */
	@Override
	public void close() {}

	@Override
	public boolean markSupported() {
		return false;
	}

	@Override
	public void mark(final int dummy) {
		throw new UnsupportedOperationException();
	}

	@Override
	public void reset() {
		throw new UnsupportedOperationException();
	}
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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.modeshape.jcr.value.binary;

import java.io.File;
import org.junit.BeforeClass;
import org.modeshape.common.util.FileUtil;

public class TransientBinaryStoreTest extends FileSystemBinaryStoreTest {

    @BeforeClass
    public static void beforeEach() {
        store = TransientBinaryStore.get();
        directory = TransientBinaryStore.TRANSIENT_STORE_DIRECTORY;
        FileUtil.delete(directory);
        directory.mkdirs();
        trash = new File(directory, FileSystemBinaryStore.TRASH_DIRECTORY_NAME);
        store.setMinimumBinarySizeInBytes(MIN_BINARY_SIZE);
        store.setMimeTypeDetector(DEFAULT_DETECTOR);
        print = false;
    }
}


text:
document.addEventListener('DOMContentLoaded', function() {
  var $root = document.documentElement;
  var template = $root.dataset.template;

  // Load iframes
  var $footerIframes = document.querySelectorAll('.footer-iframe');

  Array.prototype.forEach.call($footerIframes, function($iframe) {
    var src = $iframe.dataset.src;
    $iframe.src = src;
  });

  // Menu: Search
  var $searchInput = document.getElementById('menu-search-input');
  var $menuList = document.getElementById('menu-list');
  var $menuItems = document.querySelectorAll('.menu-item');
  var isFocused = false;
  var isSearching = false;
  var isModaling = false;
  var currentMatch = -1;
  var matches = initializeMatches($menuItems);

  if ($searchInput) {
    $searchInput.addEventListener('focus', function(event) {
      isFocused = true;
      isSearching = true;
    });

    $searchInput.addEventListener('blur', function(event) {
      isFocused = false;
      if (this.value === '') {
        globalReset();
      }
    });

    $searchInput.addEventListener('keyup', function(event) {
      var query = this.value.toLowerCase();
      isFocused = (this === document.activeElement);

      if (isFocused) {
        isSearching = true;

        if (query.length > 0) {
          matches = [];
          currentMatch = -1;
          $menuList.classList.add('is-searching');
          Array.prototype.forEach.call($menuItems, function($el, index) {
            var propertyName = $el.dataset.propertyName;
            var isMatch = highlightQuery($el, propertyName, query);

            if (isMatch) {
              matches.push({
                DOMIndex: index,
                propertyName: propertyName,
              });
            }
          });
        } else {
          $menuList.classList.remove('is-searching');
          Array.prototype.forEach.call($menuItems, function($el) {
            var $elName = $el.querySelector('.item-name');
            $elName.innerHTML = $el.dataset.propertyName;
          });
        }
      }
    });

    window.addEventListener('click', function(event) {
      if (!isFocused) {
        isSearching = false;
        cleanMenu($menuItems, false, true);
      }
    });

    window.addEventListener('keydown', function(event) {
      var key = event.code || event.key || false;

      switch (key) {
      case 'Enter':
        if (isSearching && currentMatch > -1) {
          event.preventDefault();
          var propertyName = matches[currentMatch].propertyName;
          var $target = document.getElementById(propertyName);

          if ($target) {
            $target.scrollIntoView();
          } else {
            window.location = window.location.origin + '/property/' + propertyName;
          }
        }
        break;
      case 'Escape':
        if (isModaling) {
          closeModal();
        } else {
          isSearching = false;
          globalReset();
        }
        break;
      case 'ArrowUp':
      case 'ArrowDown':
        if (isSearching) {
          event.preventDefault();
          if (isFocused) {
            $searchInput.blur();
          }
          var increment = (key === 'ArrowDown');
          currentMatch = navigateMenu($menuItems, matches, currentMatch, increment);

          if (currentMatch === -1) {
            $searchInput.focus();
          }
          break;
        }
      }
    });

    function globalReset() {
      isFocused = false;
      $searchInput.value = '';
      $searchInput.blur();
      currentMatch = -1;
      matches = initializeMatches($menuItems);
      $menuList.classList.remove('is-searching');
      cleanMenu($menuItems, true, true);
    }
  }

  // Menu: Shadows
  var $menuUl = document.getElementById('menu-list-ul');
  var $menuShadowTop = document.getElementById('menu-shadow-top');
  var $menuShadowBottom = document.getElementById('menu-shadow-bottom');
  var menuThrottle = null;

  if ($menuUl) {
    $menuUl.addEventListener('scroll', function(event) {
      clearTimeout(menuThrottle);
      throttle = setTimeout(setMenuShadows(), 100);
    });

    function setMenuShadows() {
      var scrollTop = $menuUl.scrollTop;
      var height = $menuUl.offsetHeight;
      var fullHeight = $menuUl.scrollHeight;
      var maxScroll = fullHeight - height;
      var threshold = 200;
      var topFactor = 0;
      var bottomFactor = 1;

      if (scrollTop > threshold) {
        topFactor = 1;
      } else {
        topFactor = scrollTop / threshold;
      }

      if (scrollTop < maxScroll - threshold) {
        bottomFactor = 1;
      } else {
        var fromBottom = maxScroll - scrollTop;
        bottomFactor = fromBottom / threshold;
      }

      $menuShadowTop.style.opacity = topFactor;
      $menuShadowTop.style.transform = 'scaleY(' + topFactor + ')';
      $menuShadowBottom.style.opacity = bottomFactor;
      $menuShadowBottom.style.transform = 'scaleY(' + bottomFactor + ')';
    }
    setMenuShadows();
  }

  // Menu: Mobile
  var $menuNav = document.getElementById('menu-nav');
  var $menuNavOpen = document.getElementById('menu-nav-open');
  var $menuNavClose = document.getElementById('menu-nav-close');

  if ($menuNav) {
    $menuNavOpen.addEventListener('click', function(event) {
      $menuNav.classList.add('is-active');
    });

    $menuNavClose.addEventListener('click', function(event) {
      $menuNav.classList.remove('is-active');
    });

    Array.prototype.forEach.call($menuItems, function($menuItem, index) {
      $menuItem.addEventListener('click', function(event) {
        if (window.innerWidth < 800) {
          $menuNav.classList.remove('is-active');
        }
      });
    });
  }

  // Property: Copy to clipboard
  var clipboard = new Clipboard('.example-value');

  Array.prototype.forEach.call(document.querySelectorAll('.example-value'), function($el) {
    $el.addEventListener('mouseenter', function(e) {
      e.target.classList.remove('is-copied');
    });
  });

  clipboard.on('success', function(e) {
    e.clearSelection();
    e.trigger.classList.add('is-copied');
  });

  // Property: Share modal
  var $propertyShares = document.querySelectorAll('.property-share');
  var $modalInput = document.getElementById('modal-input');
  var baseURL = '' + window.location.origin + window.location.pathname;
  baseURL = 'http://cssreference.io/';
  var facebookURL = 'https://www.facebook.com/sharer.php?u=http%3A%2F%2Fcssreference.io';
  var twitterURL = 'https://twitter.com/intent/tweet?url=http%3A%2F%2Fcssreference.io&text=CSS%20Reference%3A%20a%20visual%20guide%20to%20the%20most%20popular%20%23CSS%20properties';

  Array.prototype.forEach.call($propertyShares, function($el, index) {
    $el.addEventListener('click', function(e) {
      var propertyName = $el.dataset.propertyName;
      var shareURL = baseURL + 'property/' + propertyName;
      $modalInput.value = shareURL;
      encodedURL = encodeURIComponent(shareURL);
      facebookURL = 'https://www.facebook.com/sharer.php?u=' + encodedURL;
      twitterURL = buildTwitterURL(encodedURL, propertyName);
      openModal();
    });
  });

  var $modalTwitter = document.getElementById('modal-twitter');
  var $modalFacebook = document.getElementById('modal-facebook');

  $modalTwitter.addEventListener('click', function(event) {
    event.preventDefault();
    window.open(twitterURL);
  });

  $modalFacebook.addEventListener('click', function(event) {
    event.preventDefault();
    window.open(facebookURL);
  });

  // Modal
  var $modalShare = document.getElementById('modal-share');
  var $modalClose = document.getElementById('modal-close');

  $modalShare.addEventListener('click', function(event) {
    event.preventDefault();
    if (event.target === $modalShare) {
      closeModal();
    } else {
      return true;
    }
  });

  $modalClose.addEventListener('click', function(event) {
    event.preventDefault();
    closeModal();
  });

  function openModal() {
    isModaling = true;
    $modalShare.classList.add('is-active');
  }

  function closeModal() {
    isModaling = false;
    $modalShare.classList.remove('is-active');
    facebookURL = 'https://www.facebook.com/sharer.php?u=http%3A%2F%2Fcssreference.io';
    twitterURL = 'https://twitter.com/intent/tweet?url=http%3A%2F%2Fcssreference.io&text=CSS%20Reference%3A%20a%20visual%20guide%20to%20the%20most%20popular%20%23CSS%20properties';
  }

  var modalClipboard = new Clipboard('#modal-copy');

  modalClipboard.on('success', function(e) {
    e.clearSelection();
    e.trigger.innerHTML = 'Copied';
    setTimeout(function() { e.trigger.innerHTML = 'Copy'; }, 500);
  });

  // Property: Launch animations
  var $launchButtons = document.querySelectorAll('.property-animation-toggle');

  Array.prototype.forEach.call($launchButtons, function($launchButton, index) {
    var propertyName = $launchButton.dataset.propertyName;
    var $targets = document.querySelectorAll('#' + propertyName + ' .example-output-div');

    $launchButton.addEventListener('click', function(event) {
      this.classList.toggle('is-playing');

      Array.prototype.forEach.call($targets, function($elbis, index) {
        $elbis.classList.toggle('is-animated');
      });
    });
  });

  // Property: Enable fixed
  var $fixedButtons = document.querySelectorAll('.example-fixed-toggle');

  Array.prototype.forEach.call($fixedButtons, function($fixedButton, index) {
    var slug = $fixedButton.dataset.slug;
    var $target = document.getElementById(slug);

    $fixedButton.addEventListener('click', function(event) {
      this.classList.toggle('is-enabled');
      $target.classList.toggle('is-fixed');
    });
  });

  // Hashes
  var $hashes = document.querySelectorAll('.hash, .menu-list-ul li a');

  Array.prototype.forEach.call($hashes, function($el) {
    $el.addEventListener('click', function(event) {
      event.preventDefault();
      var propertyName = $el.dataset.propertyName;
      var $target = document.getElementById($el.dataset.propertyName);

      if ($target) {
        $target.scrollIntoView();
      } else {
        window.location = window.location.origin + '/property/' + propertyName;
      }
    });
  });
});

// Pure functions
function initializeMatches($menuItems) {
  var matches = [];

  Array.prototype.forEach.call($menuItems, function($el, index) {
    var propertyName = $el.dataset.propertyName;
    matches.push({
      DOMIndex: index,
      propertyName: propertyName,
    });
  });

  return matches;
}

function cleanMenu($menuItems, highlight, selection) {
  Array.prototype.forEach.call($menuItems, function($el, index) {
    var $elName = $el.querySelector('.item-name');
    if (highlight) {
      $elName.innerHTML = $el.dataset.propertyName;
      $el.classList.remove('is-highlighted');
    }
    if (selection) {
      $el.classList.remove('is-selected');
    }
  });
}

function navigateMenu($menuItems, matches, currentIndex, increment = true) {
  Array.prototype.forEach.call($menuItems, function($el, index) {
    $el.classList.remove('is-selected');
  });

  if (matches.length < 1) {
    return -1;
  }

  var desiredIndex = increment ? currentIndex + 1 : currentIndex - 1;
  var actualIndex = limitNumber(desiredIndex, -1, matches.length - 1);

  if (actualIndex > -1) {
    var DOMIndex = matches[actualIndex].DOMIndex;
    $menuItems[DOMIndex].classList.add('is-selected');
  }

  return actualIndex;
}

function highlightQuery($el, propertyName, query) {
  var queryIndex = propertyName.indexOf(query);
  var $elName = $el.querySelector('.item-name');

  if (queryIndex >= 0) {
    var before = propertyName.substring(0, queryIndex);
    var highlight = '' + propertyName.substring(queryIndex, queryIndex + query.length) + '';
    var after = propertyName.substring(queryIndex + query.length);
    $elName.innerHTML = before + highlight + after;
    $el.classList.add('is-highlighted');
    return true;
  } else {
    $elName.innerHTML = propertyName;
    $el.classList.remove('is-highlighted');
    return false;
  }
}

function limitNumber(value, min, max) {
  return Math.min(Math.max(value, min), max);
}

function buildTwitterURL(encodedURL, propertyName) {
  var text = 'Here\'s how ' + propertyName + ' works in #CSS';
  var encodedText = encodeURIComponent(text);
  return 'https://twitter.com/intent/tweet?url=' + encodedURL + '&text=' + encodedText;
}


text:
Here is very basic show case for jwt bearer token authorization, using angular as front end and ASP.NET Core as backend.
ASP.NET Core3.1 angular7.2.1 with systemjs.
(Make sure you have dotnet core 3.1 + and Angular7.2.1 installed)

***********************************************************

(Why systemjs not webpack? Personal opinion: webpack just too complicated to use for any small size, simple application, I rather scarified efficient to let most programmers can read my example code)

**************************************************************************

Now you can stop google and find out how to do bear JWT token Authentication, it is simple!

At backend: MS$ provide middleware AddAuthentication().AddJwtBearer() for bear JWT token Authentication, so, things turns to be as simple as add the middleware at Startup.cs

At frontend(angular in this case): save the token in sessionStorage, and when talking to backend, set header of http(https for production) request as:

     let headers = new HttpHeaders()
                        .set('Content-Type','application/json')
                        .set("Authorization", "Bearer " + token);

************************************************************
Angular & material 7.2.1 in ASP.NET Core 3.1 (VS2019 or csproj version)with JWT solution.

Make sure:

ASP.NET CORE 3.1 has been installed, if not, get from here:
  https://www.microsoft.com/net/download/core

nodejs has been installed, if not, get from https://nodejs.org/en/download/

after download this repositiry, go to folder with file ASPNETCoreAngularJWT.csproj and run command:

    >dotnet restore

    >npm install

    >npm start

Finally start dotnet and browser http://localhost:5000 by

    >dotnet run

And do not forget to run "npm start" after modify any typescript files.

You can run this for angular compile and dotnet run

    >npm run runall

Also it can be opened by both Visual Studio 2017 or Visual Studio Code.
After open by VS2017 and before run as debug, make sure project-> property -> Debug and App URL ="http://localhost:5000" and rebuild again before start to debug


text:
local packages = function(use)
  use 'wbthomason/packer.nvim'

  -- new solarized truecolor pallete
  -- use {'overcache/NeoSolarized'} --, opt = false,  cmd = 'colorscheme NeoSolarized' } --, config = 'vim.cmd[[colorscheme NeoSolarized]]' }
  use {'ishan9299/nvim-solarized-lua'}

  -- use lualine
  use { 'nvim-lualine/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons', opt = true } }
  -- use vim fugitive idk why tho maybe i'll like it
  use {'tpope/vim-fugitive'}

  -- show indents with virtual lines
  use { 'lukas-reineke/indent-blankline.nvim', opt = false }

  -- nvim colored web icons
  use { 'kyazdani42/nvim-web-devicons' }

  -- LSP progress eye candy in bottom right
  use {'j-hui/fidget.nvim', opt = false}

  -- vscode style code actions
  -- use 'kosayoda/nvim-lightbulb'

  -- required by telescope
  use {'nvim-lua/plenary.nvim'}
  use {'nvim-telescope/telescope-fzf-native.nvim', run = 'make'}
  -- suggested to telescope & aerial && neat / improved syntax highlighting and more?
  local treesitter_run = function()
    local ts_update = require('nvim-treesitter.install').update({ with_sync = true })
    ts_update()
  end
  use {'nvim-treesitter/nvim-treesitter', run = treesitter_run}
  -- telescope
  use {'nvim-telescope/telescope.nvim'}

  -- comment stuff out easily...
  use {'tpope/vim-commentary'}
  -- handle comments for multi-language-file-types
  use {'JoosepAlviste/nvim-ts-context-commentstring'}

  -- TypeScript Plugins
  -- { 'jose-elias-alvarez/null-ls.nvim' };
  -- { 'jose-elias-alvarez/nvim-lsp-ts-utils' };

  use {'ms-jpq/chadtree', branch = 'chad', run = os.getenv('HOME')..'/bin/nvpython -m chadtree deps'}
  -- coc is like coq but has its own lsp so i don't have to waste time configuring neovim-lsp's
  use {'neoclide/coc.nvim', branch= 'release'}

  -- use {'simrat39/symbols-outline.nvim'} -- did not work with CoC -- blank - https://github.com/simrat39/symbols-outline.nvim/issues/131
  -- use {'liuchengxu/vista.vim'} -- sucks to use -- shows **everything ever defined w/out collapsable sections**
  use {'stevearc/aerial.nvim', config = function() require('aerial').setup() end}

  require('packer').sync()
end

local echohl = vim.schedule_wrap(function(msg, hl)
  local emsg = vim.fn.escape(msg, '"')
  vim.cmd('echohl ' .. hl .. ' | echom "' .. emsg .. '" | echohl None')
end)

local info = function(msg) echohl(msg, 'None') end
local err = function(msg) echohl(msg, 'ErrorMsg') end

local function init(success)
  if not success then
    err('[packer]: Failed setup')
    return
  end

  info('[packer]: Loading package list')
  vim.cmd('packadd packer.nvim')

  require('packer').startup(packages)
end

local function bootstrap()
  -- Bootstrap `packer` installation to manage packages
  local packer = {
    path = vim.fn.stdpath('data') .. '/site/pack/packer/start/packer.nvim',
    url = 'https://github.com/wbthomason/packer.nvim'
  }

  if vim.fn.executable('git') ~= 1 then
    err('[packer] Bootstrap failed, git not installed')
    return
  end

  if vim.fn.empty(vim.fn.glob(packer.path)) > 0 then
    info('[packer]: Installing...')

    local handle
    handle = vim.loop.spawn(
    'git',
    {
      args = {
        'clone',
        packer.url,
        packer.path,
      },
    },
    vim.schedule_wrap(
    function(code, _)
      -- Wrapper to call `init` based on the success of the above `git` operation
      handle:close()
      init(code == 0)
    end
    )
    )
  else
    -- `packer` already installed, continue to load package list
    init(true)
  end
end

return {bootstrap = bootstrap}


text:
package com.datamountaineer.streamreactor.common.converters.sink

import org.apache.kafka.connect.sink.SinkRecord

/**
  * Provides the interface for converting a Connect sink payload (JMS, MQTT, etc) to a SinkRecord
  */
trait Converter {
  def initialize(map: Map[String, String]): Unit = {}

  def convert(sinkTopic: String, data: SinkRecord): SinkRecord
}

object Converter {
  val TopicKey = "topic"
}


text:
#include <common.h>
#include <dm.h>
#include <usb.h>
#include <dm/device-internal.h>

DECLARE_GLOBAL_DATA_PTR;

/* We only support up to 8 */
#define SANDBOX_NUM_PORTS	4

struct sandbox_hub_platdata {
	struct usb_dev_platdata plat;
	int port;	/* Port number (numbered from 0) */
};

enum {
	STRING_MANUFACTURER = 1,
	STRING_PRODUCT,
	STRING_SERIAL,

	STRING_count,
};

static struct usb_string hub_strings[] = {
	{STRING_MANUFACTURER,	"sandbox"},
	{STRING_PRODUCT,	"hub"},
	{STRING_SERIAL,		"2345"},
	{},
};

static struct usb_device_descriptor hub_device_desc = {
	.bLength =		sizeof(hub_device_desc),
	.bDescriptorType =	USB_DT_DEVICE,

	.bcdUSB =		__constant_cpu_to_le16(0x0200),

	.bDeviceClass =		USB_CLASS_HUB,
	.bDeviceSubClass =	0,
	.bDeviceProtocol =	0,

	.idVendor =		__constant_cpu_to_le16(0x1234),
	.idProduct =		__constant_cpu_to_le16(0x5678),
	.iManufacturer =	STRING_MANUFACTURER,
	.iProduct =		STRING_PRODUCT,
	.iSerialNumber =	STRING_SERIAL,
	.bNumConfigurations =	1,
};

static struct usb_config_descriptor hub_config1 = {
	.bLength		= sizeof(hub_config1),
	.bDescriptorType	= USB_DT_CONFIG,

	/* wTotalLength is set up by usb-emul-uclass */
	.bNumInterfaces		= 1,
	.bConfigurationValue	= 0,
	.iConfiguration		= 0,
	.bmAttributes		= 1 << 7,
	.bMaxPower		= 50,
};

static struct usb_interface_descriptor hub_interface0 = {
	.bLength		= sizeof(hub_interface0),
	.bDescriptorType	= USB_DT_INTERFACE,

	.bInterfaceNumber	= 0,
	.bAlternateSetting	= 0,
	.bNumEndpoints		= 1,
	.bInterfaceClass	= USB_CLASS_HUB,
	.bInterfaceSubClass	= 0,
	.bInterfaceProtocol	= US_PR_CB,
	.iInterface		= 0,
};

static struct usb_endpoint_descriptor hub_endpoint0_in = {
	.bLength		= USB_DT_ENDPOINT_SIZE,
	.bDescriptorType	= USB_DT_ENDPOINT,

	.bEndpointAddress	= 1 | USB_DIR_IN,
	.bmAttributes		= USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize		= __constant_cpu_to_le16(1024),
	.bInterval		= 0,
};

static struct usb_hub_descriptor hub_desc = {
	.bLength		= sizeof(hub_desc),
	.bDescriptorType	= USB_DT_HUB,
	.bNbrPorts		= SANDBOX_NUM_PORTS,
	.wHubCharacteristics	= __constant_cpu_to_le16(1 << 0 | 1 << 3 |
								1 << 7),
	.bPwrOn2PwrGood		= 2,
	.bHubContrCurrent	= 5,
	{
		{
			/* all ports removeable */
			.DeviceRemovable	= {0, 0xff}
		}
	}
#if SANDBOX_NUM_PORTS > 8
#error "This code sets up an incorrect mask"
#endif
};

static void *hub_desc_list[] = {
	&hub_device_desc,
	&hub_config1,
	&hub_interface0,
	&hub_endpoint0_in,
	&hub_desc,
	NULL,
};

struct sandbox_hub_priv {
	int status[SANDBOX_NUM_PORTS];
	int change[SANDBOX_NUM_PORTS];
};

static struct udevice *hub_find_device(struct udevice *hub, int port,
				       enum usb_device_speed *speed)
{
	struct udevice *dev;
	struct usb_generic_descriptor **gen_desc;
	struct usb_device_descriptor **dev_desc;

	for (device_find_first_child(hub, &dev);
	     dev;
	     device_find_next_child(&dev)) {
		struct sandbox_hub_platdata *plat;

		plat = dev_get_parent_platdata(dev);
		if (plat->port == port) {
			gen_desc = plat->plat.desc_list;
			gen_desc = usb_emul_find_descriptor(gen_desc,
							    USB_DT_DEVICE, 0);
			dev_desc = (struct usb_device_descriptor **)gen_desc;

			switch (le16_to_cpu((*dev_desc)->bcdUSB)) {
			case 0x0100:
				*speed = USB_SPEED_LOW;
				break;
			case 0x0101:
				*speed = USB_SPEED_FULL;
				break;
			case 0x0200:
			default:
				*speed = USB_SPEED_HIGH;
				break;
			}

			return dev;
		}
	}

	return NULL;
}

static int clrset_post_state(struct udevice *hub, int port, int clear, int set)
{
	struct sandbox_hub_priv *priv = dev_get_priv(hub);
	int *status = &priv->status[port];
	int *change = &priv->change[port];
	int ret = 0;

	if ((clear | set) & USB_PORT_STAT_POWER) {
		enum usb_device_speed speed;
		struct udevice *dev = hub_find_device(hub, port, &speed);

		if (dev) {
			if (set & USB_PORT_STAT_POWER) {
				ret = device_probe(dev);
				debug("%s: %s: power on, probed, ret=%d\n",
				      __func__, dev->name, ret);
				if (!ret) {
					set |= USB_PORT_STAT_CONNECTION |
						USB_PORT_STAT_ENABLE;
					if (speed == USB_SPEED_LOW)
						set |= USB_PORT_STAT_LOW_SPEED;
					else if (speed == USB_SPEED_HIGH)
						set |= USB_PORT_STAT_HIGH_SPEED;
				}

			} else if (clear & USB_PORT_STAT_POWER) {
				debug("%s: %s: power off, removed, ret=%d\n",
				      __func__, dev->name, ret);
				ret = device_remove(dev, DM_REMOVE_NORMAL);
				clear |= USB_PORT_STAT_CONNECTION;
			}
		}
	}
	*change |= *status & clear;
	*change |= ~*status & set;
	*change &= 0x1f;
	*status = (*status & ~clear) | set;

	return ret;
}

static int sandbox_hub_submit_control_msg(struct udevice *bus,
					  struct usb_device *udev,
					  unsigned long pipe,
					  void *buffer, int length,
					  struct devrequest *setup)
{
	struct sandbox_hub_priv *priv = dev_get_priv(bus);
	int ret = 0;

	if (pipe == usb_rcvctrlpipe(udev, 0)) {
		switch (setup->requesttype) {
		case USB_RT_HUB | USB_DIR_IN:
			switch (setup->request) {
			case USB_REQ_GET_STATUS: {
				struct usb_hub_status *hubsts = buffer;

				hubsts->wHubStatus = 0;
				hubsts->wHubChange = 0;
				udev->status = 0;
				udev->act_len = sizeof(*hubsts);
				return 0;
			}
			default:
				debug("%s: rx ctl requesttype=%x, request=%x\n",
				      __func__, setup->requesttype,
				      setup->request);
				break;
			}
		case USB_RT_PORT | USB_DIR_IN:
			switch (setup->request) {
			case USB_REQ_GET_STATUS: {
				struct usb_port_status *portsts = buffer;
				int port;

				port = (setup->index & USB_HUB_PORT_MASK) - 1;
				portsts->wPortStatus = priv->status[port];
				portsts->wPortChange = priv->change[port];
				udev->status = 0;
				udev->act_len = sizeof(*portsts);
				return 0;
			}
			}
		default:
			debug("%s: rx ctl requesttype=%x, request=%x\n",
			      __func__, setup->requesttype, setup->request);
			break;
		}
	} else if (pipe == usb_sndctrlpipe(udev, 0)) {
		switch (setup->requesttype) {
		case USB_RT_PORT:
			switch (setup->request) {
			case USB_REQ_SET_FEATURE: {
				int port;

				port = (setup->index & USB_HUB_PORT_MASK) - 1;
				debug("set feature port=%x, feature=%x\n",
				      port, setup->value);
				if (setup->value < USB_PORT_FEAT_C_CONNECTION) {
					ret = clrset_post_state(bus, port, 0,
							1 << setup->value);
				} else {
					debug("  ** Invalid feature\n");
				}
				return ret;
			}
			case USB_REQ_CLEAR_FEATURE: {
				int port;

				port = (setup->index & USB_HUB_PORT_MASK) - 1;
				debug("clear feature port=%x, feature=%x\n",
				      port, setup->value);
				if (setup->value < USB_PORT_FEAT_C_CONNECTION) {
					ret = clrset_post_state(bus, port,
							1 << setup->value, 0);
				} else {
					priv->change[port] &= 1 <<
						(setup->value - 16);
				}
				udev->status = 0;
				return 0;
			}
			default:
				debug("%s: tx ctl requesttype=%x, request=%x\n",
				      __func__, setup->requesttype,
				      setup->request);
				break;
			}
		default:
			debug("%s: tx ctl requesttype=%x, request=%x\n",
			      __func__, setup->requesttype, setup->request);
			break;
		}
	}
	debug("pipe=%lx\n", pipe);

	return -EIO;
}

static int sandbox_hub_bind(struct udevice *dev)
{
	return usb_emul_setup_device(dev, hub_strings, hub_desc_list);
}

static int sandbox_child_post_bind(struct udevice *dev)
{
	struct sandbox_hub_platdata *plat = dev_get_parent_platdata(dev);
	struct usb_emul_platdata *emul = dev_get_uclass_platdata(dev);

	plat->port = dev_read_u32_default(dev, "reg", -1);
	emul->port1 = plat->port + 1;

	return 0;
}

static const struct dm_usb_ops sandbox_usb_hub_ops = {
	.control	= sandbox_hub_submit_control_msg,
};

static const struct udevice_id sandbox_usb_hub_ids[] = {
	{ .compatible = "sandbox,usb-hub" },
	{ }
};

U_BOOT_DRIVER(usb_sandbox_hub) = {
	.name	= "usb_sandbox_hub",
	.id	= UCLASS_USB_EMUL,
	.of_match = sandbox_usb_hub_ids,
	.bind	= sandbox_hub_bind,
	.ops	= &sandbox_usb_hub_ops,
	.priv_auto_alloc_size = sizeof(struct sandbox_hub_priv),
	.per_child_platdata_auto_alloc_size =
			sizeof(struct sandbox_hub_platdata),
	.child_post_bind = sandbox_child_post_bind,
};


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

<title>MatcherExportFilterMapping (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.jasperreports.engine.export

Class MatcherExportFilterMapping

java.lang.Object

net.sf.jasperreports.engine.export.MatcherExportFilterMapping

public class MatcherExportFilterMapping
extends java.lang.Object

Version:

$Id: JacksonMapping.java 5880 2013-01-07 20:40:06Z teodord $

Author:

Teodor Danciu (teodord@users.sourceforge.net)

Constructor Summary

Constructors

Constructor and Description

MatcherExportFilterMapping(java.lang.String exporterKey,
                          java.lang.String value,
                          boolean isIncludes)

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getExporterKey()

java.lang.String
getValue()

boolean
isIncludes()

void
setExporterKey(java.lang.String exporterKey)

void
setIncludes(boolean isIncludes)

void
setValue(java.lang.String value)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MatcherExportFilterMapping

public MatcherExportFilterMapping(java.lang.String exporterKey,
                          java.lang.String value,
                          boolean isIncludes)

Method Detail

getExporterKey

public java.lang.String getExporterKey()

setExporterKey

public void setExporterKey(java.lang.String exporterKey)

getValue

public java.lang.String getValue()

setValue

public void setValue(java.lang.String value)

isIncludes

public boolean isIncludes()

setIncludes

public void setIncludes(boolean isIncludes)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
<?php

namespace lithium\net\socket;

use lithium\core\NetworkException;

/**
 * A PHP stream-based socket adapter.
 *
 * This stream adapter provides the required method implementations of the abstract `Socket` class
 * for the `open()`, `close()`, `read()`, `write()`, `timeout()` `eof()` and `encoding()` methods.
 *
 * @link http://php.net/book.stream.php PHP Manual: Streams
 * @see lithium\net\socket\Stream
 */
class Stream extends \lithium\net\Socket {

	/**
	 * Opens a socket and initializes the internal resource handle.
	 *
	 * @param array $options update the config settings
	 * @return mixed Returns `false` if the socket configuration does not contain the
	 *         `'scheme'` or `'host'` settings, or if configuration fails, otherwise returns a
	 *         resource stream. Throws exception if there is a network error.
	 */
	public function open(array $options = array()) {
		parent::open($options);
		$config = $this->_config;

		if (!$config['scheme'] || !$config['host']) {
			return false;
		}
		$scheme = ($config['scheme'] !== 'udp') ? 'tcp' : 'udp';
		$port = $config['port'] ?: 80;
		$host = "{$scheme}://{$config['host']}:{$port}";
		$flags = STREAM_CLIENT_CONNECT;

		if ($config['persistent']) {
			$flags = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
		}
		$errorCode = $errorMessage = null;
		$this->_resource = stream_socket_client(
			$host, $errorCode, $errorMessage, $config['timeout'], $flags
		);
		if ($errorCode || $errorMessage) {
			throw new NetworkException($errorMessage);
		}
		$this->timeout($config['timeout']);

		if (!empty($config['encoding'])) {
			$this->encoding($config['encoding']);
		}
		return $this->_resource;
	}

	/**
	 * Closes the stream
	 *
	 * @return boolean True on closed connection
	 */
	public function close() {
		if (!is_resource($this->_resource)) {
			return true;
		}
		fclose($this->_resource);

		if (is_resource($this->_resource)) {
			$this->close();
		}
		return true;
	}

	/**
	 * Determines if the socket resource is at EOF.
	 *
	 * @return boolean Returns `true` if resource pointer is at its EOF, `false` otherwise.
	 */
	public function eof() {
		return is_resource($this->_resource) ? feof($this->_resource) : true;
	}

	/**
	 * Reads data from the stream resource
	 *
	 * @param integer $length If specified, will read up to $length bytes from the stream.
	 *        If no value is specified, all remaining bytes in the buffer will be read.
	 * @param integer $offset Seek to the specified byte offset before reading.
	 * @return string Returns string read from stream resource on success, false otherwise.
	 */
	public function read($length = null, $offset = null) {
		if (!is_resource($this->_resource)) {
			return false;
		}
		if (!$length) {
			return stream_get_contents($this->_resource);
		}
		return stream_get_contents($this->_resource, $length, $offset);
	}

	/**
	 * writes data to the stream resource
	 *
	 * @param string $data The string to be written.
	 * @return mixed False on error, number of bytes written otherwise.
	 */
	public function write($data = null) {
		if (!is_resource($this->_resource)) {
			return false;
		}
		if (!is_object($data)) {
			$data = $this->_instance($this->_classes['request'], (array) $data + $this->_config);
		}
		return fwrite($this->_resource, (string) $data, strlen((string) $data));
	}

	/**
	 * Set timeout period on a stream.
	 *
	 * @link http://php.net/function.stream-set-timeout.php
	 *       PHP Manual: stream_set_timeout()
	 * @param integer $time The timeout value in seconds.
	 * @return boolean
	 */
	public function timeout($time) {
		if (!is_resource($this->_resource)) {
			return false;
		}
		return stream_set_timeout($this->_resource, $time);
	}

	/**
	 * Sets the character set for stream encoding if possible. The `stream_encoding`
	 * function is not guaranteed to be available as it is seems as if it's experimental
	 * or just not officially documented. If the function is not available returns `false`.
	 *
	 * @link http://php.net/function.stream-encoding.php stream_encoding()
	 * @param string $charset
	 * @return boolean Returns `false` if `stream_encoding()` function does not exist, boolean
	 *         result of `stream_encoding()` otherwise.
	 */
	public function encoding($charset) {
		if (!function_exists('stream_encoding')) {
			return false;
		}
		return is_resource($this->_resource) ? stream_encoding($this->_resource, $charset) : false;
	}
}

?>


text:
'''
  Database backends
'''
from db_backend import DbBackend
import config

#数据库配置
DATABASE_SETTINGS = {
  #"engine": "backends.mongodb", # name of monogdb moduel
  "host": config.MONGODB_HOST,             # Set host address
  "port": config.MONGODB_PORT,                   # Set port
  "db_file":config.MONGODB_NAME,    # Set database file
  "max_pool_size":config.MONGODB_MAX_POOL_SIZE,
}

db_backend = DbBackend(DATABASE_SETTINGS)


text:
package cmd

import (
	"github.com/shirou/gopsutil/mem"
	"github.com/spf13/viper"
)

func memHandler(metric string) (resp []metricHandlerResponse, err error) {
	v, err := mem.VirtualMemory()

	if err != nil {
		return nil, err
	}

	value := 0.0
	unit := storageUnits[viper.GetString("memoryUnit")].Name
	multiplier := storageUnits[viper.GetString("memoryUnit")].Multiplier

	switch metric {
	case "avail":
		value = 100.0 - v.UsedPercent
		unit = "Percent"
	case "free":
		value = float64(v.Available) / multiplier
	case "total":
		value = float64(v.Total) / multiplier
	case "used":
		value = float64(v.Used) / multiplier
	case "util":
		value = v.UsedPercent
		unit = "Percent"
	}

	return []metricHandlerResponse{metricHandlerResponse{Value: value, Unit: unit}}, nil
}

func memAvail() (resp []metricHandlerResponse, err error) {
	return memHandler("avail")
}

func memFree() (resp []metricHandlerResponse, err error) {
	return memHandler("free")
}

func memTotal() (resp []metricHandlerResponse, err error) {
	return memHandler("total")
}

func memUsed() (resp []metricHandlerResponse, err error) {
	return memHandler("used")
}

func memUtil() (resp []metricHandlerResponse, err error) {
	return memHandler("util")
}


text:
package com.sequenceiq.cloudbreak.service.template;

import static com.sequenceiq.cloudbreak.common.type.ResourceStatus.DEFAULT_DELETED;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.inject.Inject;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.sequenceiq.cloudbreak.api.model.TemplateRequest;
import com.sequenceiq.cloudbreak.common.type.ResourceStatus;
import com.sequenceiq.cloudbreak.controller.json.JsonHelper;
import com.sequenceiq.cloudbreak.common.model.user.IdentityUser;
import com.sequenceiq.cloudbreak.domain.Template;
import com.sequenceiq.cloudbreak.repository.TemplateRepository;
import com.sequenceiq.cloudbreak.util.FileReaderUtils;
import com.sequenceiq.cloudbreak.util.JsonUtil;
import com.sequenceiq.cloudbreak.util.NameUtil;

@Service
@Transactional
public class DefaultTemplateLoaderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTemplateLoaderService.class);

    @Value("#{'${cb.template.defaults:}'.split(',')}")
    private List<String> templateArray;

    @Inject
    @Qualifier("conversionService")
    private ConversionService conversionService;

    @Inject
    private TemplateRepository templateRepository;

    @Inject
    private JsonHelper jsonHelper;

    public void createDefaultTemplates(IdentityUser user) {
        Set<Template> defaultTemplates = templateRepository.findAllDefaultInAccount(user.getAccount());

        List<String> defaultNetworkNames = defaultTemplates.stream()
                .map(t -> t.getStatus() == DEFAULT_DELETED ? NameUtil.cutTimestampPostfix(t.getName()) : t.getName())
                .collect(Collectors.toList());
        createDefaultTemplateInstances(user, defaultNetworkNames);
    }

    private void createDefaultTemplateInstances(IdentityUser user, List<String> defaultNetworkNames) {
        for (String templateName : templateArray) {
            if (!templateName.isEmpty() && !defaultNetworkNames.contains(templateName)) {
                try {
                    JsonNode jsonNode = jsonHelper.createJsonFromString(
                            FileReaderUtils.readFileFromClasspath(String.format("defaults/templates/%s.tmpl", templateName)));
                    TemplateRequest templateRequest = JsonUtil.treeToValue(jsonNode, TemplateRequest.class);
                    Template converted = conversionService.convert(templateRequest, Template.class);
                    converted.setAccount(user.getAccount());
                    converted.setOwner(user.getUserId());
                    converted.setPublicInAccount(true);
                    converted.setStatus(ResourceStatus.DEFAULT);
                    templateRepository.save(converted);
                } catch (Exception e) {
                    LOGGER.error("Template is not available for '{}' user.", e, user);
                }
            }
        }
    }

}


text: Here's my resume :dog:


text:
class LwoScan : public ProgramBase {
public:
  LwoScan();

  void run();

protected:
  virtual bool handle_args(Args &args);

  Filename _input_filename;
};

#endif


text:
using System.IO;
using System.Runtime.InteropServices;

namespace Joy.Data
{
    internal static class IOExceptionExtensions
    {
        public static bool IsLockException(this IOException exception)
        {
            int errorCode = Marshal.GetHRForException(exception) & 0xffff;
            if (errorCode != 0x20)
            {
                return (errorCode == 0x21);
            }
            return true;
        }
    }
}


text:
require "mars_rover/version"

module MarsRover
  autoload :Plateau,    'mars_rover/plateau'
  autoload :Rover,      'mars_rover/rover'
  autoload :Navigation, 'mars_rover/navigation'
  autoload :Position,   'mars_rover/position'
  autoload :CLI,        'mars_rover/cli'

  def self.start
    CLI.run
  end
end


text:
import React from 'react';
import createReactClass from 'create-react-class';
import { MenuProps } from './PropsType';

const Menu = createReactClass<MenuProps, any>({
  render() {
    return
TODO for react-native
;
  },
});

export default Menu;


text:
package aws

import (
	"testing"

	"github.com/hashicorp/terraform/terraform"
)

func TestAWSVpcMigrateState(t *testing.T) {
	cases := map[string]struct {
		StateVersion int
		ID           string
		Attributes   map[string]string
		Expected     string
		Meta         interface{}
	}{
		"v0_1": {
			StateVersion: 0,
			ID:           "some_id",
			Attributes: map[string]string{
				"assign_generated_ipv6_cidr_block": "true",
			},
			Expected: "false",
		},
		"v0_1_without_value": {
			StateVersion: 0,
			ID:           "some_id",
			Attributes:   map[string]string{},
			Expected:     "false",
		},
	}

	for tn, tc := range cases {
		is := &terraform.InstanceState{
			ID:         tc.ID,
			Attributes: tc.Attributes,
		}
		is, err := resourceAwsVpcMigrateState(
			tc.StateVersion, is, tc.Meta)

		if err != nil {
			t.Fatalf("bad: %s, err: %#v", tn, err)
		}

		if is.Attributes["assign_generated_ipv6_cidr_block"] != tc.Expected {
			t.Fatalf("bad VPC Migrate: %s\n\n expected: %s", is.Attributes["assign_generated_ipv6_cidr_block"], tc.Expected)
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:paddingLeft="32dp"
    android:paddingRight="32dp">

    <LinearLayout
        android:id="@+id/material_background"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/cube_material_card"
        android:orientation="vertical"
        android:paddingBottom="6dp">

        <LinearLayout
            android:id="@+id/cube_dialog_content_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/cube_dialog_title"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="23dp"
                android:layout_marginRight="24dp"
                android:layout_marginTop="23dp"
                android:text="Material title"
                android:textColor="#DE000000"
                android:textSize="23sp" />

            <LinearLayout
                android:id="@+id/message_content_view"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/cube_dialog_message"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:lineSpacingMultiplier="1.3"
                    android:text="message"
                    android:textColor="#8a000000"
                    android:textSize="16sp" />
            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/cube_dialog_bottom"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:gravity="center_vertical"
            android:orientation="horizontal">

        </LinearLayout>
    </LinearLayout>
</LinearLayout>


text:
cd %~dp0
google\protobuf\cmake\Release\protoc tensorflow/core/example/example.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/example/feature.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/log_memory.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/allocation_description.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/attr_value.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/cost_graph.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/device_attributes.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/function.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/graph.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/kernel_def.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/op_def.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/step_stats.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/summary.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/tensor.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/tensor_description.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/tensor_shape.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/tensor_slice.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/types.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/variable.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/framework/versions.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/kernels/reader_base.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/lib/core/error_codes.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/config.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/master.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/master_service.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/meta_graph.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/named_tensor.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/queue_runner.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/saver.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/tensorflow_server.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/worker.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/protobuf/worker_service.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/util/event.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/util/memmapped_file_system.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/util/saved_tensor_slice.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/core/util/test_log.proto --cpp_out=. -I.
google\protobuf\cmake\Release\protoc tensorflow/tools/proto_text/test.proto --cpp_out=. -I.


text:
@{

# File del modulo di script o del modulo binario associato a questo manifesto.
RootModule = 'Poshstache.psm1'

# Numero di versione del modulo.
ModuleVersion = '0.1.10'

# Edizioni di PS supportate
# CompatiblePSEditions = @()

# ID utilizzato per identificare in modo univoco il modulo
GUID = 'e8382377-7e6b-443e-8d1a-b9f8d877ba7d'

# Autore del modulo
Author = 'Marco Torello'

# Società o fornitore del modulo
CompanyName = 'Sconosciuto'

# Informazioni sul copyright per il modulo
Copyright = '(c) 2021 Marco Torello. Licensed under MIT license.'

# Descrizione delle funzionalità offerte dal modulo
Description = 'A Powershell implementation of Mustache based on Stubble'

# Versione minima del motore di Windows PowerShell necessaria per il modulo
# PowerShellVersion = ''

# Nome dell'host di Windows PowerShell richiesto dal modulo
# PowerShellHostName = ''

# Versione minima dell'host di Windows PowerShell richiesta dal modulo
# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module. Questo prerequisito è valido solo per l'edizione Desktop di PowerShell.
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module. Questo prerequisito è valido solo per l'edizione Desktop di PowerShell.
# CLRVersion = ''

# Architettura del processore (None, X86, Amd64, IA64) richiesta dal modulo
# ProcessorArchitecture = ''

# Moduli che devono essere importati nell'ambiente globale prima di importare il modulo
# RequiredModules = @()

# Assembly che devono essere caricati prima di importare il modulo
# RequiredAssemblies = @()

# File script (ps1) eseguiti nell'ambiente del chiamante prima di importare il modulo.
# ScriptsToProcess = @()

# File di tipi (ps1xml) da caricare al momento dell'importazione del modulo
# TypesToProcess = @()

# File di formato (ps1xml) da caricare al momento dell'importazione del modulo
# FormatsToProcess = @()

# Moduli da importare come moduli annidati del modulo specificato in RootModule/ModuleToProcess
# NestedModules = @()

# Funzioni da esportare dal modulo. Per ottenere prestazioni ottimali, non usare caratteri jolly e non eliminare la voce. Usare una matrice vuota se non sono presenti funzioni da esportare.
FunctionsToExport = 'ConvertTo-PoshstacheTemplate'

# Cmdlet da esportare dal modulo. Per ottenere prestazioni ottimali, non usare caratteri jolly e non eliminare la voce. Usare una matrice vuota se non sono presenti cmdlet da esportare.
CmdletsToExport = ''

# Variabili da esportare dal modulo
VariablesToExport = ''

# Alias da esportare dal modulo. Per ottenere prestazioni ottimali, non usare caratteri jolly e non eliminare la voce. Usare una matrice vuota se non sono presenti alias da esportare.
AliasesToExport = ''

# Risorse DSC da esportare da questo modulo
# DscResourcesToExport = @()

# Elenco di tutti i moduli inclusi nel modulo
# ModuleList = @()

# Elenco di tutti i file inclusi nel modulo
# FileList = @()

# Dati privati da passare al modulo specificato in RootModule/ModuleToProcess. Può inoltre includere una tabella hash PSData con altri metadati del modulo utilizzati da PowerShell.
PrivateData = @{

    PSData = @{

        # Tag applicati al modulo per semplificarne l'individuazione nelle raccolte online.
        Tags = @("Mustache","LogicLessTemplate","HTML","Templating","Template")

        # URL della licenza di questo modulo.
        LicenseUri = 'https://github.com/baldator/Poshstache/blob/master/LICENSE.txt'

        # URL del sito Web principale per questo progetto.
        ProjectUri = 'https://github.com/baldator/Poshstache'

        # URL di un'icona che rappresenta questo modulo.
        # IconUri = ''

        # Note sulla versione di questo modulo
        ReleaseNotes = @"
    v 0.1.10 - add HashTable parameter
    v 0.1.9 - add -ValidJSON parameter
    v 0.1.8 - Fix import
    v 0.1.7 - Fix dependencies and update Stubble
    v 0.1.6 - Support complex input object
    v 0.1.5 - Add support for PowerShell Core
    v 0.1.4 - Rollback to Nustache; will create a new module for Stubble
    v 0.1.3 - Replace Nustache with Stubble
    v 0.1.2 - Bugfix
    v 0.1.1 - Add Pester tests
    v 0.1.0 - First release
"@

    } # Fine della tabella hash PSData

} # Fine della tabella hash PrivateData

# URI HelpInfo del modulo
# HelpInfoURI = ''

# Prefisso predefinito per i comandi esportati da questo modulo. Per sostituire il prefisso predefinito, utilizzare Import-Module -Prefix.
# DefaultCommandPrefix = ''

}


text:
package in.projectmanas.manasliaison.activities;

import android.Manifest;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.backendless.Backendless;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.sheets.v4.SheetsScopes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import in.projectmanas.manasliaison.App;
import in.projectmanas.manasliaison.MyCredential;
import in.projectmanas.manasliaison.R;
import in.projectmanas.manasliaison.backendless_classes.Links;
import in.projectmanas.manasliaison.backendless_classes.Sheet;
import in.projectmanas.manasliaison.constants.ConstantsManas;
import in.projectmanas.manasliaison.listeners.SheetDataFetchedListener;
import in.projectmanas.manasliaison.tasks.ReadSpreadSheet;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class LoginActivity extends AppCompatActivity
        implements EasyPermissions.PermissionCallbacks, SheetDataFetchedListener {
    public static final int REQUEST_AUTHORIZATION = 1001;
    public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
    static final int REQUEST_ACCOUNT_PICKER = 1000;
    static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003;
    private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS_READONLY};
    public static GoogleAccountCredential mCredential;
    public static MyCredential myCredential;
    ProgressDialog mProgress;
    private CoordinatorLayout coordinatorLayout;
    private ProgressBar progressBar;
    private Button login;

    /**
     * Create the main activity.
     *
     * @param savedInstanceState previously saved instance data.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        linkViews();
        myCredential = new MyCredential();
        mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());
        progressBar.setVisibility(View.INVISIBLE);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getResultsFromApi();
            }
        });
        try {
            if (!getSharedPreferences("UserDetails", Context.MODE_PRIVATE).getString("emailID", "emailID").equals("emailID")) {
                mCredential.setSelectedAccountName(getSharedPreferences("UserDetails", Context.MODE_PRIVATE).getString("emailID", "emailID"));
                startActivity(new Intent(LoginActivity.this, HomeActivity.class).putExtra("fromLogin", true));
                finish();
            } else {
                mCredential.setSelectedAccountName(null);
            }
        } catch (Exception e) {
            mCredential.setSelectedAccountName(null);
        }
    }

    private void linkViews() {
        setContentView(R.layout.activity_login);
        progressBar = (ProgressBar) findViewById(R.id.pb_circular_login);
        login = (Button) findViewById(R.id.button_login);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.cl_login);
    }

    private void getResultsFromApi() {
        if (!isGooglePlayServicesAvailable()) {
            acquireGooglePlayServices();
        } else if (mCredential.getSelectedAccountName() == null) {
            chooseAccount();
        } else if (!isDeviceOnline()) {
            Toast.makeText(getApplicationContext(), "No network connection available.", Toast.LENGTH_LONG).show();
        } else {

            checkEmailID();
        }
    }

    private void checkEmailID() {
        //Snackbar.make(coordinatorLayout, "Authenticating.. Please wait.", Snackbar.LENGTH_INDEFINITE).show();
        progressBar.setIndeterminate(true);
        progressBar.setVisibility(View.VISIBLE);
        login.setClickable(false);
        ((App) getApplication()).getSheetMetadata(new AsyncCallback<Sheet>() {
            @Override
            public void handleResponse(Sheet response) {
                final String[] params = new String[]{response.getEmailID()};
                ReadSpreadSheet readSpreadSheet = new ReadSpreadSheet(mCredential, LoginActivity.this);
                readSpreadSheet.delegate = LoginActivity.this;
                readSpreadSheet.execute(params);
            }

            @Override
            public void handleFault(BackendlessFault fault) {
                Snackbar.make(coordinatorLayout, fault.getMessage(), Snackbar.LENGTH_LONG).show();
            }
        });
    }

    @AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
    private void chooseAccount() {
        if (EasyPermissions.hasPermissions(
                this, Manifest.permission.GET_ACCOUNTS)) {
            String accountName = getPreferences(Context.MODE_PRIVATE)
                    .getString(ConstantsManas.PREF_ACCOUNT_NAME, null);
            if (accountName != null) {
                mCredential.setSelectedAccountName(accountName);
                getResultsFromApi();
            } else {
                // Start a dialog from which the user can choose an account
                startActivityForResult(
                        mCredential.newChooseAccountIntent(),
                        REQUEST_ACCOUNT_PICKER);
            }
        } else {
            // Request the GET_ACCOUNTS permission via a user dialog
            EasyPermissions.requestPermissions(
                    this,
                    "This app needs to access your Google account (via Contacts).",
                    REQUEST_PERMISSION_GET_ACCOUNTS,
                    Manifest.permission.GET_ACCOUNTS);
        }
    }

    @Override
    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_GOOGLE_PLAY_SERVICES:
                if (resultCode != RESULT_OK) {
                    /*mOutputText.setText(
                            "This app requires Google Play Services. Please install " +
                                    "Google Play Services on your device and relaunch this app.");*/
                } else {
                    getResultsFromApi();
                }
                break;
            case REQUEST_ACCOUNT_PICKER:
                if (resultCode == RESULT_OK && data != null &&
                        data.getExtras() != null) {
                    String accountName =
                            data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    if (accountName != null) {
                        mCredential.setSelectedAccountName(accountName);
                        getResultsFromApi();
                    }
                }
                break;
            case REQUEST_AUTHORIZATION:
                if (resultCode == RESULT_OK) {
                    getResultsFromApi();
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(
                requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Do nothing.
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Do nothing.
    }

    private boolean isDeviceOnline() {
        ConnectivityManager connMgr =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    private boolean isGooglePlayServicesAvailable() {
        GoogleApiAvailability apiAvailability =
                GoogleApiAvailability.getInstance();
        final int connectionStatusCode =
                apiAvailability.isGooglePlayServicesAvailable(this);
        return connectionStatusCode == ConnectionResult.SUCCESS;
    }

    private void acquireGooglePlayServices() {
        GoogleApiAvailability apiAvailability =
                GoogleApiAvailability.getInstance();
        final int connectionStatusCode =
                apiAvailability.isGooglePlayServicesAvailable(this);
        if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
            showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
        }
    }

    void showGooglePlayServicesAvailabilityErrorDialog(
            final int connectionStatusCode) {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        Dialog dialog = apiAvailability.getErrorDialog(
                LoginActivity.this,
                connectionStatusCode,
                REQUEST_GOOGLE_PLAY_SERVICES);
        dialog.show();
    }

    @Override
    public void onProcessFinish(ArrayList<ArrayList<ArrayList<String>>> outputList) {
        boolean stateFlagFound = false;
        ArrayList<ArrayList<String>> output = outputList.get(0);
        for (int i = 0; i < output.size(); i++) {
            ArrayList<String> row = output.get(i);
            if (row.size() > 0 && row.get(0).equals(mCredential.getSelectedAccountName())) {
                //Snackbar.make(coordinatorLayout, "Welcome " + outputList.get(4).get(i).get(0), Snackbar.LENGTH_LONG).show();
                stateFlagFound = true;
                break;
            }
        }
        progressBar.setVisibility(View.INVISIBLE);
        if (!stateFlagFound) {
            login.setClickable(true);
            getPreferences(Context.MODE_PRIVATE).edit().clear().apply();
            mCredential.setSelectedAccount(null);
            Snackbar.make(coordinatorLayout, "Please use the same email address you used to fill the form.  ", Snackbar.LENGTH_INDEFINITE).setAction("Fill Form", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Links.findFirstAsync(new AsyncCallback<Links>() {
                        @Override
                        public void handleResponse(Links response) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(response.getRegistrationForm())));
                        }

                        @Override
                        public void handleFault(BackendlessFault fault) {
                            Snackbar.make(coordinatorLayout, fault.getMessage(), Snackbar.LENGTH_INDEFINITE);
                        }
                    });
                }
            }).show();
        } else {
            SharedPreferences sharedPreferences = getSharedPreferences("UserDetails", Context.MODE_PRIVATE);
            sharedPreferences.edit().putString("emailID", mCredential.getSelectedAccountName()).apply();
            Backendless.Messaging.registerDevice(ConstantsManas.gcmId);
            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
            intent.putExtra("fromLogin", true);
            startActivity(intent);
            finish();
        }
    }
}