text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <title>Snippets</title>
  <meta property="og:title" content="Snippets" />
  <meta name="twitter:title" content="Snippets" />
  <meta name="author" content="davor badrov"/>
  <link href='https://davorbadrov.github.io/img/favicon.ico' rel='icon' type='image/x-icon'/>
  <meta property="og:image" content="https://davorbadrov.github.io/img/avatar-icon.png" />
  <meta name="twitter:image" content="https://davorbadrov.github.io/img/avatar-icon.png" />
  <meta name="twitter:card" content="summary" />
  <meta property="og:url" content="https://davorbadrov.github.io/snippets/" />
  <meta property="og:type" content="website" />
  <meta property="og:site_name" content="Davor Badrov" />

  <meta name="generator" content="Hugo 0.23" />
  <link rel="canonical" href="https://davorbadrov.github.io/snippets/" />
  <link rel="alternate" href="https://davorbadrov.github.io/index.xml" type="application/rss+xml" title="Davor Badrov">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="https://davorbadrov.github.io/css/main.css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />
  <link rel="stylesheet" href="https://davorbadrov.github.io/css/pygment_highlights.css" />
  <link rel="stylesheet" href="https://davorbadrov.github.io/css/highlight.min.css" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.css" integrity="sha256-sCl5PUOGMLfFYctzDW3MtRib0ctyUvI9Qsmq2wXOeBY=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/default-skin/default-skin.min.css" integrity="sha256-BFeI1V+Vh1Rk37wswuOYn5lsTcaU96hGaI7OUVCLjPc=" crossorigin="anonymous" />

      <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
      <button class="pswp__button pswp__button--share" title="Share"></button>
      <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
      <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

    <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
    </button>
    <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
    </button>

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

      </button>
      Davor Badrov

              Home

              Blog

              Snippets

              About

Snippets

Nested SELECT query | Snippets

                Posted on June 19, 2017

How to use inner select query in SQL.

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

SQL - Find duplicate values | Snippets

                Posted on June 19, 2017

Find multiple entries inside a table for given values.
This example return users which share their email with other users.

SELECT
    name, email, COUNT(*)
FROM
    users
GROUP BY
    name, email
HAVING
    COUNT(*) > 1

              davor badrov

           •
          2017

             •
            Davor Badrov

          Hugo v0.23 powered  •  Theme by Beautiful Jekyll adapted to Beautiful Hugo


text:
"use strict";

var Support     = require(__dirname + "/support");
var helpers     = require(__dirname + "/support/helpers");
var gulp        = require("gulp");
var optionsPath = Support.resolveSupportPath("config", "options.js");

describe(Support.getTestDialectTeaser("--options-path"), function () {
  it("using options file instead of cli switches", function (done) {
    gulp
      .src(Support.resolveSupportPath("tmp"))
      .pipe(helpers.clearDirectory())
      .pipe(helpers.runCli("init --options-path " + optionsPath))
      .pipe(helpers.listFiles())
      .pipe(helpers.ensureContent("db"))
      .pipe(helpers.teardown(done));
  });
});

describe(Support.getTestDialectTeaser(".sequelizerc"), function () {
  it("uses the .sequelizerc file", function (done) {
    gulp
      .src(Support.resolveSupportPath("tmp"))
      .pipe(helpers.clearDirectory())
      .pipe(helpers.copyFile(optionsPath, ".sequelizerc"))
      .pipe(helpers.runCli("init"))
      .pipe(helpers.listFiles())
      .pipe(helpers.ensureContent("db"))
      .pipe(helpers.teardown(done));
  });
});

redpajama_set_name: RedPajamaGithub


text:
import React, {Component} from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import {
  FormsyCheckbox,
  FormsyDate,
  FormsyRadio,
  FormsyRadioGroup,
  FormsySelect,
  FormsyText,
  FormsyTime,
  FormsyToggle,
  FormsyAutoComplete
} from 'formsy-material-ui/lib';
import YoutubeExtract from '../../../utils/youtubeExtract';
const uuidV1 = require('uuid/v1');
import SongItem from './songItem';
import {BtnIconAdd} from '../../../components/iconButtons';

class MyForm extends Component {

  constructor() {
    super();
    this.submitForm = this
      .submitForm
      .bind(this);
    this.onSongChange = this
      .onSongChange
      .bind(this);
    this.onRemoveSong = this
      .onRemoveSong
      .bind(this);
    this.state = {
      title: '',
      songs: [
        {
          id: uuidV1()
        }
      ]
    }
  }

  submitForm(data) {
    alert(JSON.stringify(data, null, 4));
  }
  addSong() {
    this.setState({
      ...this.state,
      songs: this
        .state
        .songs
        .concat({id: uuidV1()})
    })
  }

  onRemoveSong(id) {
    if (this.state.songs.length == 1) {
      return;
    }
    this.setState({
      ...this.state,
      songs: this
        .state
        .songs
        .filter((s) => s.id != id)
    });
  }

  onSongChange(id, e) {
    const extractedYoutubeId = YoutubeExtract(e.currentTarget.value);
    this.props.onLoadPreview(extractedYoutubeId);
    //
    // /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/.
    // exec('https://www.youtube.com/watch?v=MT30X9klyL8')[7]
  }

  render() {
    return (
      <Formsy.Form
        onValid={this.enableButton}
        onInvalid={this.disableButton}
        onValidSubmit={this.submitForm}
        onInvalidSubmit={this.notifyFormError}>

          <FormsyText
            name="title"
            required
            hintText="שם הפלייליסט"
            floatingLabelText="שם הפלייליסט"/>

            {this
              .state
              .songs
              .map((song, idx) => <SongItem
                idx={idx}
                song={song}
                onChange={this
                .onSongChange
                .bind(this, song.id)}
                key={song.id}
                onRemove={this
                .onRemoveSong
                .bind(this, song.id)}/>)}

              <BtnIconAdd onClick={() => this.addSong()}/>

          <RaisedButton type="submit" label="Submit"/>

      </Formsy.Form>
    )
  }
}

export default MyForm;


text:
using namespace std;

PropertyManager::PropertyManager() {
}

PropertyManager::~PropertyManager() {
}

string PropertyManager::GetProperty(string key, string defaultValue) {
	char property[256];
	memset(property, 0, 256);
	property_get(key.c_str(), property, defaultValue.c_str());
	return string(property);
}

void PropertyManager::SetProperty(string key, string value) {
	property_set(key.c_str(), value.c_str());
}


text:
package rules

import (
	"fmt"

	"github.com/GoogleCloudPlatform/magic-modules/.ci/breaking-change-detector/constants"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func documentationReference(version, identifier string) string {
	return fmt.Sprintf(" - [reference](%s)", constants.GetFileUrl(version, identifier))
}

func getValueType(valueType schema.ValueType) string {
	switch valueType {
	case schema.TypeBool:
		return "TypeBool"
	case schema.TypeInt:
		return "TypeInt"
	case schema.TypeFloat:
		return "TypeFloat"
	case schema.TypeString:
		return "TypeString"
	case schema.TypeList:
		return "TypeList"
	case schema.TypeMap:
		return "TypeMap"
	case schema.TypeSet:
		return "TypeSet"
	}
	return "TypeUndefined"
}


text:
<?php
session_start();
	  define('DB_HOST', 'localhost');
		  define('DB_NAME', 'inventory');
		  define('DB_USER','root');
		  define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);

if(! $con )
            {
               die('Could not connect: ' . mysql_error());
            }
      $salesID = $_POST['salesID'];
	  $query = "DELETE FROM sales WHERE salesID = '$salesID'";
	  mysql_select_db('inventory');

	  $retval = mysql_query( $query, $con );
	  if(! $retval)
	  {
	  die('Could not update data: ' . mysql_error());
      }else{
           header("location:deletesales.php");
	  }
  mysql_close($con);

?>


text:
<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>jQuery - Connected Large Lists Plugin</title>

		<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/base/jquery-ui.css" type="text/css" media="all" />
		<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />

		<link rel="stylesheet" href="css/connect-ll.css" type="text/css" media="all" />

	<form action="index.html" method="post" accept-charset="utf-8">

jQuery - Connected Large Lists Plugin

Connected Lists 1

			<select id="myList" name="myList" size="10" multiple="multiple">
			</select>

Connected Lists 2 - Pre selected itens

			<select id="myList2" name="myList2" multiple="multiple" style="display: none; ">
				<option value="0">Item 0</option>
				<option value="1" selected="selected">Item 1</option>
				<option value="2" selected="selected">Item 2</option>
				<option value="3">Item 3</option>
				<option value="4">Item 4</option>
				<option value="5" selected="selected">Item 5</option>
				<option value="6">Item 6</option>
				<option value="7">Item 7</option>
			</select>

	</form>


text:
package project.type1.mapper.api;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import project.type1.dto.ContactDto;

@Repository
public interface IContactMapper {

	ContactDto get(long id);

	int update(@Param("id")long id, @Param("tel")String tel);

}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Iraq on All American Muslim</title>
    <link>https://www.allamericanmuslim.com/tags/iraq/</link>
    <description>Recent content in Iraq on All American Muslim</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 25 Aug 2014 00:00:00 +0000</lastBuildDate>

	<atom:link href="https://www.allamericanmuslim.com/tags/iraq/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Heartwarming Moment when Iraqi Policeman Meets his Mom in Village Liberated from ISIS</title>
      <link>https://www.allamericanmuslim.com/iraqi-policeman-meets-mom-after-2-yrs/</link>
      <pubDate>Mon, 25 Aug 2014 00:00:00 +0000</pubDate>

      <guid>https://www.allamericanmuslim.com/iraqi-policeman-meets-mom-after-2-yrs/</guid>
      <description>An Iraqi police officer had to leave his mom behind when ISIS captured their village in 2014. They had no news about each other for two years. It was extremely hard for his mom because she she didn&rsquo;t know what happened to him: was he captured by ISIS? Did he make it out of the village?
Photo: imgur user H3LLR4153R
   (adsbygoogle = window.adsbygoogle || []).push({});  Now, 2 years later, her son came back as a member of the Iraqi force fighting to liberate the Al-Qayyarh village from ISIS.</description>
    </item>

  </channel>
</rss>


text:
extern crate pancurses;

use pancurses::{initscr, endwin};

fn main() {
    let window = initscr();
    window.printw("Hello Rust");
    window.refresh();
    window.getch();
    endwin();
}


text:
package com.intellij.ide.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.ScreenUtil;

import javax.swing.*;
import java.awt.*;

public class MaximizeActiveDialogAction extends WindowAction {
  private static final String NORMAL_BOUNDS = "NORMAL_BOUNDS";

  @Override
  public void actionPerformed(AnActionEvent e) {
    if (myWindow instanceof JDialog) {
      doMaximize((JDialog)myWindow);
    }
  }

  public static void doMaximize(JDialog dialog) {
    if (canBeMaximized(dialog)) {
      maximize(dialog);
    } else if (canBeNormalized(dialog)) {
      normalize(dialog);
    }
  }

  public static boolean canBeMaximized(JDialog dialog) {
    JRootPane rootPane = dialog != null && dialog.isResizable() ? dialog.getRootPane() : null;
    if (rootPane == null) return false;
    return !ScreenUtil.getScreenRectangle(dialog).equals(dialog.getBounds());
  }

  public static void maximize(JDialog dialog) {
    if (!canBeMaximized(dialog)) return;
    dialog.getRootPane().putClientProperty(NORMAL_BOUNDS, dialog.getBounds());
    dialog.setBounds(ScreenUtil.getScreenRectangle(dialog));
  }

  public static boolean canBeNormalized(JDialog dialog) {
    JRootPane rootPane = dialog != null && dialog.isResizable() ? dialog.getRootPane() : null;
    if (rootPane == null) return false;
    Rectangle screenRectangle = ScreenUtil.getScreenRectangle(dialog);
    return dialog.getBounds().equals(screenRectangle) && rootPane.getClientProperty(NORMAL_BOUNDS) instanceof Rectangle;
  }

  public static void normalize(JDialog dialog) {
    if (!canBeNormalized(dialog)) return;
    JRootPane rootPane = dialog.getRootPane();
    Object value = rootPane.getClientProperty(NORMAL_BOUNDS);
    if (value instanceof Rectangle) {
      Rectangle bounds = (Rectangle)value;
      ScreenUtil.fitToScreen(bounds);
      dialog.setBounds(bounds);
      rootPane.putClientProperty(NORMAL_BOUNDS, null);
    }
  }
}


text:
package hudson.model;

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

import hudson.console.HyperlinkNote;
import hudson.diagnosis.OldDataMonitor;
import hudson.util.XStream2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import com.thoughtworks.xstream.converters.UnmarshallingContext;

/**
 * Cause object base class.  This class hierarchy is used to keep track of why
 * a given build was started. This object encapsulates the UI rendering of the cause,
 * as well as providing more useful information in respective subypes.
 *
 * The Cause object is connected to a build via the {@link CauseAction} object.
 *
 *
Views

 *

 *
description.jelly
 *
Renders the cause to HTML. By default, it puts the short description.
 *

 *
 * @author Michael Donohue
 * @see Run#getCauses()
 * @see Queue.Item#getCauses()
 */
@ExportedBean
public abstract class Cause {
    /**
     * One-line human-readable text of the cause.
     *
     *

     * By default, this method is used to render HTML as well.
     */
    @Exported(visibility=3)
    public abstract String getShortDescription();

    /**
     * Called when the cause is registered to {@link AbstractBuild}.
     *
     * @param build
     *      never null
     * @since 1.376
     */
    public void onAddedTo(AbstractBuild build) {}

    /**
     * Report a line to the listener about this cause.
     * @since 1.362
     */
    public void print(TaskListener listener) {
        listener.getLogger().println(getShortDescription());
    }

    /**
     * Fall back implementation when no other type is available.
     * @deprecated since 2009-02-08
     */
    public static class LegacyCodeCause extends Cause {
        private StackTraceElement [] stackTrace;
        public LegacyCodeCause() {
            stackTrace = new Exception().getStackTrace();
        }

        @Override
        public String getShortDescription() {
            return Messages.Cause_LegacyCodeCause_ShortDescription();
        }
    }

    /**
     * A build is triggered by the completion of another build (AKA upstream build.)
     */
    public static class UpstreamCause extends Cause {
        private String upstreamProject, upstreamUrl;
        private int upstreamBuild;
        /**
         * @deprecated since 2009-02-28
         */
        @Deprecated
        private transient Cause upstreamCause;
        private List<Cause> upstreamCauses;

        /**
         * @deprecated since 2009-02-28
         */
        // for backward bytecode compatibility
        public UpstreamCause(AbstractBuild<?,?> up) {
            this((Run<?,?>)up);
        }

        public UpstreamCause(Run<?, ?> up) {
            upstreamBuild = up.getNumber();
            upstreamProject = up.getParent().getFullName();
            upstreamUrl = up.getParent().getUrl();
            upstreamCauses = new ArrayList<Cause>(up.getCauses());
        }

        /**
         * Returns true if this cause points to a build in the specified job.
         */
        public boolean pointsTo(Job<?,?> j) {
            return j.getFullName().equals(upstreamProject);
        }

        /**
         * Returns true if this cause points to the specified build.
         */
        public boolean pointsTo(Run<?,?> r) {
            return r.getNumber()==upstreamBuild && pointsTo(r.getParent());
        }

        @Exported(visibility=3)
        public String getUpstreamProject() {
            return upstreamProject;
        }

        @Exported(visibility=3)
        public int getUpstreamBuild() {
            return upstreamBuild;
        }

        @Exported(visibility=3)
        public String getUpstreamUrl() {
            return upstreamUrl;
        }

        @Override
        public String getShortDescription() {
            return Messages.Cause_UpstreamCause_ShortDescription(upstreamProject, upstreamBuild);
        }

        @Override
        public void print(TaskListener listener) {
            listener.getLogger().println(
                Messages.Cause_UpstreamCause_ShortDescription(
                    HyperlinkNote.encodeTo('/'+upstreamUrl, upstreamProject),
                    HyperlinkNote.encodeTo('/'+upstreamUrl+upstreamBuild, Integer.toString(upstreamBuild)))
            );
        }

        public static class ConverterImpl extends XStream2.PassthruConverter<UpstreamCause> {
            public ConverterImpl(XStream2 xstream) { super(xstream); }
            @Override protected void callback(UpstreamCause uc, UnmarshallingContext context) {
                if (uc.upstreamCause != null) {
                    if (uc.upstreamCauses == null) uc.upstreamCauses = new ArrayList<Cause>();
                    uc.upstreamCauses.add(uc.upstreamCause);
                    uc.upstreamCause = null;
                    OldDataMonitor.report(context, "1.288");
                }
            }
        }
    }

    /**
     * A build is started by an user action.
     */
    public static class UserCause extends Cause {
        private String authenticationName;
        public UserCause() {
            this.authenticationName = Hudson.getAuthentication().getName();
        }

        @Exported(visibility=3)
        public String getUserName() {
        	User u = User.get(authenticationName, false);
            return u != null ? u.getDisplayName() : authenticationName;
        }

        @Override
        public String getShortDescription() {
            return Messages.Cause_UserCause_ShortDescription(authenticationName);
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof UserCause && Arrays.equals(new Object[] {authenticationName},
                    new Object[] {((UserCause)o).authenticationName});
        }

        @Override
        public int hashCode() {
            return 295 + (this.authenticationName != null ? this.authenticationName.hashCode() : 0);
        }
    }

    public static class RemoteCause extends Cause {
        private String addr;
        private String note;

        public RemoteCause(String host, String note) {
            this.addr = host;
            this.note = note;
        }

        @Override
        public String getShortDescription() {
            if(note != null) {
                return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note);
            } else {
                return Messages.Cause_RemoteCause_ShortDescription(addr);
            }
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof RemoteCause && Arrays.equals(new Object[] {addr, note},
                    new Object[] {((RemoteCause)o).addr, ((RemoteCause)o).note});
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 83 * hash + (this.addr != null ? this.addr.hashCode() : 0);
            hash = 83 * hash + (this.note != null ? this.note.hashCode() : 0);
            return hash;
        }
    }
}


text:
% UNDER CONSTRUCTION
%
% This method looks up space values at specified grid locations...
function result=lookup(object,varargin)

end


text:
class DummySortedLookupTableOddLength : public UniformlySpacedOutputSortedLookupTable<uint16_t, uint16_t, float, float>
{
public:
	DummySortedLookupTableOddLength() {
		OUTPUT_MIN = 0;
		OUTPUT_TABLE_DELTA = 0.5;
		OUTPUT_TABLE_DELTA_INTERP_PREC = 0.5;
	};
	float getTemperature(uint16_t reading);
    // LUT for thermistor
private:
	static uint16_t const INPUT_SIZE = 5;
	static uint16_t const INPUTS[INPUT_SIZE]; // non-integral init later
protected:
	virtual uint16_t getArrSize() { return INPUT_SIZE; };
	virtual uint16_t const* getArr() { return INPUTS; };
};
uint16_t const DummySortedLookupTableOddLength::INPUTS[INPUT_SIZE] = { 1, 3, 5, 7, 9 };
float DummySortedLookupTableOddLength::getTemperature(uint16_t const reading) {
  auto const lowHighIndex = binarySearchBounds(reading);
  //auto const lowHighIndex = linearSearchBounds(reading);
  uint16_t const lowValue = INPUTS[lowHighIndex.first];
  // check for special cases
  if (lowHighIndex.first == lowHighIndex.second) {
	  return computeOutputValue(lowHighIndex.first, 0);
  }
  else {
	  uint16_t const highValue = INPUTS[lowHighIndex.second];
	  return computeOutputValue(lowHighIndex.first, computeInterpFactor(lowValue, highValue, reading));
  }

}
// ************
// END DUMMY ODD CLASS
// ***********

// ************
// INIT DUMMY EVEN CLASS
// ***********
class DummySortedLookupTableEvenLength : public UniformlySpacedOutputSortedLookupTable<uint16_t, uint16_t, float, float>
{
public:
	DummySortedLookupTableEvenLength() {
		OUTPUT_MIN = 0;
		OUTPUT_TABLE_DELTA = 0.5;
		OUTPUT_TABLE_DELTA_INTERP_PREC = 0.5;
	};
	float getTemperature(uint16_t reading);
	// LUT for thermistor
private:
	static uint16_t const INPUT_SIZE = 6;
	static uint16_t const INPUTS[INPUT_SIZE]; // non-integral init later
protected:
	virtual uint16_t getArrSize() { return INPUT_SIZE; };
	virtual uint16_t const* getArr() { return INPUTS; };
};
uint16_t const DummySortedLookupTableEvenLength::INPUTS[INPUT_SIZE] = { 1, 3, 5, 7, 9, 11 };
float DummySortedLookupTableEvenLength::getTemperature(uint16_t const reading) {
	auto const lowHighIndex = binarySearchBounds(reading);
	//auto const lowHighIndex = linearSearchBounds(reading);
	uint16_t const lowValue = INPUTS[lowHighIndex.first];
	// check for special cases
	if (lowHighIndex.first == lowHighIndex.second) {
		return computeOutputValue(lowHighIndex.first, 0);
	}
	else {
		uint16_t const highValue = INPUTS[lowHighIndex.second];
		return computeOutputValue(lowHighIndex.first, computeInterpFactor(lowValue, highValue, reading));
	}
}
// ************
// END DUMMY EVEN CLASS
// ***********

// ************
// INIT ODD TEST FIXTURE
// ***********
class SortedLookupTableTestOddLength : public ::testing::Test {
protected:
	virtual void SetUp() {
	}
	// virtual void TearDown() {}
	DummySortedLookupTableOddLength lut_;
};

// ************
// INIT EVEN TEST FIXTURE
// ***********
class SortedLookupTableTestEvenLength : public ::testing::Test {
protected:
	virtual void SetUp() {
	}
	// virtual void TearDown() {}
	DummySortedLookupTableEvenLength lut_;
};

// ************
// RUN ODD TESTS
// ***********
TEST_F(SortedLookupTableTestOddLength, outOfBoundsLow)
{
	auto tVal = lut_.getTemperature(0);
	EXPECT_EQ(tVal, 0);
}
TEST_F(SortedLookupTableTestOddLength, onLowerBound)
{
	auto tVal = lut_.getTemperature(1);
	EXPECT_EQ(tVal, 0.0f);
}
TEST_F(SortedLookupTableTestOddLength, justInsideLowerBound)
{
	auto tVal = lut_.getTemperature(2);
	EXPECT_EQ(tVal, 0.25f);
}
TEST_F(SortedLookupTableTestOddLength, oneInsideLowerBound)
{
	auto tVal = lut_.getTemperature(3);
	EXPECT_EQ(tVal, 0.5f);
}
TEST_F(SortedLookupTableTestOddLength, justBelowHalf)
{
	auto tVal = lut_.getTemperature(4);
	EXPECT_EQ(tVal, 0.75f);
}
TEST_F(SortedLookupTableTestOddLength, onHalf)
{
	auto tVal = lut_.getTemperature(5);
	EXPECT_EQ(tVal, 1.0f);
}
TEST_F(SortedLookupTableTestOddLength, justAboveHalf)
{
	auto tVal = lut_.getTemperature(6);
	EXPECT_EQ(tVal, 1.25f);
}
TEST_F(SortedLookupTableTestOddLength, oneInsideUpperBound)
{
	auto tVal = lut_.getTemperature(7);
	EXPECT_EQ(tVal, 1.5f);
}
TEST_F(SortedLookupTableTestOddLength, justInsideUpperBound)
{
	auto tVal = lut_.getTemperature(8);
	EXPECT_EQ(tVal, 1.75f);
}
TEST_F(SortedLookupTableTestOddLength, onUpperBound)
{
	auto tVal = lut_.getTemperature(9);
	EXPECT_EQ(tVal, 2.0f);
}
TEST_F(SortedLookupTableTestOddLength, outOfBoundsHigh)
{
	auto tVal = lut_.getTemperature(65535);
	EXPECT_EQ(tVal, 2.0);
	// our LUT uses an unsigned value type, check for correct behavior on roll-over
	tVal = lut_.getTemperature(-1);
	EXPECT_EQ(tVal, 2.0);
}

// ************
// RUN EVEN TESTS
// ***********
TEST_F(SortedLookupTableTestEvenLength, outOfBoundsLow)
{
	auto tVal = lut_.getTemperature(0);
	EXPECT_EQ(tVal, 0);
}
TEST_F(SortedLookupTableTestEvenLength, onLowerBound)
{
	auto tVal = lut_.getTemperature(1);
	EXPECT_EQ(tVal, 0.0f);
}
TEST_F(SortedLookupTableTestEvenLength, justInsideLowerBound)
{
	auto tVal = lut_.getTemperature(2);
	EXPECT_EQ(tVal, 0.25f);
}
TEST_F(SortedLookupTableTestEvenLength, oneInsideLowerBound)
{
	auto tVal = lut_.getTemperature(3);
	EXPECT_EQ(tVal, 0.5f);
}
TEST_F(SortedLookupTableTestEvenLength, justBelowIntHalf)
{
	auto tVal = lut_.getTemperature(4);
	EXPECT_EQ(tVal, 0.75f);
}
TEST_F(SortedLookupTableTestEvenLength, onIntHalf)
{
	auto tVal = lut_.getTemperature(5);
	EXPECT_EQ(tVal, 1.0f);
}
TEST_F(SortedLookupTableTestEvenLength, justAboveIntHalf)
{
	auto tVal = lut_.getTemperature(6);
	EXPECT_EQ(tVal, 1.25f);
}
TEST_F(SortedLookupTableTestEvenLength, oneInsideUpperBound)
{
	auto tVal = lut_.getTemperature(9);
	EXPECT_EQ(tVal, 2.0f);
}
TEST_F(SortedLookupTableTestEvenLength, justInsideUpperBound)
{
	auto tVal = lut_.getTemperature(10);
	EXPECT_EQ(tVal, 2.25f);
}
TEST_F(SortedLookupTableTestEvenLength, onUpperBound)
{
	auto tVal = lut_.getTemperature(11);
	EXPECT_EQ(tVal, 2.5f);
}
TEST_F(SortedLookupTableTestEvenLength, outOfBoundsHigh)
{
	auto tVal = lut_.getTemperature(65535);
	EXPECT_EQ(tVal, 2.5);
	// our LUT uses an unsigned value type, check for correct behavior on roll-over
	tVal = lut_.getTemperature(-1);
	EXPECT_EQ(tVal, 2.5);
}


text:
@class NSString;

@protocol EmoticonStoreCellDelegate <NSObject>
- (void)OnShowAlertWithIKnow:(NSString *)arg1;
- (void)OnShowAlertWithOK:(NSString *)arg1;
- (void)OnStopLoading;
- (void)OnStopLoadingAndShowError:(NSString *)arg1;
- (void)OnStopLoadingAndShowOK:(NSString *)arg1;
- (void)OnStartLoadingAndShowStringBlocked:(NSString *)arg1;
- (void)OnStartLoadingAndShowString:(NSString *)arg1;
@end


text:
Elwë is a minimal ELF parser, requiring no external dependencies.

## Building

To compile, simply run `make` in the root directory of the project.

## Using

You can launch the test program by executing `./elwe
<path/to/executable>`.


text:
namespace ExampleApp
{
    namespace Search
    {
        namespace SdkModel
        {
            SearchTags CreateSearchTagsFromFile(
                    Eegeo::Helpers::IFileIO& fileIO, const std::string& fileName)
            {
                const std::string& jsonText = Helpers::FileHelpers::GetFileContentsAsString(fileIO, fileName);
                rapidjson::Document document;

                if (document.Parse<0>(jsonText.c_str()).HasParseError())
                {
                    Eegeo_ASSERT(false, "Failed to parse tag to icon key mapping");
                    return SearchTags();
                }

                Eegeo_ASSERT(document.IsObject(), "Document root should be an object");

                const char* defaultReadableTagKeyName = "default_readable_tag";
                Eegeo_ASSERT(document.HasMember(defaultReadableTagKeyName), "no member named %s", defaultReadableTagKeyName);
                Eegeo_ASSERT(document[defaultReadableTagKeyName].IsString(), "value of %s was not a string", defaultReadableTagKeyName);
                const std::string defaultReadableTag = document[defaultReadableTagKeyName].GetString();

                const char* defaultIconJsonKeyName = "default_icon_key";
                Eegeo_ASSERT(document.HasMember(defaultIconJsonKeyName ), "no member named %s", defaultIconJsonKeyName );
                Eegeo_ASSERT(document[defaultIconJsonKeyName ].IsString(), "value of %s was not a string", defaultIconJsonKeyName );
                const TagIconKey defaultIconKey = document[defaultIconJsonKeyName].GetString();

                const char* tagsKeyName = "tags";
                Eegeo_ASSERT(document.HasMember(tagsKeyName), "no member named %s", tagsKeyName);

                const auto& tagsArray = document[tagsKeyName];
                Eegeo_ASSERT(tagsArray.IsArray(), "value of %s was not an array", tagsKeyName);
                SearchTags searchTags = {};
                searchTags.defaultReadableTag = defaultReadableTag;
                searchTags.defaultIconKey = defaultIconKey;

                for (rapidjson::Value::ConstValueIterator itr = tagsArray.Begin(); itr != tagsArray.End(); ++itr)
                {
                    const auto& tagElem = *itr;

                    Eegeo_ASSERT(tagElem.IsObject(), "value of was not an object");

                    const char* tagKeyName = "tag";
                    Eegeo_ASSERT(tagElem.HasMember(tagKeyName), "no member named %s", tagKeyName);
                    Eegeo_ASSERT(tagElem[tagKeyName].IsString(), "value of %s was not a string", tagKeyName);
                    const std::string tag = tagElem[tagKeyName].GetString();

                    const char* readableTagKeyName = "readable_tag";
                    Eegeo_ASSERT(tagElem.HasMember(readableTagKeyName), "no member named %s", readableTagKeyName);
                    Eegeo_ASSERT(tagElem[readableTagKeyName].IsString(), "value of %s was not a string", readableTagKeyName);
                    const std::string readableTag = tagElem[readableTagKeyName].GetString();

                    const char* iconKeyJsonKeyName= "icon_key";
                    Eegeo_ASSERT(tagElem.HasMember(iconKeyJsonKeyName), "no member named %s", iconKeyJsonKeyName);
                    Eegeo_ASSERT(tagElem[iconKeyJsonKeyName].IsString(), "value of %s was not a string", iconKeyJsonKeyName);
                    const TagIconKey iconKey = tagElem[iconKeyJsonKeyName].GetString();

                    searchTags.tags.emplace_back(SearchTag(tag, readableTag, iconKey));
                }

                return searchTags;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<declare-styleable name="UrlImageView">
		<attr name="defaultImage" format="reference|color" />
		<attr name="maxPixels" format="integer" />
	</declare-styleable>
</resources>


text:
set -e
set -x

ES_HOME="/opt/elasticsearch"

mvn clean install -q $@
mkdir -p $ES_HOME/plugins/river-git
rm -rf $ES_HOME/plugins/river-git
unzip target/releases/elasticsearch-river-git-*.zip -d $ES_HOME/plugins/river-git

rm -rf $ES_HOME/data
rm -rf ~/.elasticsearch-river-git
/opt/elasticsearch/bin/elasticsearch -f -Xmx2g -Xms2g -Des.index.storage.type=memory


text:
Wiki
===============================

[Extension](https://github.com/strumasoft/octopus/wiki/Extension)

[Graphical widget](https://github.com/strumasoft/octopus/wiki/Graphical-widget)

[Object relational mapping](https://github.com/strumasoft/octopus/wiki/Object-relational-mapping)

[Security](https://github.com/strumasoft/octopus/wiki/Security)

[Editor](https://github.com/strumasoft/octopus/wiki/Editor)

[Revision control](https://github.com/strumasoft/octopus/wiki/Revision-control)

[Database administration](https://github.com/strumasoft/octopus/wiki/Database-administration)

Introduction
============

Octopus is web framework based on [nginx](https://www.nginx.com/), [luajit](https://luajit.org/) and [lua-nginx-module](https://github.com/openresty/lua-nginx-module). It contains an automated process for creating all the required configurations for [lua-nginx-module](https://github.com/openresty/lua-nginx-module). Octopus is capable of hosting many websites at the same time. Every website is made up of units called extensions that aggregate everything needed for an MVC architecture.

The heart of the system is the build process which creates all the necessary nginx configurations, create widgets, creates type system and autowire modules in dependency injection style.
[build.lua](bin/unix/build.lua) together with [config.lua](extensions/config.lua) are responsible for configurating the build/generation process, while [server.sh](bin/unix/server.sh) is responsible for the actual building, installing, starting, stoping and restarting the server:

```bash
# go to bin directory
cd bin/unix
# install nginx
. ./server.sh install
# build octopus and restart server
. ./server.sh restart
# build
. ./server.sh build
# start server
. ./server.sh start
# stop server
. ./server.sh stop
```

Prerequisites
============

```
sudo apt-get install libssl-dev
sudo apt-get install gcc g++ build-essential
```

Set Up
============

Minimum set up script:

```bash
cd bin/unix
. ./server.sh install
. ./server.sh restart
```
then just open [localhost:8787](http://localhost:8787)

Demo Shop
============

* Create database and set up database connection - databaseConnection object in [config.lua](extensions/config.lua)
* Create tables and import data - go to [localhost:8787/database](http://localhost:8787/database) and execute
```lua
db:dropAllTables()
db:createAllTables()
db:import("shopImport")
```
* use the following credentials - username 'test@test.com' and password 'test'

Copyright and License
=====================

Copyright (C) 2015-2021, StrumaSoft

All rights reserved. BSD license.


text:
from ctypes import *
from enum import IntEnum

zonoml_api = CDLL("libzonoml.so")


text:
#import <Foundation/Foundation.h>
#import "SDWebImageDownloader.h"
#import "SDWebImageOperation.h"

@interface SDWebImageDownloaderOperation : NSOperation <SDWebImageOperation>

/**
 * The request used by the operation's connection.
 */
@property (strong, nonatomic, readonly) NSURLRequest *request;

@property (assign, nonatomic) BOOL shouldDecompressImages;

/**
 * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
 *
 * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
 */
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;

/**
 * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
 *
 * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
 */
@property (nonatomic, strong) NSURLCredential *credential;

/**
 * The SDWebImageDownloaderOptions for the receiver.
 */
@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options;

/**
 *  Initializes a `SDWebImageDownloaderOperation` object
 *
 *  @see SDWebImageDownloaderOperation
 *
 *  @param request        the URL request
 *  @param options        downloader options
 *  @param progressBlock  the block executed when a new chunk of data arrives.
 *                        @note the progress block is executed on a background queue
 *  @param completedBlock the block executed when the download is done.
 *                        @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue
 *  @param cancelBlock    the block executed if the download (operation) is cancelled
 *
 *  @return the initialized instance
 */
- (id)initWithRequest:(NSURLRequest *)request
              options:(SDWebImageDownloaderOptions)options
             progress:(SDWebImageDownloaderProgressBlock)progressBlock
            completed:(SDWebImageDownloaderCompletedBlock)completedBlock
            cancelled:(SDWebImageNoParamsBlock)cancelBlock;

@end


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

<title>Renamer</title>
<meta name="date" content="2017-04-05">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Class Renamer

java.lang.Object

Renamer

public class Renamer
extends java.lang.Object

Main class which manages all the renaming operations.

Since:

1.0.0.0

Version:

1.0.0.0

Author:

Divyansh Shekhar Gaur

Field Summary

Fields

Modifier and Type
Field and Description

(package private) static java.lang.String
folder

Path to folder in which the target files are.

(package private) static Mod[]
mods

Array to store the modification options entered by user.

Constructor Summary

Constructors

Modifier
Constructor and Description

private
Renamer()

Private constructor to prevent accidental instantiation of this class.

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static void
getCriteria()

Get the criteria for renaming the files.

private static void
getPath()

Get path of the target folder.

static void
main(java.lang.String[] args)

Entry point of program.

private static void
op_rename()

Carry out the low level task of renaming.

private static void
renameInFolder()

Take input from user and do renaming.

Methods inherited from class java.lang.Object

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

Field Detail

mods

static Mod[] mods

Array to store the modification options entered by user.
 There can be at most 4 modifications. 2 at the start and 2 at the end. However, currently only one modification (i.e. at the start of file) is supported. It is planned to be extended to a more general implementation which can modify file name at all position and recongize patterns of characters and replace accordingly.

folder

static java.lang.String folder

Path to folder in which the target files are.

Constructor Detail

Renamer

private Renamer()

Private constructor to prevent accidental instantiation of this class.

Method Detail

main

public static void main(java.lang.String[] args)
                 throws java.io.IOException

Entry point of program.

Parameters:

args - No arguments needed.

Throws:

java.io.IOException - Catch an IO Exception if occurs.

Since:

1.0.0.0

renameInFolder

private static void renameInFolder()
                            throws java.io.IOException

Take input from user and do renaming.

Throws:

java.io.IOException - InputStreamReader may throw IOException

Since:

1.0.0.0

op_rename

private static void op_rename()

Carry out the low level task of renaming.

Since:

1.0.0.0

getPath

private static void getPath()

Get path of the target folder.

Since:

1.0.0.0

getCriteria

public static void getCriteria()

Get the criteria for renaming the files. Currently supports renaming only the start of the file. Help in extending it to end as well as middle of the file.

Since:

1.0.0.0

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using Machine.Specifications;

namespace Stripe.Tests
{
    public class when_deleting_a_recipient
    {
        private static StripeRecipientService _stripeRecipientService;
        private static string _createdStripeRecipientId;

        Establish context = () =>
        {
            _stripeRecipientService = new StripeRecipientService();

            var stripeRecipient = _stripeRecipientService.Create(test_data.stripe_recipient_create_options.ValidIndividual());
            _createdStripeRecipientId = stripeRecipient.Id;
        };

        Because of = () =>
            _stripeRecipientService.Delete(_createdStripeRecipientId);
    }
}


text:
package wunderdog

import java.io.{ByteArrayOutputStream, PrintStream}

import org.scalatest.FlatSpec

class FunnyFinnishWordsSpec extends FlatSpec {

  "FunnyFinnishWords" should "print 6 funny words to stdout" in {
      // Hack to obtain printed words from stdout
      val stdoutStream = new ByteArrayOutputStream
      val stdoutRedirectStream = new PrintStream(stdoutStream)

      Console.withOut(stdoutRedirectStream)(FunnyFinnishWords.main(null))
      val funnyWordsOutput = stdoutStream.toString("UTF-8")
      val funnyWords = funnyWordsOutput.split(System.lineSeparator).toList

      assert(funnyWords.size == 6)
      assert(funnyWords.contains("seremoniioissa"))
      assert(funnyWords.contains("liioittelematta"))
      assert(funnyWords.contains("seremoniioilla"))
      assert(funnyWords.contains("puuaineen"))
      assert(funnyWords.contains("leeaakaan"))
      assert(funnyWords.contains("niiaamaan"))
    }
}


text:
package mdhim;
import org.bridj.BridJ;
import org.bridj.Pointer;
import org.bridj.StructObject;
import org.bridj.ann.Field;
import org.bridj.ann.Library;
/**
 * native declaration : mdhim-tng-ycsb/src/range_server.h:1368

 * This file was autogenerated by JNAerator,

 * a tool written by Olivier Chafik that uses a few opensource projects..

 * For help, please visit NativeLibs4Java or BridJ .
 */
@Library("mdhim")
public abstract class out_req extends StructObject {
	static {
		BridJ.register();
	}
	/** C type : out_req* */
	@Field(0)
	public Pointer<out_req > next() {
		return this.io.getPointerField(this, 0);
	}
	/** C type : out_req* */
	@Field(0)
	public out_req next(Pointer<out_req > next) {
		this.io.setPointerField(this, 0, next);
		return this;
	}
	/** C type : out_req* */
	@Field(1)
	public Pointer<out_req > prev() {
		return this.io.getPointerField(this, 1);
	}
	/** C type : out_req* */
	@Field(1)
	public out_req prev(Pointer<out_req > prev) {
		this.io.setPointerField(this, 1, prev);
		return this;
	}
	/** C type : void* */
	@Field(2)
	public Pointer<? > req() {
		return this.io.getPointerField(this, 2);
	}
	/** C type : void* */
	@Field(2)
	public out_req req(Pointer<? > req) {
		this.io.setPointerField(this, 2, req);
		return this;
	}
	/** Conversion Error : MPI_Request* (failed to convert type to Java (undefined type)) */
}


text:
import S from 'lang/symbolTypes';
import Scope from 'lang/scope';
var M = require("mori"); // Couldn't figure out how to convert to ECMAScript6

var makeAssignment = function (sym, r) {
  return { status: 'ASSIGNMENT', symbol: sym, value: r };
}

var makeResult = function (r) {
  return { status: 'RESULT', res: r };
}

var makeError = function (e, vals, pos) {
  return { status: 'ERROR', message: e, involvedValues: vals, pos: pos };
}

var evaluateAdd = function (a, b, pos, scope) {
  if (M.get(a,'type') === S.T_INT && M.get(b,'type') === S.T_INT) {
    return makeResult(S.makeInt(M.get(a, 'value') + M.get(b,'value'), pos));
  } else if (M.get(a,'type') === S.T_FLOAT && M.get(b,'type') === S.T_FLOAT) {
    return makeResult(S.makeFloat(M.get(a, 'value') + M.get(b,'value'), pos));
  } else {
    return makeError("I don't understand addition on "+M.get(a,'type').toString()+" and "+M.get(b,'type').toString()
                    , [a, b], pos);
  }
};

var evaluateSub = function (a, b, pos, scope) {
  if (M.get(a,'type') === S.T_INT && M.get(b,'type') === S.T_INT) {
    return makeResult(S.makeInt(M.get(a, 'value') - M.get(b,'value'), pos));
  } else if (M.get(a,'type') === S.T_FLOAT && M.get(b,'type') === S.T_FLOAT) {
    return makeResult(S.makeFloat(M.get(a, 'value') - M.get(b,'value'), pos));
  } else {
    return makeError("I don't understand subtraction on "+M.get(a,'type').toString()+" and "+M.get(b,'type').toString()
                    , [a, b], pos);
  }
};

var evaluateMul = function (a, b, pos, scope) {
  if (M.get(a,'type') === S.T_INT && M.get(b,'type') === S.T_INT) {
    return makeResult(S.makeInt(M.get(a, 'value') * M.get(b,'value'), pos));
  } else if (M.get(a,'type') === S.T_FLOAT && M.get(b,'type') === S.T_FLOAT) {
    return makeResult(S.makeFloat(M.get(a, 'value') * M.get(b,'value'), pos));
  } else {
    return makeError("I don't understand multiplication on "+M.get(a,'type').toString()+" and "+M.get(b,'type').toString()
                    , [a, b], pos);
  }
};

var evaluateDiv = function (a, b, pos, scope) {
  var a_type = M.get(a,'type');
  var b_type = M.get(b,'type');
  var a_value = M.get(a, 'value');
  var b_value = M.get(b, 'value');
  if (a_type === S.T_INT && b_type === S.T_INT) {
    var div = a_value / b_value;
    var f = Math.trunc(div); // floor doesn't work correctly for negative numbers
    var res = S.makeInt(f, pos);
    res._couldLosePrecision = true;
    res._didLosePrecision = (f !== div);
    return makeResult(res);
  } else if (a_type === S.T_FLOAT && b_type === S.T_FLOAT) {
    return makeResult(S.makeFloat(a_value / b_value, pos));
  } else {
    return makeError("I don't understand division on "+a_type.toString()+" and "+b_type.toString()
                    , [a, b], pos);
  }
};

var evaluateEq = function (a, b, pos, scope) {
  var a_type = M.get(a,'type');
  var b_type = M.get(b,'type');
  if (a_type !== b_type) {
    return makeResult(S.makeBool(false, pos));
  } else if (a_type === S.T_INT || // Don't need to check b because we know the types match
             a_type === S.T_FLOAT ||
             a_type === S.T_BOOL) {
    return makeResult(S.makeBool(M.get(a, 'value') == M.get(b,'value'), pos));
  } else {
    return makeError("I don't understand equivalence checks on "+a_type.toString()+" and "+b_type.toString()
                    , [a, b], pos);
  }
};

var evaluateNeg = function (node, pos, scope) {
  var node_type = M.get(node,'type');
  var node_value = M.get(node,'value');
  if (node_type === S.T_INT) {
    return makeResult(S.makeInt(-node_value, pos));
  } else if (node_type === S.T_FLOAT) {
    return makeResult(S.makeFloat(-node_value, pos));
  } else {
    return makeError("I don't understand negation on "+node_type.toString()
                    , [node], pos);
  }
};

var evaluateUnaryOperator = function (node, scope) {
  var val = M.get(node,'value');
  var res;
  if (!S.isTerminal(val)) {
    res = evaluateASTTree(val, scope);
    if (res.status === 'ERROR') {
      return res;
    }
    val = res.res;
  }
  var node_pos = M.get(node,'pos');
  var node_type = M.get(node,'type');
  if (node_type === S.E_NEG) {
    res = evaluateNeg(val, node_pos, scope);
  } else {
    return makeError("I don't understand the unary operator "+node_type.toString()
                    , [node], node_pos);
  }
  node._cachedResult = res;
  return res;
}

var evaluateBinaryOperator = function (node, scope) {
  var valA = M.get(node,'valueA');
  var valB = M.get(node,'valueB');
  if (!S.isTerminal(valA)) {
    var resA = evaluateASTTree(valA, scope);
    if (resA.status === 'ERROR') {
      return resA;
    }
    valA = resA.res;
  }
  if (!S.isTerminal(valB)) {
    var resB = evaluateASTTree(valB, scope);
    if (resB.status === 'ERROR') {
      return resB;
    }
    valB = resB.res;
  }

  var res = null;
  var node_pos = M.get(node, 'pos');
  var node_type = M.get(node, 'type');
  if (node_type === S.E_ADD) {
    res = evaluateAdd(valA, valB, node_pos, scope);
  } else if (node_type === S.E_SUB) {
    res = evaluateSub(valA, valB, node_pos, scope);
  } else if (node_type === S.E_MUL) {
    res = evaluateMul(valA, valB, node_pos, scope);
  } else if (node_type === S.E_DIV) {
    res = evaluateDiv(valA, valB, node_pos, scope);
  } else if (node_type === S.E_EQ) {
    res = evaluateEq(valA, valB, node_pos, scope);
  } else {
    return makeError("I don't understand the binary operator "+node_type.toString()
                    , [node], node_pos);
  }
  node._cachedResult = res;
  return res;
}

var evaluateTerminal = function (node, scope) {
  return makeResult(node);
};

var evaluateSymbol = function (node, scope) {
  // TODO: Think about optimizing this if it becomes a bottleneck;
  // it has to walk the scope 2x for the sake of avoiding try/catch
  var node_name = M.get(node,'name');
  var node_pos = M.get(node,'pos');
  if (Scope.scopeOfSymbol(scope, node_name) === null) {
    var e = makeError("I can't find "+node_name.toString()+" in my scope or parent scopes :("
                    , [node], node_pos);
    node._cachedResult = e;
    return e;
  }
  var s = Scope.lookupSymbolValue(scope, node_name);
  s = M.assoc(s, 'pos', node_pos);
  // pos actually doesn't make much sense for values
  // mapped to symbols in the scope contents.
  // However, when we do a symbol lookup, we can set it
  // to the pos of the symbol we replaced.

  s = makeResult(s);
  node._cachedResult = s;
  return s;
};

var evaluateAssign = function (node, scope) {
  var res = evaluateASTTree(M.get(node,'expr'), scope);
  if (res.status === 'ERROR') {
    return res;
  }
  return makeAssignment(M.get(node,'symbol'), res.res);
};

// NOTE: As this is architected, this MUST NOT modify the scope. EVER.
// Otherwise, all of the time travelling stuff won't work.
// This means that functions must be externally pure. i.e. a function
// can modify its own local variables but may not modify
// variables external to its scope.
export default function evaluateASTTree (node, scope) {
  if (!node) {
    return;
  }
  var node_type = M.get(node,'type');
  if (node_type === S.S_ASSIGN) {
    return evaluateAssign(node, scope);
  } else if (S.isUnaryOperator(node_type)) {
    return evaluateUnaryOperator(node, scope);
  } else if (S.isBinaryOperator(node_type)) {
    return evaluateBinaryOperator(node, scope);
  } else if (node_type === S.T_SYM) { // Needs to be above isTerminal because we don't want to evaluate symbols before lookup
    return evaluateSymbol(node, scope);
  } else if (S.isTerminal(node_type)) {
    return evaluateTerminal(node, scope);
  } else {
    return makeError("I don't understand "+node_type.toString()
                    , [node], M.get(node,'pos'));
    // S.E_CALL
  }
};


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var plugin_1 = require('./plugin');
/**
 * @name OneSignal
 * @description
 * The OneSignal plugin is an client implementation for using the [OneSignal](https://onesignal.com/) Service.
 * OneSignal is a simple implementation for delivering push notifications.
 *
 * Requires Cordova plugin: `onesignal-cordova-plugin`. For more info, please see the [OneSignal Cordova Docs](https://documentation.onesignal.com/docs/phonegap-sdk-installation).
 *
 * @usage
 * ```typescript
 * import { OneSignal } from 'ionic-native';
 *
 * OneSignal.startInit('b2f7f966-d8cc-11e4-bed1-df8f05be55ba', '703322744261');
 *
 * OneSignal.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.InAppAlert);
 *
 * OneSignal.handleNotificationReceived().subscribe(() => {
 *  // do something when notification is received
 * });
 *
 * OneSignal.handleNotificationOpened().subscribe(() => {
 *   // do something when a notification is opened
 * });
 *
 * OneSignal.endInit();
 * ```
 *
 */
var OneSignal = (function () {
    function OneSignal() {
    }
    /**
     * Start the initialization process. Once you are done configuring OneSignal, call the endInit function.
     *
     * @param {string} appId Your AppId from your OneSignal app
     * @param {string} googleProjectNumber The Google Project Number (which you can get from the Google Developer Portal) and the autoRegister option.
     * @returns {any}
     */
    OneSignal.startInit = function (appId, googleProjectNumber) { return; };
    /**
     * Callback to run when a notification is received
     * @return {Observable<any>}
     */
    OneSignal.handleNotificationReceived = function () { return; };
    /**
     * Callback to run when a notification is opened
     * @return {Observable<any>}
     */
    OneSignal.handleNotificationOpened = function () { return; };
    /**
     *
     * @param settings
     * @returns {any}
     */
    OneSignal.iOSSettings = function (settings) { return; };
    /**
     * @returns {any}
     */
    OneSignal.endInit = function () { return; };
    /**
     * Retrieve a list of tags that have been set on the user from the OneSignal server.
     *
     * @returns {Promise<any>} Returns a Promise that resolves when tags are recieved.
     */
    OneSignal.getTags = function () { return; };
    /**
     * Lets you retrieve the OneSignal user id and device token.
     * Your handler is called after the device is successfully registered with OneSignal.
     *
     * @returns {Promise<any>} Returns a Promise that reolves if the device was successfully registered.
     * It returns a JSON with `userId`and `pushToken`.
     */
    OneSignal.getIds = function () { return; };
    /**
     * Tag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com/) to target these users.
     * Recommend using sendTags over sendTag if you need to set more than one tag on a user at a time.
     *
     * @param {string} Key of your choosing to create or update.
     * @param {string} Value to set on the key. NOTE: Passing in a blank String deletes the key, you can also call deleteTag.
     */
    OneSignal.sendTag = function (key, value) { };
    /**
     * Tag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com/) to target these users.
     * Recommend using sendTags over sendTag if you need to set more than one tag on a user at a time.
     *
     * @param {string} Pass a json object with key/value pairs like: {key: "value", key2: "value2"}
     */
    OneSignal.sendTags = function (json) { };
    /**
     * Deletes a tag that was previously set on a user with `sendTag` or `sendTags`. Use `deleteTags` if you need to delete more than one.
     *
     * @param {string} Key to remove.
     */
    OneSignal.deleteTag = function (key) { };
    /**
     * Deletes tags that were previously set on a user with `sendTag` or `sendTags`.
     *
     * @param {Array<string>} Keys to remove.
     */
    OneSignal.deleteTags = function (keys) { };
    /**
     * Call this when you would like to prompt an iOS user to accept push notifications with the default system prompt.
     * Only use if you passed false to autoRegister when calling init.
     */
    OneSignal.registerForPushNotifications = function () { };
    /**
    * Warning:
    * Only applies to Android and Amazon. You can call this from your UI from a button press for example to give your user's options for your notifications.
    *
    * By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode.
    * Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.
    *
    * @param {boolean} false to disable vibrate, true to re-enable it.
    */
    OneSignal.enableVibrate = function (enable) { };
    /**
    * Warning:
    * Only applies to Android and Amazon. You can call this from your UI from a button press for example to give your user's options for your notifications.
    *
    * By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on.
    * Passing false means that the device will only vibrate unless the device is set to a total silent mode.
    *
    * @param {boolean} false to disable sound, true to re-enable it.
    */
    OneSignal.enableSound = function (enable) { };
    /**
    *
    * Setting to control how OneSignal notifications will be shown when one is received while your app is in focus. By default this is set to inAppAlert, which can be helpful during development.
    *
    * @param {number} displayOption Options are 0 = None, 1 = InAppAlert, and 2 = Notification.
    */
    OneSignal.inFocusDisplaying = function (displayOption) { };
    /**
    * You can call this method with false to opt users out of receiving all notifications through OneSignal.
    * You can pass true later to opt users back into notifications.
    *
    * @param {boolean} enable
    */
    OneSignal.setSubscription = function (enable) { };
    /**
    *
    * @param {notificationObj} Parameters see POST [documentation](https://documentation.onesignal.com/v2.0/docs/notifications-create-notification)
    * @returns {Promise<any>} Returns a Promise that resolves if the notification was send successfully.
    */
    OneSignal.postNotification = function (notificationObj) { return; };
    /**
    * Prompts the user for location permission to allow geotagging based on the "Location radius" filter on the OneSignal dashboard.
    */
    OneSignal.promptLocation = function () { };
    /**
     *
     * @param email {string}
     */
    OneSignal.syncHashedEmail = function (email) { };
    /**
    * Enable logging to help debug if you run into an issue setting up OneSignal.
    * The logging levels are as follows: 0 = None, 1= Fatal, 2 = Errors, 3 = Warnings, 4 = Info, 5 = Debug, 6 = Verbose

    * The higher the value the more information is shown.
    *
    * @param {loglevel} contains two properties: logLevel (for console logging) and visualLevel (for dialog messages)
    */
    OneSignal.setLogLevel = function (logLevel) { };
    /**
     * constants to use in inFocusDisplaying()
     */
    OneSignal.OSInFocusDisplayOption = {
        None: 0,
        InAppAlert: 1,
        Notification: 2
    };
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "startInit", null);
    __decorate([
        plugin_1.Cordova({
            observable: true
        })
    ], OneSignal, "handleNotificationReceived", null);
    __decorate([
        plugin_1.Cordova({
            observable: true
        })
    ], OneSignal, "handleNotificationOpened", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "iOSSettings", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "endInit", null);
    __decorate([
        plugin_1.Cordova()
    ], OneSignal, "getTags", null);
    __decorate([
        plugin_1.Cordova()
    ], OneSignal, "getIds", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "sendTag", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "sendTags", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "deleteTag", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "deleteTags", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "registerForPushNotifications", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "enableVibrate", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "enableSound", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "inFocusDisplaying", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "setSubscription", null);
    __decorate([
        plugin_1.Cordova()
    ], OneSignal, "postNotification", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "promptLocation", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "syncHashedEmail", null);
    __decorate([
        plugin_1.Cordova({ sync: true })
    ], OneSignal, "setLogLevel", null);
    OneSignal = __decorate([
        plugin_1.Plugin({
            pluginName: 'OneSignal',
            plugin: 'onesignal-cordova-plugin',
            pluginRef: 'plugins.OneSignal',
            repo: 'https://github.com/OneSignal/OneSignal-Cordova-SDK'
        })
    ], OneSignal);
    return OneSignal;
}());
exports.OneSignal = OneSignal;
//# sourceMappingURL=onesignal.js.map


text:
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Formatting and tools for comments.

use std::{self, iter};

use syntax::codemap::Span;

use Indent;
use config::Config;
use rewrite::RewriteContext;
use string::{StringFormat, rewrite_string};
use utils::wrap_str;

pub fn rewrite_comment(orig: &str,
                       block_style: bool,
                       width: usize,
                       offset: Indent,
                       config: &Config)
                       -> Option<String> {
    let s = orig.trim();

    // Edge case: block comments. Let's not trim their lines (for now).
    let (opener, closer, line_start) =
        if block_style {
            ("/* ", " */", " * ")
        } else if !config.normalize_comments {
            if orig.starts_with("/**") && !orig.starts_with("/**/") {
                ("/** ", " **/", " ** ")
            } else if orig.starts_with("/*!") {
                ("/*! ", " */", " * ")
            } else if orig.starts_with("/*") {
                ("/* ", " */", " * ")
            } else if orig.starts_with("///") {
                ("/// ", "", "/// ")
            } else if orig.starts_with("//!") {
                ("//! ", "", "//! ")
            } else {
                ("// ", "", "// ")
            }
        } else if orig.starts_with("///") ||
                  (orig.starts_with("/**") && !orig.starts_with("/**/")) {
            ("/// ", "", "/// ")
        } else if orig.starts_with("//!") || orig.starts_with("/*!") {
            ("//! ", "", "//! ")
        } else {
            ("// ", "", "// ")
        };

    let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);

    let fmt = StringFormat {
        opener: "",
        closer: "",
        line_start: line_start,
        line_end: "",
        width: max_chars,
        offset: offset + (opener.len() - line_start.len()),
        trim_end: true,
        config: config,
    };

    let indent_str = offset.to_string(config);
    let line_breaks = s.chars().filter(|&c| c == '\n').count();

    let lines = s.lines()
        .enumerate()
        .map(|(i, mut line)| {
            line = line.trim();
            // Drop old closer.
            if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
                line = &line[..(line.len() - 2)];
            }

            line.trim_right()
        })
        .map(left_trim_comment_line)
        .map(|line| {
            if orig.starts_with("/*") && line_breaks == 0 {
                line.trim_left()
            } else {
                line
            }
        });

    let mut result = opener.to_owned();
    for line in lines {
        if result == opener {
            if line.len() == 0 {
                continue;
            }
        } else {
            result.push('\n');
            result.push_str(&indent_str);
            result.push_str(line_start);
        }

        if config.wrap_comments && line.len() > max_chars {
            let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
            result.push_str(&rewrite);
        } else {
            if line.len() == 0 {
                // Remove space if this is an empty comment or a doc comment.
                result.pop();
            }
            result.push_str(line);
        }
    }

    result.push_str(closer);
    if result == opener {
        // Trailing space.
        result.pop();
    }

    Some(result)
}

fn left_trim_comment_line(line: &str) -> &str {
    if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
       line.starts_with("/** ") {
        &line[4..]
    } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
              line.starts_with("///") ||
              line.starts_with("** ") || line.starts_with("/*!") ||
              (line.starts_with("/**") && !line.starts_with("/**/")) {
        &line[3..]
    } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
              line.starts_with("**") {
        &line[2..]
    } else if line.starts_with("*") {
        &line[1..]
    } else {
        line
    }
}

pub trait FindUncommented {
    fn find_uncommented(&self, pat: &str) -> Option<usize>;
}

impl FindUncommented for str {
    fn find_uncommented(&self, pat: &str) -> Option<usize> {
        let mut needle_iter = pat.chars();
        for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
            match needle_iter.next() {
                None => {
                    return Some(i - pat.len());
                }
                Some(c) => {
                    match kind {
                        FullCodeCharKind::Normal if b == c => {}
                        _ => {
                            needle_iter = pat.chars();
                        }
                    }
                }
            }
        }

        // Handle case where the pattern is a suffix of the search string
        match needle_iter.next() {
            Some(_) => None,
            None => Some(self.len() - pat.len()),
        }
    }
}

// Returns the first byte position after the first comment. The given string
// is expected to be prefixed by a comment, including delimiters.
// Good: "/* /* inner */ outer */ code();"
// Bad:  "code(); // hello\n world!"
pub fn find_comment_end(s: &str) -> Option<usize> {
    let mut iter = CharClasses::new(s.char_indices());
    for (kind, (i, _c)) in &mut iter {
        if kind == FullCodeCharKind::Normal {
            return Some(i);
        }
    }

    // Handle case where the comment ends at the end of s.
    if iter.status == CharClassesStatus::Normal {
        Some(s.len())
    } else {
        None
    }
}

/// Returns true if text contains any comment.
pub fn contains_comment(text: &str) -> bool {
    CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
}

struct CharClasses<T>
    where T: Iterator,
          T::Item: RichChar
{
    base: iter::Peekable<T>,
    status: CharClassesStatus,
}

trait RichChar {
    fn get_char(&self) -> char;
}

impl RichChar for char {
    fn get_char(&self) -> char {
        *self
    }
}

impl RichChar for (usize, char) {
    fn get_char(&self) -> char {
        self.1
    }
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
enum CharClassesStatus {
    Normal,
    LitString,
    LitStringEscape,
    LitChar,
    LitCharEscape,
    // The u32 is the nesting deepness of the comment
    BlockComment(u32),
    // Status when the '/' has been consumed, but not yet the '*', deepness is
    // the new deepness (after the comment opening).
    BlockCommentOpening(u32),
    // Status when the '*' has been consumed, but not yet the '/', deepness is
    // the new deepness (after the comment closing).
    BlockCommentClosing(u32),
    LineComment,
}

/// Distinguish between functionnal part of code and comments
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum CodeCharKind {
    Normal,
    Comment,
}

/// Distinguish between functionnal part of code and comments,
/// describing opening and closing of comments for ease when chunking
/// code from tagged characters
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
enum FullCodeCharKind {
    Normal,
    /// The first character of a comment, there is only one for a comment (always '/')
    StartComment,
    /// Any character inside a comment including the second character of comment
    /// marks ("//", "/*")
    InComment,
    /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
    EndComment,
}

impl FullCodeCharKind {
    fn is_comment(&self) -> bool {
        match *self {
            FullCodeCharKind::Normal => false,
            FullCodeCharKind::StartComment |
            FullCodeCharKind::InComment |
            FullCodeCharKind::EndComment => true,
        }
    }

    fn to_codecharkind(&self) -> CodeCharKind {
        if self.is_comment() {
            CodeCharKind::Comment
        } else {
            CodeCharKind::Normal
        }
    }
}

impl<T> CharClasses<T>
    where T: Iterator,
          T::Item: RichChar
{
    fn new(base: T) -> CharClasses<T> {
        CharClasses {
            base: base.peekable(),
            status: CharClassesStatus::Normal,
        }
    }
}

impl<T> Iterator for CharClasses<T>
    where T: Iterator,
          T::Item: RichChar
{
    type Item = (FullCodeCharKind, T::Item);

    fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
        let item = try_opt!(self.base.next());
        let chr = item.get_char();
        self.status = match self.status {
            CharClassesStatus::LitString => {
                match chr {
                    '"' => CharClassesStatus::Normal,
                    '\\' => CharClassesStatus::LitStringEscape,
                    _ => CharClassesStatus::LitString,
                }
            }
            CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
            CharClassesStatus::LitChar => {
                match chr {
                    '\\' => CharClassesStatus::LitCharEscape,
                    '\'' => CharClassesStatus::Normal,
                    _ => CharClassesStatus::LitChar,
                }
            }
            CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
            CharClassesStatus::Normal => {
                match chr {
                    '"' => CharClassesStatus::LitString,
                    '\'' => CharClassesStatus::LitChar,
                    '/' => {
                        match self.base.peek() {
                            Some(next) if next.get_char() == '*' => {
                                self.status = CharClassesStatus::BlockCommentOpening(1);
                                return Some((FullCodeCharKind::StartComment, item));
                            }
                            Some(next) if next.get_char() == '/' => {
                                self.status = CharClassesStatus::LineComment;
                                return Some((FullCodeCharKind::StartComment, item));
                            }
                            _ => CharClassesStatus::Normal,
                        }
                    }
                    _ => CharClassesStatus::Normal,
                }
            }
            CharClassesStatus::BlockComment(deepness) => {
                assert!(deepness != 0);
                self.status = match self.base.peek() {
                    Some(next) if next.get_char() == '/' && chr == '*' => {
                        CharClassesStatus::BlockCommentClosing(deepness - 1)
                    }
                    Some(next) if next.get_char() == '*' && chr == '/' => {
                        CharClassesStatus::BlockCommentOpening(deepness + 1)
                    }
                    _ => CharClassesStatus::BlockComment(deepness),
                };
                return Some((FullCodeCharKind::InComment, item));
            }
            CharClassesStatus::BlockCommentOpening(deepness) => {
                assert_eq!(chr, '*');
                self.status = CharClassesStatus::BlockComment(deepness);
                return Some((FullCodeCharKind::InComment, item));
            }
            CharClassesStatus::BlockCommentClosing(deepness) => {
                assert_eq!(chr, '/');
                if deepness == 0 {
                    self.status = CharClassesStatus::Normal;
                    return Some((FullCodeCharKind::EndComment, item));
                } else {
                    self.status = CharClassesStatus::BlockComment(deepness);
                    return Some((FullCodeCharKind::InComment, item));
                }
            }
            CharClassesStatus::LineComment => {
                match chr {
                    '\n' => {
                        self.status = CharClassesStatus::Normal;
                        return Some((FullCodeCharKind::EndComment, item));
                    }
                    _ => {
                        self.status = CharClassesStatus::LineComment;
                        return Some((FullCodeCharKind::InComment, item));
                    }
                }
            }
        };
        Some((FullCodeCharKind::Normal, item))
    }
}

/// Iterator over functional and commented parts of a string. Any part of a string is either
/// functional code, either *one* block comment, either *one* line comment. Whitespace between
/// comments is functional code. Line comments contain their ending newlines.
struct UngroupedCommentCodeSlices<'a> {
    slice: &'a str,
    iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
}

impl<'a> UngroupedCommentCodeSlices<'a> {
    fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
        UngroupedCommentCodeSlices {
            slice: code,
            iter: CharClasses::new(code.char_indices()).peekable(),
        }
    }
}

impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
    type Item = (CodeCharKind, usize, &'a str);

    fn next(&mut self) -> Option<Self::Item> {
        let (kind, (start_idx, _)) = try_opt!(self.iter.next());
        match kind {
            FullCodeCharKind::Normal => {
                // Consume all the Normal code
                while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
                    let _ = self.iter.next();
                }
            }
            FullCodeCharKind::StartComment => {
                // Consume the whole comment
                while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
            }
            _ => panic!(),
        }
        let slice = match self.iter.peek() {
            Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
            None => &self.slice[start_idx..],
        };
        Some((if kind.is_comment() {
            CodeCharKind::Comment
        } else {
            CodeCharKind::Normal
        },
              start_idx,
              slice))
    }
}

/// Iterator over an alternating sequence of functional and commented parts of
/// a string. The first item is always a, possibly zero length, subslice of
/// functional text. Line style comments contain their ending newlines.
pub struct CommentCodeSlices<'a> {
    slice: &'a str,
    last_slice_kind: CodeCharKind,
    last_slice_end: usize,
}

impl<'a> CommentCodeSlices<'a> {
    pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
        CommentCodeSlices {
            slice: slice,
            last_slice_kind: CodeCharKind::Comment,
            last_slice_end: 0,
        }
    }
}

impl<'a> Iterator for CommentCodeSlices<'a> {
    type Item = (CodeCharKind, usize, &'a str);

    fn next(&mut self) -> Option<Self::Item> {
        if self.last_slice_end == self.slice.len() {
            return None;
        }

        let mut sub_slice_end = self.last_slice_end;
        let mut first_whitespace = None;
        let subslice = &self.slice[self.last_slice_end..];
        let mut iter = CharClasses::new(subslice.char_indices());

        for (kind, (i, c)) in &mut iter {
            let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
                                       &subslice[..2] == "//" &&
                                       [' ', '\t'].contains(&c);

            if is_comment_connector && first_whitespace.is_none() {
                first_whitespace = Some(i);
            }

            if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
                let last_index = match first_whitespace {
                    Some(j) => j,
                    None => i,
                };
                sub_slice_end = self.last_slice_end + last_index;
                break;
            }

            if !is_comment_connector {
                first_whitespace = None;
            }
        }

        if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
            // This was the last subslice.
            sub_slice_end = match first_whitespace {
                Some(i) => self.last_slice_end + i,
                None => self.slice.len(),
            };
        }

        let kind = match self.last_slice_kind {
            CodeCharKind::Comment => CodeCharKind::Normal,
            CodeCharKind::Normal => CodeCharKind::Comment,
        };
        let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
        self.last_slice_end = sub_slice_end;
        self.last_slice_kind = kind;

        Some(res)
    }
}

/// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
/// (if it fits in the width/offset, else return None), else return `new`
pub fn recover_comment_removed(new: String,
                               span: Span,
                               context: &RewriteContext,
                               width: usize,
                               offset: Indent)
                               -> Option<String> {
    let snippet = context.snippet(span);
    if changed_comment_content(&snippet, &new) {
        // We missed some comments
        // Keep previous formatting if it satisfies the constrains
        return wrap_str(snippet, context.config.max_width, width, offset);
    } else {
        Some(new)
    }
}

/// Return true if the two strings of code have the same payload of comments.
/// The payload of comments is everything in the string except:
///     - actual code (not comments)
///     - comment start/end marks
///     - whitespace
///     - '*' at the beginning of lines in block comments
fn changed_comment_content(orig: &str, new: &str) -> bool {
    // Cannot write this as a fn since we cannot return types containing closures
    let code_comment_content = |code| {
        let slices = UngroupedCommentCodeSlices::new(code);
        slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
            .flat_map(|(_, _, s)| CommentReducer::new(s))
    };
    let res = code_comment_content(orig).ne(code_comment_content(new));
    debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
           res,
           orig,
           new,
           code_comment_content(orig).collect::<String>(),
           code_comment_content(new).collect::<String>());
    res
}

/// Iterator over the 'payload' characters of a comment.
/// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
/// The comment must be one comment, ie not more than one start mark (no multiple line comments,
/// for example).
struct CommentReducer<'a> {
    is_block: bool,
    at_start_line: bool,
    iter: std::str::Chars<'a>,
}

impl<'a> CommentReducer<'a> {
    fn new(comment: &'a str) -> CommentReducer<'a> {
        let is_block = comment.starts_with("/*");
        let comment = remove_comment_header(comment);
        CommentReducer {
            is_block: is_block,
            at_start_line: false, // There are no supplementary '*' on the first line
            iter: comment.chars(),
        }
    }
}

impl<'a> Iterator for CommentReducer<'a> {
    type Item = char;
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let mut c = try_opt!(self.iter.next());
            if self.is_block && self.at_start_line {
                while c.is_whitespace() {
                    c = try_opt!(self.iter.next());
                }
                // Ignore leading '*'
                if c == '*' {
                    c = try_opt!(self.iter.next());
                }
            } else {
                if c == '\n' {
                    self.at_start_line = true;
                }
            }
            if !c.is_whitespace() {
                return Some(c);
            }
        }
    }
}

fn remove_comment_header(comment: &str) -> &str {
    if comment.starts_with("///") || comment.starts_with("//!") {
        &comment[3..]
    } else if comment.starts_with("//") {
        &comment[2..]
    } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
              comment.starts_with("/*!") {
        &comment[3..comment.len() - 2]
    } else {
        assert!(comment.starts_with("/*"),
                format!("string '{}' is not a comment", comment));
        &comment[2..comment.len() - 2]
    }
}

#[cfg(test)]
mod test {
    use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
                FindUncommented, CommentCodeSlices};
    use Indent;

    #[test]
    fn char_classes() {
        let mut iter = CharClasses::new("//\n\n".chars());

        assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
        assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
        assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
        assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
        assert_eq!(None, iter.next());
    }

    #[test]
    fn comment_code_slices() {
        let input = "code(); /* test */ 1 + 1";
        let mut iter = CommentCodeSlices::new(input);

        assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
        assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
                   iter.next().unwrap());
        assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
        assert_eq!(None, iter.next());
    }

    #[test]
    fn comment_code_slices_two() {
        let input = "// comment\n    test();";
        let mut iter = CommentCodeSlices::new(input);

        assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
        assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
                   iter.next().unwrap());
        assert_eq!((CodeCharKind::Normal, 11, "    test();"),
                   iter.next().unwrap());
        assert_eq!(None, iter.next());
    }

    #[test]
    fn comment_code_slices_three() {
        let input = "1 // comment\n    // comment2\n\n";
        let mut iter = CommentCodeSlices::new(input);

        assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
        assert_eq!((CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
                   iter.next().unwrap());
        assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
        assert_eq!(None, iter.next());
    }

    #[test]
    #[cfg_attr(rustfmt, rustfmt_skip)]
    fn format_comments() {
        let mut config: ::config::Config = Default::default();
        config.wrap_comments = true;

        let comment = rewrite_comment(" //test", true, 100, Indent::new(0, 100), &config).unwrap();
        assert_eq!("/* test */", comment);

        let comment = rewrite_comment("// comment on a",
                                      false,
                                      10,
                                      Indent::empty(),
                                      &config).unwrap();
        assert_eq!("// comment\n// on a", comment);

        let comment = rewrite_comment("//  A multi line comment\n             // between args.",
                                      false,
                                      60,
                                      Indent::new(0, 12),
                                      &config).unwrap();
        assert_eq!("//  A multi line comment\n            // between args.", comment);

        let input = "// comment";
        let expected =
            "/* comment */";
        let comment = rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap();
        assert_eq!(expected, comment);

        let comment = rewrite_comment("/*   trimmed    */",
                                      true,
                                      100,
                                      Indent::new(0, 100),
                                      &config).unwrap();
        assert_eq!("/* trimmed */", comment);
    }

    // This is probably intended to be a non-test fn, but it is not used. I'm
    // keeping it around unless it helps us test stuff.
    fn uncommented(text: &str) -> String {
        CharClasses::new(text.chars())
            .filter_map(|(s, c)| {
                match s {
                    FullCodeCharKind::Normal => Some(c),
                    _ => None,
                }
            })
            .collect()
    }

    #[test]
    fn test_uncommented() {
        assert_eq!(&uncommented("abc/*...*/"), "abc");
        assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
                   "..ac\n");
        assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
    }

    #[test]
    fn test_contains_comment() {
        assert_eq!(contains_comment("abc"), false);
        assert_eq!(contains_comment("abc // qsdf"), true);
        assert_eq!(contains_comment("abc /* kqsdf"), true);
        assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
    }

    #[test]
    fn test_find_uncommented() {
        fn check(haystack: &str, needle: &str, expected: Option<usize>) {
            assert_eq!(expected, haystack.find_uncommented(needle));
        }

        check("/*/ */test", "test", Some(6));
        check("//test\ntest", "test", Some(7));
        check("/* comment only */", "whatever", None);
        check("/* comment */ some text /* more commentary */ result",
              "result",
              Some(46));
        check("sup // sup", "p", Some(2));
        check("sup", "x", None);
        check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
        check("/*sup yo? \n sup*/ sup", "p", Some(20));
        check("hel/*lohello*/lo", "hello", None);
        check("acb", "ab", None);
        check(",/*A*/ ", ",", Some(0));
        check("abc", "abc", Some(0));
        check("/* abc */", "abc", None);
        check("/**/abc/* */", "abc", Some(4));
        check("\"/* abc */\"", "abc", Some(4));
        check("\"/* abc", "abc", Some(4));
    }
}


text:
provides a helper function that allows the grouping\coalesing of async function calls that have cachable output. This provides more resiliance around cachable code paths that have not been cached yet.

### why?
if you had a route that took 20 seconds to resolve the first time, but was cachable if 1000 users hit that route before it had a chance to resolve it would result in an attempt to resolve that route 1000 times.

collapsio will limit the number of times that route can be executed concurrently and hold the other request until it has been resolved and then passes those results onto the 1000 requests.

### usage

    var collapse = require('./collapsio');

    collapse({}, 'key-http://google.com', request.get.bind(null, 'http://google.com'), function callback(req, res) {
    });

collapse(
- options - object
    - retryTimeout
        - default: 250
        - how long before the action is retried if it has not returned
    - maxTries
        - default: infinity
        - how many times an action is attempted
    - gracePeriod
        - default: 1000
        - how many ms the result of an action will be cached
- key - string
    - used to identify which calls are collapsed\grouped\coallesed together
- action - function
    - a function must be provided that takes a callback as its arguments, functions with more complex interfaces can be curried with fn.bind
- callback - function
     - the function that is executed once the action has been completed or its results have been cached

)
### example
##### This example will simulate 100000 requests to google.com/ over 10 seconds
- Without a cache this would never complete.

        var collapse = require('./collapsio'),
            request = require('request'),
            url = 'http://google.com',
            start = new Date(),
            requestCount = 100000,
            requestCompleted = 0;

        for (var i = 0; i < requestCount; i++) {
            request.get(url, function(req, res) {
                requestCompleted++;
                if (requestCompleted === requestCount) console.log("Completed in:", new Date() - start + "ms");
            });
        }

- With a cache a large number of requests will be created in the time it takes for the first one to return and populate the cache, and in many cases prevent the first request from actually returning.

        var collapse = require('./collapsio'),
            request = require('request'),
            url = 'http://google.com',
            start = new Date(),
            requestCount = 100000,
            requestCompleted = 0,
            cachedResponse = null;

        for (var i = 0; i < requestCount; i++) {
            if(!cachedResponse){
              request.get(url, function(req, res) {
                    cachedResponse = arguments;
                    requestCompleted++;
                    if (requestCompleted === requestCount) console.log("Completed in:", new Date() - start + "ms");
                });
            } else {
                requestCompleted++;
                    if (requestCompleted === requestCount) console.log("Completed in:", new Date() - start + "ms");
            }

        }

- With collapsio a significantly lower number of requests are made and the result of the first successful request are passed to all of the attempts.

        var collapse = require('./collapsio'),
            request = require('request'),
            url = 'http://google.com',
            start = new Date(),
            requestCount = 100000,
            requestCompleted = 0;

        for (var i = 0; i < requestCount; i++) {
            collapse({}, url, request.get.bind(null, url), function(req, res) {
                requestCompleted++;
                if (requestCompleted === requestCount) console.log("Completed in:", new Date() - start + "ms");
            });
        }


text:
var expect = require('chai').expect;
var lodash = require('lodash');
var nock = require('nock');
var sinon = require('sinon');

var WebAPIClient = require('../../../lib/clients/web/client');

var mockTransport = function (args, cb) {
  cb(args.data.err, args.headers, args.data.statusCode, args.data.body);
};

describe('Web API Client', function () {

  it('should accept supplied defaults when present', function () {
    var opts = {
      slackAPIUrl: 'test',
      userAgent: 'test',
      transport: lodash.noop,
    };
    var client = new WebAPIClient('test-token', opts);

    expect(client.slackAPIUrl).to.equal('test');
    expect(client.userAgent).to.equal('test');
  });

  it('should register facets  during construction', function () {
    var client = new WebAPIClient('test-token', { transport: lodash.noop });
    expect(client.auth).to.not.equal(undefined);
  });

  it('should make API calls via the transport function', function (done) {
    var args = {
      headers: {},
      statusCode: 200,
      body: '{"test": 10}',
    };

    var client = new WebAPIClient('test-token', { transport: mockTransport });

    client.makeAPICall('test', args, function (err, res) {
      expect(res).to.deep.equal({ test: 10 });
      done();
    });
  });

  it('should not crash when no callback is supplied to an API request', function () {
    var client = new WebAPIClient('test-token', { transport: mockTransport });

    client.makeAPICall('test', { test: 'test' });
  });

  describe('it should retry failed or rate-limited requests', function () {

    var attemptAPICall = function (done) {
      var client;

      nock('https://slack.com/api')
        .post('/test')
        .reply(200, '{}');

      client = new WebAPIClient('test-token', {
        retryConfig: {
          minTimeout: 0,
          maxTimeout: 1,
        },
      });
      sinon.spy(client, 'transport');

      client.makeAPICall('test', {}, function () {
        expect(client.transport.callCount).to.equal(2);
        done();
      });
    };

    it('should pause job execution in response to a 429 header', function (done) {
      nock('https://slack.com/api')
        .post('/test')
        .reply(429, '{}', { 'X-Retry-After': 0 });

      attemptAPICall(done);
    });

    it('should retry failed requests', function (done) {
      nock('https://slack.com/api')
        .post('/test')
        .replyWithError('this should never happen');

      attemptAPICall(done);
    });

    it('should retry non 200 or 429 responses', function (done) {
      nock('https://slack.com/api')
        .post('/test')
        .reply(500, '');

      attemptAPICall(done);
    });

  });

});


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal"
    android:weightSum="1">
    <Button
        android:id="@+id/button_1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/button_teal"
        android:textStyle="bold" />
</LinearLayout>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Cactaceae Consensis Init. 5:13. 1998

#### Original name
Echinocactus crassihamatus F.A.C.Weber

### Remarks
null