text:
package com.intellij.ide.lightEdit.project;

import com.intellij.ide.lightEdit.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorLocation;
import com.intellij.openapi.fileEditor.FileEditorProvider;
import com.intellij.openapi.fileEditor.ex.FileEditorWithProvider;
import com.intellij.openapi.fileEditor.impl.EditorWindow;
import com.intellij.openapi.fileEditor.impl.EditorWithProviderComposite;
import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public final class LightEditFileEditorManagerImpl extends FileEditorManagerImpl {

  LightEditFileEditorManagerImpl(@NotNull Project project) {
    super(project);
  }

  @Override
  public void loadState(@NotNull Element state) {
    // do not open previously opened files
  }

  @Override
  public @Nullable Element getState() {
    return null;
  }

  @Override
  public boolean isProblem(@NotNull VirtualFile file) {
    return false;
  }

  @Override
  public @NotNull Pair<FileEditor[], FileEditorProvider[]> openFileImpl2(@NotNull EditorWindow window,
                                                                         @NotNull VirtualFile file,
                                                                         boolean focusEditor) {
    LightEditService.getInstance().openFile(file);
    return getEditorsWithProviders(file);
  }

  @Override
  public @NotNull Pair<FileEditor[], FileEditorProvider[]> getEditorsWithProviders(@NotNull VirtualFile file) {
    FileEditorWithProvider data = getSelectedEditorWithProvider(file);
    return data != null
           ? Pair.create(new FileEditor[]{data.getFileEditor()}, new FileEditorProvider[]{data.getProvider()})
           : Pair.create(FileEditor.EMPTY_ARRAY, new FileEditorProvider[0]);
  }

  @Override
  public @Nullable FileEditorWithProvider getSelectedEditorWithProvider(@NotNull VirtualFile file) {
    LightEditorManagerImpl editorManager = (LightEditorManagerImpl)LightEditService.getInstance().getEditorManager();
    LightEditorInfoImpl editorInfo = (LightEditorInfoImpl)editorManager.findOpen(file);
    if (editorInfo != null) {
      return new FileEditorWithProvider(editorInfo.getFileEditor(), editorInfo.getProvider());
    }
    return null;
  }

  @Override
  public @Nullable FileEditor getSelectedEditor() {
    return LightEditService.getInstance().getSelectedFileEditor();
  }

  @Override
  public Editor getSelectedTextEditor() {
    return LightEditorInfoImpl.getEditor(getSelectedEditor());
  }

  @Override
  public VirtualFile @NotNull [] getOpenFiles() {
    return VfsUtilCore.toVirtualFileArray(LightEditService.getInstance().getEditorManager().getOpenFiles());
  }

  @Override
  public boolean isFileOpen(@NotNull VirtualFile file) {
    return LightEditService.getInstance().getEditorManager().isFileOpen(file);
  }

  @Override
  public boolean hasOpenedFile() {
    return !LightEditService.getInstance().getEditorManager().getOpenFiles().isEmpty();
  }

  @Override
  public VirtualFile @NotNull [] getSelectedFiles() {
    VirtualFile file = LightEditService.getInstance().getSelectedFile();
    return file != null ? new VirtualFile[] {file} : VirtualFile.EMPTY_ARRAY;
  }

  @Override
  public VirtualFile getCurrentFile() {
    return LightEditService.getInstance().getSelectedFile();
  }

  @Override
  public VirtualFile getFile(@NotNull FileEditor editor) {
    VirtualFile file = editor.getFile();
    if (file != null) {
      return file;
    }
    FileEditorLocation location = editor.getCurrentLocation();
    if (location != null) {
      return location.getEditor().getFile();
    }
    LightEditorManagerImpl editorManager = (LightEditorManagerImpl)LightEditService.getInstance().getEditorManager();
    for (VirtualFile openFile : editorManager.getOpenFiles()) {
      LightEditorInfo editorInfo = editorManager.findOpen(openFile);
      if (editorInfo != null && editorInfo.getFileEditor().equals(editor)) {
        return openFile;
      }
    }
    return null;
  }

  @Override
  public boolean hasOpenFiles() {
    return !LightEditService.getInstance().getEditorManager().getOpenFiles().isEmpty();
  }

  @NotNull
  public EditorWithProviderComposite createEditorComposite(@NotNull LightEditorInfo editorInfo) {
    editorInfo.getFileEditor().putUserData(DUMB_AWARE, true); // Needed for composite not to postpone loading via DumbService.wrapGently()
    EditorWithProviderComposite composite = createComposite(
      editorInfo.getFile(),
      new FileEditor[]{editorInfo.getFileEditor()},
      new FileEditorProvider[]{((LightEditorInfoImpl)editorInfo).getProvider()});
    assert composite != null;
    return composite;
  }

  @Override
  protected @Nullable EditorWithProviderComposite getEditorComposite(@NotNull FileEditor editor) {
    return LightEditUtil.findEditorComposite(editor);
  }

  @Override
  public FileEditor @NotNull [] getAllEditors(@NotNull VirtualFile file) {
    return ContainerUtil.map(LightEditService.getInstance().getEditorManager()
                                             .getEditors(file), editorInfo -> editorInfo.getFileEditor())
                        .toArray(FileEditor.EMPTY_ARRAY);
  }
}


text:
SET gp_create_table_random_default_distribution=off;
-- end_ignore
CREATE SEQUENCE sync2_seq1  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;
CREATE SEQUENCE sync2_seq2  INCREMENT BY 2 MINVALUE 1 MAXVALUE  100  CACHE 100 CYCLE;

DROP SEQUENCE sync1_seq7;
DROP SEQUENCE ck_sync1_seq6;
DROP SEQUENCE ct_seq4;
DROP SEQUENCE resync_seq2;
DROP SEQUENCE sync2_seq1;

-- SEQUENCE USAGE

CREATE TABLE sync2_tbl1 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO sync2_tbl1 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE sync2_seq11 START 101 OWNED BY sync2_tbl1.col1;
INSERT INTO sync2_tbl1 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

CREATE TABLE sync2_tbl2 ( col1 int, col2 text, col3 int) DISTRIBUTED RANDOMLY;
INSERT INTO sync2_tbl2 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));
CREATE SEQUENCE sync2_seq22 START 101 OWNED BY sync2_tbl2.col1;
INSERT INTO sync2_tbl2 values (generate_series(1,100),repeat('seq_tbl_string',100),generate_series(1,100));

DROP SEQUENCE sync1_seq77;
DROP SEQUENCE ck_sync1_seq66;
DROP SEQUENCE ct_seq44;
DROP SEQUENCE resync_seq22;
DROP SEQUENCE sync2_seq11;

redpajama_set_name: RedPajamaGithub


text:
<resources>

    <!-- base -->

    <style name="FillContainer">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">fill_parent</item>
    </style>

    <style name="Background" parent="FillContainer">
        <item name="android:background">@color/background</item>
    </style>

    <style name="Container">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
    </style>

    <style name="VerticalContainer">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">fill_parent</item>
    </style>

    <style name="Block">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
    </style>

    <style name="InScrollContainer" parent="Block">
        <item name="android:focusable">true</item>
        <item name="android:focusableInTouchMode">true</item>
    </style>

    <style name="PaddedContainer" parent="Container">
        <item name="android:padding">@dimen/padding_medium</item>
    </style>

    <style name="SidePaddedContainer" parent="Container">
        <item name="android:paddingLeft">16dip</item>
        <item name="android:paddingRight">16dip</item>
    </style>

    <style name="Separator">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">1dp</item>
        <item name="android:background">@color/separator</item>
    </style>

    <style name="ShadowBottom">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">@dimen/shadow_height</item>
        <item name="android:background">@drawable/shadow_bottom</item>
    </style>

    <style name="ShadowTop">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">@dimen/shadow_height</item>
        <item name="android:background">@drawable/shadow_top</item>
    </style>

    <style name="EmptySpace">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">0px</item>
        <item name="android:layout_weight">1</item>
    </style>

    <!-- Text -->

    <style name="BaseText" parent="Block">
        <item name="android:textColor">@color/text</item>
    </style>

    <style name="TinyText" parent="BaseText">
        <item name="android:textSize">@dimen/text_tiny</item>
    </style>

    <style name="SmallText" parent="BaseText">
        <item name="android:textSize">@dimen/text_small</item>
    </style>

    <style name="Text" parent="BaseText">
        <item name="android:textSize">@dimen/text_medium</item>
    </style>

    <style name="LargeText" parent="BaseText">
        <item name="android:textSize">@dimen/text_large</item>
    </style>

    <style name="BaseTextInverse" parent="Block">
        <item name="android:textColor">@color/text_inverse</item>
    </style>

    <style name="TinyTextInverse" parent="BaseTextInverse">
        <item name="android:textSize">@dimen/text_tiny</item>
    </style>

    <style name="SmallTextInverse" parent="BaseTextInverse">
        <item name="android:textSize">@dimen/text_small</item>
    </style>

    <style name="TextInverse" parent="BaseTextInverse">
        <item name="android:textSize">@dimen/text_medium</item>
    </style>

    <style name="LargeTextInverse" parent="BaseTextInverse">
        <item name="android:textSize">@dimen/text_large</item>
    </style>

    <style name="SmallSubText" parent="TinyText">
        <item name="android:textColor">@color/subtext</item>
    </style>

    <style name="SubText" parent="SmallText">
        <item name="android:textColor">@color/subtext</item>
    </style>

    <style name="LargeSubText" parent="Text">
        <item name="android:textColor">@color/subtext</item>
    </style>

    <style name="TinyTitleText" parent="TinyText">
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@color/title</item>
    </style>

    <style name="SmallTitleText" parent="SmallText">
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@color/title</item>
    </style>

    <style name="TitleText" parent="Text">
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@color/title</item>
    </style>

    <style name="LargeTitleText" parent="LargeText">
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@color/title</item>
    </style>

</resources>


text:
pymatgen\.io\.abinit package
============================

Subpackages
-----------

.. toctree::

Submodules
----------

.. toctree::

   pymatgen.io.abinit.abiinspect
   pymatgen.io.abinit.abiobjects
   pymatgen.io.abinit.abitimer
   pymatgen.io.abinit.calculations
   pymatgen.io.abinit.db
   pymatgen.io.abinit.events
   pymatgen.io.abinit.flows
   pymatgen.io.abinit.helpers
   pymatgen.io.abinit.launcher
   pymatgen.io.abinit.netcdf
   pymatgen.io.abinit.nodes
   pymatgen.io.abinit.pseudos
   pymatgen.io.abinit.qadapters
   pymatgen.io.abinit.qjobs
   pymatgen.io.abinit.qutils
   pymatgen.io.abinit.scheduler_error_handlers
   pymatgen.io.abinit.scheduler_error_parsers
   pymatgen.io.abinit.tasks
   pymatgen.io.abinit.utils
   pymatgen.io.abinit.works
   pymatgen.io.abinit.wrappers

Module contents
---------------

.. automodule:: pymatgen.io.abinit
    :members:
    :undoc-members:
    :show-inheritance:


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

<title>UselessFileDetector</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.openqa.selenium.remote

Class UselessFileDetector

java.lang.Object

org.openqa.selenium.remote.UselessFileDetector

All Implemented Interfaces:

FileDetector

public class UselessFileDetector
extends java.lang.Object
implements FileDetector

A file detector that never finds anything.

Constructor Summary

Constructors

Constructor and Description

UselessFileDetector()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.io.File
getLocalFile(java.lang.CharSequence... keys)

Methods inherited from class java.lang.Object

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

Constructor Detail

UselessFileDetector

public UselessFileDetector()

Method Detail

getLocalFile

public java.io.File getLocalFile(java.lang.CharSequence... keys)

Specified by:

getLocalFile in interface FileDetector

Skip navigation links

Overview

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:
package CountryGamer_PEforPC.lib;

import java.util.HashMap;

public class Util {

}


text:
namespace ASP.NETAppWithNorthwind.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    public class CategoriesController : Controller
    {
        NORTHWNDEntities dbContext = new NORTHWNDEntities();

        public ActionResult All()
        {
            var categories = dbContext.Categories.ToList();

            return View(categories);
        }
    }
}


text:
// Separate Numbers with Commas in JavaScript **Pairing Challenge**

// I worked on this challenge with: Brian Wagner.

// Pseudocode

// Initial Solution
var addCommas = function(integer){
  var newArray = integer.toString().split("").reverse();
  for (var i = 3; i < newArray.length; i+= 4) {
  	newArray.splice(i, 0, ",");
  };
  newArray = newArray.reverse().join("");
  console.log(newArray);
};

addCommas(1234555556);

// Refactored Solution

// Your Own Tests (OPTIONAL)

/* Reflection
What was it like to approach the problem from the perspective of JavaScript? Did you approach the problem differently?

We didn't really approach the problem differently at all. You're trying to get to the same solution, so our intial steps and pseudocoding were similar to what I remember.

What did you learn about iterating over arrays in JavaScript?

Logically it's very similar to Ruby. I am already a little more partial to Java but that might just be on this level of difficulty. I like having everything in one line in the for loops.

What was different about solving this problem in JavaScript?

Learning the different JavaScript methods. It wasn't all that different in my opinion.

What built-in methods did you find to incorporate in your refactored solution?

We didn't have a refactored solution, as we used multiple built-in methods for our initial solution. The ones we did use have methods mirrored in Ruby as well, so it was just learning the syntax for the .split that was new for me. I also learned about using .split to find spaces or periods in strings and split there.

*/


text:
import requests

from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.github.provider import GitHubProvider
from allauth.socialaccount.providers.oauth2.views import (
    OAuth2Adapter,
    OAuth2CallbackView,
    OAuth2LoginView,
)

class GitHubOAuth2Adapter(OAuth2Adapter):
    provider_id = GitHubProvider.id
    settings = app_settings.PROVIDERS.get(provider_id, {})

    if 'GITHUB_URL' in settings:
        web_url = settings.get('GITHUB_URL').rstrip('/')
        api_url = '{0}/api/v3'.format(web_url)
    else:
        web_url = 'https://github.com'
        api_url = 'https://api.github.com'

    access_token_url = '{0}/login/oauth/access_token'.format(web_url)
    authorize_url = '{0}/login/oauth/authorize'.format(web_url)
    profile_url = '{0}/user'.format(api_url)
    emails_url = '{0}/user/emails'.format(api_url)

    def complete_login(self, request, app, token, **kwargs):
        params = {'access_token': token.token}
        resp = requests.get(self.profile_url, params=params)
        extra_data = resp.json()
        if app_settings.QUERY_EMAIL and not extra_data.get('email'):
            extra_data['email'] = self.get_email(token)
        return self.get_provider().sociallogin_from_response(
            request, extra_data
        )

    def get_email(self, token):
        email = None
        params = {'access_token': token.token}
        resp = requests.get(self.emails_url, params=params)
        emails = resp.json()
        if resp.status_code == 200 and emails:
            email = emails[0]
            primary_emails = [
                e for e in emails
                if not isinstance(e, dict) or e.get('primary')
            ]
            if primary_emails:
                email = primary_emails[0]
            if isinstance(email, dict):
                email = email.get('email', '')
        return email

oauth2_login = OAuth2LoginView.adapter_view(GitHubOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(GitHubOAuth2Adapter)


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

<title>CSSUtil.CSSIdConstants</title>
<meta name="date" content="2015-07-23">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jacpfx.rcp.util

Interface CSSUtil.CSSIdConstants

Enclosing class:

CSSUtil

public static interface CSSUtil.CSSIdConstants

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
ID_ERROR_DIMMER

static java.lang.String
ID_ROOT

static java.lang.String
ID_ROOT_PANE

static java.lang.String
ID_WINDOW_CLOSE

static java.lang.String
ID_WINDOW_MAX

static java.lang.String
ID_WINDOW_MIN

Field Detail

ID_WINDOW_MIN

static final java.lang.String ID_WINDOW_MIN

See Also:

Constant Field Values

ID_WINDOW_MAX

static final java.lang.String ID_WINDOW_MAX

See Also:

Constant Field Values

ID_WINDOW_CLOSE

static final java.lang.String ID_WINDOW_CLOSE

See Also:

Constant Field Values

ID_ROOT

static final java.lang.String ID_ROOT

See Also:

Constant Field Values

ID_ROOT_PANE

static final java.lang.String ID_ROOT_PANE

See Also:

Constant Field Values

ID_ERROR_DIMMER

static final java.lang.String ID_ERROR_DIMMER

See Also:

Constant Field Values

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package ee.cone.c4actor_logback_impl

trait BasicLoggingAppBase


text:
This Windows application was inspired by the work of Andrew, seen [here](http://blog.andrewsomething.com/2014/04/25/digitalocean-indicator-release/)!

![ui](http://i.imgur.com/TjnRJVc.png)

![notification1](http://i.imgur.com/G9ew15v.png)
![notification2](http://i.imgur.com/wZSXdqP.png)

## Install

Download the latest release from the GitHub releases page [here](https://github.com/vevix/DigitalOcean.Indicator/releases).

## License

The MIT License (MIT)

Copyright (c) 2014 Thomas McNiven (vevix)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
/*
  ==============================================================================

    TestTableComponent.cpp
    Created: 19 May 2016 6:12:20pm
    Author:  Jonathan Thorpe

  ==============================================================================
*/

#include "TestTableComponent.h"

/*
 ==============================================================================

 TestTableComponent.cpp
 Created: 12 May 2016 4:38:11pm
 Author:  Jonathan Thorpe

 ==============================================================================
 */

#include "../JuceLibraryCode/JuceHeader.h"

#include "CommonComponent.h"
#include "RelayComponent.h"
#include "TestTableComponent.h"

//==============================================================================
TestTableComponent::TestTableComponent(RelayAudioProcessor& _processor) : processor(_processor)
{
    // In your constructor, you should add any child components, and
    // initialise any special settings that your component needs.

    // Create our table component and add it to this component..
    addAndMakeVisible (table);

    table.setModel (this);

    // give it a border
    table.setColour (ListBox::outlineColourId, Colours::grey);
    table.setOutlineThickness (1);

    TableHeaderComponent::ColumnPropertyFlags flags = (TableHeaderComponent::ColumnPropertyFlags)
    (TableHeaderComponent::ColumnPropertyFlags::visible |
     TableHeaderComponent::ColumnPropertyFlags::resizable);

    TableHeaderComponent::ColumnPropertyFlags sliderFlags = (TableHeaderComponent::ColumnPropertyFlags)
    (TableHeaderComponent::ColumnPropertyFlags::visible);

    table.getHeader().addColumn ("Index", indexColumnId, 60, 50, 400, flags);
    table.getHeader().addColumn ("Name", nameColumnId, 200, 50, 400, flags);
    table.getHeader().addColumn ("Value", valueColumnId, 200, 50, 400, sliderFlags);

    table.setRowHeight(25);

}

TestTableComponent::~TestTableComponent()
{
}

void TestTableComponent::paint (Graphics& g)
{
    /* This demo code just fills the component's background and
     draws some placeholder text to get you started.

     You should replace everything in this method with your own
     drawing code..
     */

    g.fillAll (Colours::white);   // clear the background

    g.setColour (Colours::grey);
    g.drawRect (getLocalBounds(), 1);   // draw an outline around the component

    g.setColour (Colours::lightblue);
    g.setFont(14.0f);

    // draw some placeholder text
    // g.drawText ("TestTableComponent", getLocalBounds(), Justification::centred, true);
}

void TestTableComponent::resized()
{
    // This method is where you should set the bounds of any child
    // components that your component contains...

    int margin = 4;

    table.setBounds( getBounds().withX(0).withY(0).withTrimmedBottom(0).reduced(margin) );
}

void TestTableComponent::update()
{
    table.updateContent();
}

// ======= TableListBoxModel =========

int TestTableComponent::getNumRows()
{
    return processor.getParameters().size();
}

void TestTableComponent::paintRowBackground (Graphics& g, int rowNumber, int width, int height, bool rowIsSelected)
{
    if (rowIsSelected) g.fillAll (Colours::lightblue);
    else if (rowNumber % 2) g.fillAll (Colour (0xffeeeeee));
}

// This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom components.
void TestTableComponent::paintCell (Graphics& g, int rowNumber, int columnId, int width, int height, bool rowIsSelected)
{
    g.setColour (Colours::black);
    g.setFont (font);

    // we need custom components to actually be able to edit the cells which is a bit shitty but anyway...
    // so only the connected indicator can be drawn using a graphics context

    int x = 2;
    int y = 0;
    int w = width - 4;
    int h = height;

    AudioProcessorParameter* parameter = processor.getParameters()[rowNumber];

    if (columnId == indexColumnId)
    {
        g.setColour (Colours::green.withAlpha (0.5f));
        g.drawText ( String(parameter->getParameterIndex()), x, y, w, h, Justification::centredLeft, true);
    }

    else if (columnId == indexColumnId)
    {
        g.setColour (Colours::green.withAlpha (0.5f));
        g.drawText ( parameter->getName(20), x, y, w, h, Justification::centredLeft, true);
    }

}

// This is overloaded from TableListBoxModel, and must update any custom components that we're using
Component* TestTableComponent::refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected, Component* existingComponentToUpdate)
{

    if (columnId == valueColumnId) // For the ratings column, we return the custom combobox component
    {
        AudioProcessorParameter* parameter = processor.getParameters()[rowNumber];

        DemoParameterSlider* component = static_cast<DemoParameterSlider*> (existingComponentToUpdate);

        // If an existing component is being passed-in for updating, we'll re-use it, but
        // if not, we'll have to create one.
        if (component == nullptr) component = new DemoParameterSlider(*parameter);

        return component;
    }

    return nullptr;

}

int TestTableComponent::getColumnAutoSizeWidth (int columnId)
{
    return 32;
}


text:
case $2 in
    PRE-INSTALL)

        ;;
    POST-INSTALL)
	echo Importing service ...
	svccfg import /opt/local/fifo-grafana/manifest.xml
        if [ ! -f /opt/local/fifo-grafana/conf/custom.ini ]; then
            cp /opt/local/fifo-grafana/conf/custom.ini.example /opt/local/fifo-grafana/conf/custom.ini
        fi
        ;;
esac


text:
package com.facebook.litho.widget;

import com.facebook.litho.Column;
import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.Size;
import com.facebook.litho.annotations.LayoutSpec;
import com.facebook.litho.annotations.OnCreateLayout;
import com.facebook.litho.annotations.Prop;

@LayoutSpec
class ComponentCachingSpec {

  @OnCreateLayout
  static Component onCreateLayout(
      final ComponentContext c,
      final @Prop Component component,
      final @Prop int widthSpec,
      final @Prop int heightSpec) {
    component.measure(c, widthSpec, heightSpec, new Size());
    return Column.create(c).child(component).build();
  }
}


text:
local A = aura_env
-- local R = WeakAuras.regions[A.id].region
-- local S = WeakAurasSaved.displays[A.id]
local playerGUID = UnitGUID("player")

----- Set options here -----
local refreshRate = 20

----- Utility -----
local now
local refreshInterval = 1 / refreshRate
local lastRefresh     = -refreshInterval - 1
local customText
local shouldShow      = true
local isOptionsOpen   = WeakAuras.IsOptionsOpen
local playerGUID      = UnitGUID("player")

----- Main logic -----
local rbCounts = {}
local rbMults = {
    [0] = "1.00",
    [1] = "1.25",
    [2] = "1.56",
    [3] = "1.95",
    [4] = "2.44",
    [5] = "3.05",
    [6] = "3.81",
    [7] = "4.77",
}

local function onCombatEvent(_, subEvent, _, sourceGUID, sourceName, sourceFlags, _,
    destGUID, destName, destFlags, _, spellID, spellName, _, ...)

    if spellID == 17962 then
        if subEvent == "SPELL_DAMAGE" then
            rbCounts[destGUID] = (rbCounts[destGUID] or 0) + 1
        end
    elseif spellID == 157736 then
        if strsub(subEvent, 1, 11) == "SPELL_AURA_" then
            rbCounts[destGUID] = (subEvent ~= "SPELL_AURA_REMOVED") and 0 or nil
        end
    end
end

local function onRefresh()
    if UnitDebuff("target", "Immolate", nil, "PLAYER") then
        customText = rbMults[rbCounts[UnitGUID("target")]] or "???"
    else
        customText = isOptionsOpen() and "1.00" or ""
    end
end

local function doCustomText()
    now = GetTime()
    if now - lastRefresh >= refreshInterval then
        onRefresh()
        lastRefresh = now
    end
    return customText
end
A.doCustomText = doCustomText

local triggerDispatch = {
    ["COMBAT_LOG_EVENT_UNFILTERED"] = onCombatEvent,
}
local function doTrigger(event, ...)
    now = GetTime()
    triggerDispatch[event](...)
    return shouldShow
end
A.doTrigger = doTrigger


text:
using Microsoft.AspNetCore.Authorization;
using MyWorkSpace.Domain;
using MyWorkSpace.Domain.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyWorkSpace.MPA.AuthPolicy
{
    public class BaseAuthRequirmentHandler : AuthorizationHandler<BaseAuthRequirment>
    {
        private readonly LoginService _loginService;

        public BaseAuthRequirmentHandler(LoginService loginService)
        {
            _loginService = loginService;
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, BaseAuthRequirment requirement)
        {
            if (context.Resource is Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext mvcContext)
            {
                string identyKey;
                if (mvcContext.HttpContext.Request.Cookies.TryGetValue(Consts.COOKIE_LOGIN_IDENTITY, out identyKey))
                {
                    var loginInfo = _loginService.GetLoginInfo(identyKey);
                    if (loginInfo != null)
                        context.Succeed(requirement);
                }
            }

            return Task.CompletedTask;
        }
    }
}


text:
var Buffer = require('buffer').Buffer;

function readData(data, current) {
  if(!current.riff) {
    var tag = data.slice(0, 4).toString();
    var size = data.readUInt32LE(4);
    var type = data.slice(8, 12).toString();
    current.riff = {
      tag: tag,
      size: size,
      type: type,
      raw: data.slice(0, 12)
    };
    data = data.slice(12);
  }
  if(!current.format) {
    var tag = data.slice(0, 4).toString();
    var size = data.readUInt32LE(4);
    var wFormatTag = data.readUInt16LE(8);
    var wChannels = data.readUInt16LE(10);
    var dwSamplesPerSec = data.readUInt32LE(12);
    var dwAvgBytesPerSec = data.readUInt32LE(16);
    var wBlockAlign = data.readUInt16LE(20);
    var wBitsPerSample = data.readUInt16LE(22);
    current.format = {
      tag: tag,
      size: size,
      wFormatTag: wFormatTag,
      wChannels: 1,
      dwSamplesPerSec: dwSamplesPerSec,
      dwAvgBytesPerSec: dwAvgBytesPerSec/wChannels,
      wBlockAlign: wBlockAlign/wChannels,
      wBitsPerSample: wBitsPerSample,
      raw: data.slice(0, 8 + size)
    };
    data = data.slice(8 + size);
  }
  if(!current.buf) {
    var id = data.slice(0, 4).toString();
    var dataSize = data.readUInt32LE(4);
    current.buf = new Buffer(dataSize/2);//monoral
    data = data.slice(8);
  }
  var monoral = toMonoral(data);
  monoral.copy(current.buf, current.cursor);
  current.cursor += monoral.length;
}
function toMonoral(data) {
  var monoral = new Buffer(data.length/2);
  for(i = 0; i < data.length; i += 4) {
    monoral[i/2] = data[i];
    monoral[i/2+1] = data[i+1];
  }
  return monoral;
}
function cuttingPoints(data, lengthThreshold, seekStart, seekEnd) {
  seekStart = seekStart || 0;
  seekEnd = seekEnd || data.length;
  var points = [];
  var threshold = 0.01;
  var start = seekStart;
  var silentLength = 0;

  for(i = seekStart; i < seekEnd; i++) {
    var l = data[i];
    if(Math.abs(l) < threshold) {
      silentLength++;
    } else {
      if(silentLength > lengthThreshold) {
        points.push([start, i-1]);
        start = i-1;
      }
      silentLength = 0;
    }
  }
  points.push([start, data.length - 1]);
  return points;
}
function createWavFileBuffer(riff, format, buf) {
  var dataLength = buf.length;
  var riffDataSize = 4 + format.raw.length + 8 + dataLength;
  var riffHeader = new Buffer(12);
  riff.raw.copy(riffHeader);
  riffHeader.writeUInt32LE(riffDataSize, 4);

  var formatChunk = new Buffer(format.raw.length);
  format.raw.copy(formatChunk);
  formatChunk.writeUInt16LE(format.wChannels, 10);
  formatChunk.writeUInt32LE(format.dwAvgBytesPerSec, 16);
  formatChunk.writeUInt16LE(format.wBlockAlign, 20);

  var dataChunk = new Buffer(dataLength);
  dataChunk.write('data', 0, 4, 'ascii');
  dataChunk.writeUInt32LE(dataLength, 4);
  buf.copy(dataChunk, 8);

  var all = Buffer.concat([riffHeader, formatChunk, dataChunk]);
  return all;
}
module.exports = {
  createWavFileBuffer: createWavFileBuffer,
  cuttingPoints: cuttingPoints
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
<title type="text">FOSEC</title>
<generator uri="https://github.com/mojombo/jekyll">Jekyll</generator>
<link rel="self" type="application/atom+xml" href="http://127.0.0.1:4000/feed.xml" />
<link rel="alternate" type="text/html" href="http://127.0.0.1:4000" />
<updated>2016-10-26T19:04:50+07:00</updated>
<id>http://127.0.0.1:4000/</id>
<author>
  <name>FOSEC</name>
  <uri>http://127.0.0.1:4000/</uri>
  <email>fosec.vn@gmail.com</email>
</author>

<entry>
  <title type="html"><![CDATA[What is CTF]]></title>
 <link rel="alternate" type="text/html" href="http://127.0.0.1:4000/ctf/what_is_ctf/" />
  <id>http://127.0.0.1:4000/ctf/what_is_ctf</id>
  <updated>2016-10-26T00:00:00-00:00</updated>
  <published>2016-10-26T00:00:00+07:00</published>

  <author>
    <name>FOSEC</name>
    <uri>http://127.0.0.1:4000</uri>
    <email>fosec.vn@gmail.com</email>
  </author>
  <content type="html">

Capture the Flag (CTF) is a special kind of information security competitions. There are three common types of CTFs: Jeopardy, Attack-Defence and mixed.

Jeopardy-style CTFs has a couple of questions (tasks) in range of categories. For example, Web, Forensic, Crypto, Binary or something else. Team can gain some points for every solved task. More points for more complicated tasks usually. The next task in chain can be opened only after some team solve previous task. Then the game time is over sum of points shows you a CTF winer. Famous example of such CTF is Defcon CTF quals.

Well, attack-defence is another interesting kind of competitions. Here every team has own network(or only one host) with vulnarable services. Your team has time for patching your services and developing exploits usually. So, then organizers connects participants of competition and the wargame starts! You should protect own services for defence points and hack opponents for attack points. Historically this is a first type of CTFs, everybody knows about DEF CON CTF - something like a World Cup of all other competitions.

Mixed competitions may vary possible formats. It may be something like wargame with special time for task-based elements (like UCSB iCTF).

CTF games often touch on many other aspects of information security: cryptography, stego, binary analysis, reverse engeneering, mobile security and others. Good teams generally have strong skills and experience in all these issues.

ctftime[dot]org/ctf-wtf/

What is CTF was originally published by FOSEC at FOSEC on October 26, 2016.

  </content>
</entry>

<entry>
  <title type="html"><![CDATA[Hacking Firmware from Mobile Phone Hacking Company Leaked Online]]></title>
 <link rel="alternate" type="text/html" href="http://127.0.0.1:4000/news/phone-hacking-software/" />
  <id>http://127.0.0.1:4000/news/phone-hacking-software</id>
  <updated>2016-10-26T00:00:00-00:00</updated>
  <published>2016-10-26T00:00:00+07:00</published>

  <author>
    <name>FOSEC</name>
    <uri>http://127.0.0.1:4000</uri>
    <email>fosec.vn@gmail.com</email>
  </author>
  <content type="html">

The Israeli firm Cellebrite, which provides digital forensics tools and software to help law enforcement access mobile phones in investigations, has had its firmware and software leaked online.

Yes, you heard that right. Cellebrite's most sensitive in-house capabilities have been made public by one of its products' resellers, who is now distributing copies of Cellebrite's firmware and software for anyone to download.

The apparent reseller is McSira Professional Solutions, which hosts software for various versions of Cellebrite's Universal Forensic Extraction Device (UFED).

UFED is one of the company's key products that help investigators bypass the security mechanisms of mobile phones, especially iPhones, and extract all data and passwords from them.

For the Cellebrite's hand on iOS devices, you can watch the 2015 YouTube video (below), which demonstrates one of the company's products that unlocked the iPhone device in few hours.

Download Links to Cellebrite's Key Forensic Product

McSira is allowing anyone to download the firmware for the UFED Touch and UFED 4PC (PC version). The company is also hosting copies of UFED packages for different mobile phone brands, including Apple, Samsung, Blackberry, Nokia, and LG.

Besides this, McSira is also hosting copies of Cellebrite forensic software, such as the UFED Phone Detective, UFED Cloud Analyzer and Link Analyzer, which allows investigators to analyze seized data further.

McSira is likely offering these download links for firmware and software files so that its customers – which, according to its site, are "police, military and security agencies in the E.U. and other parts of the world" – can conveniently update their hardware to the latest version.
However, the company opened doors for researchers, hackers, and its competitors to download these leaked files, reverse-engineer them, and figure out how Cellebrite's tools break into mobile phones.

Researcher Started Examining leaked Software and Firmware

According to Joseph Cox, freelance security journalist for Motherboard, an unnamed researcher has already started examining the leaked files to disclose the kind of exploits Cellebrite uses to bypass even strong security mechanisms on mobile phones, as well as weaknesses in the implementation of affected phones that could be fixed.

Another researcher Pedro Vilaça from SentinelOne said he already cracked some of the Cellebrite software and ran it against an old iPad, though he said he needed to explore the leaked files more to understand the capability of those software better.

"Doesn't seem to be trying to exploit things but just data extraction," Vilaça told Motherboard. "For example, I'd to pair my device with iTunes for the logical extraction feature to work."

Mike Reilly, a PR firm representative that works with Cellebrite, said the McSira website's links "don't allow access to any of the solutions without a license key," meaning that downloaders need a key (code) given by Cellebrite or its reseller to run those software.

At the time of writing, McSira is hosting these files, but it is not clear how long the files will be hosted on its website.

McSira and Cellebrite have yet to comment on the matter.

thehackernews[dot]com/2016/10/phone-hacking-software.html

Hacking Firmware from Mobile Phone Hacking Company Leaked Online was originally published by FOSEC at FOSEC on October 26, 2016.

  </content>
</entry>

<entry>
  <title type="html"><![CDATA[Massive DDoS Attack Against Dyn DNS Service Knocks Popular Sites Offline]]></title>
 <link rel="alternate" type="text/html" href="http://127.0.0.1:4000/news/dyn-dns-ddos/" />
  <id>http://127.0.0.1:4000/news/dyn-dns-ddos</id>
  <updated>2016-10-26T00:00:00-00:00</updated>
  <published>2016-10-26T00:00:00+07:00</published>

  <author>
    <name>FOSEC</name>
    <uri>http://127.0.0.1:4000</uri>
    <email>fosec.vn@gmail.com</email>
  </author>
  <content type="html">

Cyber attacks are getting evil and worst nightmare for companies day-by-day, and the Distributed Denial of Service (DDoS) attack is one such attacks that cause a massive damage to any service.

Recently, the Internet witnessed a record-breaking largest DDoS attack of over 1 Tbps against France-based hosting provider OVH, and now the latest victim of the attack is none other than Dyn DNS provider.

A sudden outage of popular sites and services, including Twitter, SoundCloud, Spotify, and Shopify, for many users, is causing uproar online. It's because of a DDoS attack against the popular Domain Name System (DNS) service provider Dyn, according to a post on Ycombinator.

DNS act as the authoritative reference for mapping domain names to IP addresses. In other words, DNS is simply an Internet's phone book that resolves human-readable web addresses, like thehackernews.com, against IP addresses.

Dyn DNS is used by many websites and services as their upstream DNS provider, including Twitter, Spotify, SaneBox, Reddit, Box, Github, Zoho CRM, PayPal, Airbnb, Freshbooks, Wired.com, Pinterest, Heroku and Vox Media properties.

All of these sites and services are reportedly experiencing outages and downtime, either completely or partially.

Here's an internet outage map from Level3:

thehackernews[dot]com/2016/10/dyn-dns-ddos.html

Massive DDoS Attack Against Dyn DNS Service Knocks Popular Sites Offline was originally published by FOSEC at FOSEC on October 26, 2016.

  </content>
</entry>

<entry>
  <title type="html"><![CDATA[Best Password Manager — For Windows, Linux, Mac, Android, iOS and Enterprise]]></title>
 <link rel="alternate" type="text/html" href="http://127.0.0.1:4000/news/best-password-manager/" />
  <id>http://127.0.0.1:4000/news/best-password-manager</id>
  <updated>2016-10-26T00:00:00-00:00</updated>
  <published>2016-10-26T00:00:00+07:00</published>

  <author>
    <name>FOSEC</name>
    <uri>http://127.0.0.1:4000</uri>
    <email>fosec.vn@gmail.com</email>
  </author>
  <content type="html">

When it comes to safeguarding your Internet security, installing an antivirus software or running a Secure Linux OS on your system does not mean you are safe enough from all kinds of cyber-threats.

Today majority of Internet users are vulnerable to cyber attacks, not because they aren't using any best antivirus software or other security measures, but because they are using weak passwords to secure their online accounts.

Passwords are your last lines of defense against online threats. Just look back to some recent data breaches and cyber attacks, including high-profile data breach at OPM (United States Office of Personnel Management) and the extra-marital affair site Ashley Madison, that led to the exposure of hundreds of millions of records online.

Although you can not control data breaches, it is still important to create strong passwords that can withstand dictionary and brute-force attacks.

You see, the longer and more complex your password is, the much harder it is crack.

How to Stay Secure Online?

Security researchers have always advised online users to create long, complex and different passwords for their various online accounts. So, if one site is breached, your other accounts on other websites are secure enough from being hacked.

Ideally, your strong password should be at least 16 characters long, should contain a combination of digits, symbols, uppercase letters and lowercase letters and most importantly the most secure password is one you don't even know.

The password should be free of repetition and not contain any dictionary word, pronoun, your username or ID, and any other predefined letter or number sequences.

I know this is a real pain to memorize such complex password strings and unless we are human supercomputers, remembering different passwords for several online accounts is not an easy task.

The issue is that today people subscribe to a lot of online sites and services, and it's usually hard to create and remember different passwords for every single account.

But, Luckily to make this whole process easy, there's a growing market for password managers for PCs and phones that can significantly reduce your password memorizing problem, along with the cure for your bad habit of setting weak passwords.

What is Password Manager?

…

thehackernews[dot]com/2016/07/best-password-manager.html

Best Password Manager — For Windows, Linux, Mac, Android, iOS and Enterprise was originally published by FOSEC at FOSEC on October 26, 2016.

  </content>
</entry>

</feed>


text:
const { Event } = require("klasa");

/*
 * Event watches for deleted starboard messages and updates the data as not to cause
 * Margarine to crash if another reaction was added to the original message.
 */
module.exports = class extends Event {
    constructor(...args) {
        super(...args, {
            name: "starboardWatch",
            enabled: true,
            event: "messageDelete"
        });
    }

    async run(message) {
        //Message is not in a guild, do nothing.
        if (message.guild === undefined) { return; }

        let sbConfig = message.guild.settings.starboard;
        if (sbConfig.sbCache.includes(message.id)) {
            var index = sbConfig.sbCache.indexOf(message.id);
            var msgLink = sbConfig.msgCache[index];

            message.guild.settings.update("starboard.msgCache", msgLink, { action: "remove" }).then(() => {
                message.guild.settings.update("starboard.sbCache", message.id, { action: "remove" });
            });
        }
    }
};


text:
namespace ospray {

void registerAllTextures()
{
  Texture::registerType<Texture2D>("texture2d");
  Texture::registerType<TextureVolume>("volume");
}

} // namespace ospray


text:
"""ONNX: Open Neural Network Exchange frontend for Relay."""
from __future__ import absolute_import as _abs

import logging
import numpy as np
import tvm
from ... import nd as _nd
from .. import analysis
from .. import transform as _transform
from .. import expr as _expr
from .. import module as _module
from .. import op as _op
from .common import AttrCvt, Renamer
from .common import get_relay_op, new_var, infer_shape, infer_channels, get_name

__all__ = ['from_onnx']

def dimension_picker(prefix, surfix=''):
    def _impl(attr):
        kernel = attr['kernel_shape']
        if len(kernel) == 2:
            return prefix + '2d' + surfix
        msg = 'Only 2D kernels are supported for operator {}.'
        op_name = prefix + '2d'
        raise tvm.error.OpAttributeInvalid(msg.format(op_name))

    return _impl

def revert_caffe2_pad(pads):
    """Caffe2 requires two times the normal padding."""
    if len(pads) == 4:
        pads = pads[:2]
    elif len(pads) == 2:
        pass
    else:
        raise tvm.error.OpAttributeInvalid(
            'Number of pads must be either 2 or 4.')
    return pads

def onnx_storage_order2layout(storage_order):
    """converter of onnx storage order parameter to tvm storage order format"""
    if storage_order not in (0, 1):
        raise tvm.error.OpAttributeInvalid('Mode of storage_order must be either 0 or 1')

    return 'NCHW' if sotrage_order == 0 else 'NHWC'

def dimension_constraint():
    def _dim_check(attrs):
        if len(attrs['kernel_shape']) == 2:
            return True
        return False

    return _dim_check, "Only 2d kernel supported."

class OnnxOpConverter(object):
    """ A helper class for holding onnx op converters.
    """

    @classmethod
    def get_converter(cls, opset):
        """ Get converter matches given opset.

        Parameters
        ----------
        opset: int
            opset from model.

        Returns
        -------
        converter, which should be `_impl_vx`. Number x is the biggest
            number smaller than or equal to opset belongs to all support versions.
        """
        versions = [
            int(d.replace('_impl_v', '')) for d in dir(cls) if '_impl_v' in d
        ]
        versions = sorted(versions + [opset])
        version = versions[
            max([i for i, v in enumerate(versions) if v == opset]) - 1]
        if hasattr(cls, '_impl_v{}'.format(version)):
            return getattr(cls, '_impl_v{}'.format(version))
        raise NotImplementedError(
            'opset version {} of {} not implemented'.format(
                version, cls.__name__))

class Elemwise(OnnxOpConverter):
    """ A helper class for elemwise op converters.
    """
    name = ''

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        assert len(inputs) == 2, "Math op take 2 inputs, {} given".format(
            len(inputs))
        op_name = cls.name
        conv_ops = ["conv2d", "conv2d_transpose"]
        if attr.get('broadcast', 0) and any(x in str(inputs[0]) for x in conv_ops):
            # TODO(zhreshold): remove hard coded infershape
            axis = int(attr.get('axis', 0))
            inputs[1] = _op.expand_dims(inputs[1], axis=axis, num_newaxis=2)
        return get_relay_op(op_name)(*inputs)

class Pool(OnnxOpConverter):
    """ A helper class for pool op converters.
    """
    name = ''

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        return AttrCvt(
            op_name=dimension_picker(cls.name),
            transforms={
                'kernel_shape': 'pool_size',
                'pads': ('padding', (0, 0), revert_caffe2_pad)
            },
            # very weird attributes here in onnx, force check
            ignores=['dilations', 'auto_pad'],
            # TODO(zhreshold): make sure ceil_mode in onnx, and layout?
            extras={'ceil_mode': False},
            custom_check=dimension_constraint())(inputs, attr, params)

class Absolute(OnnxOpConverter):
    """ Operator converter for Absolute.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        return _op.nn.relu(inputs[0]) + _op.nn.relu(_op.negative(inputs[0]))

class Add(Elemwise):
    """ Operator converter for Add.
    """
    name = 'add'

class AveragePool(Pool):
    """ Operator converter for AveragePool.
    """
    name = 'avg_pool'

class BatchNorm(OnnxOpConverter):
    """ Operator converter for BatchNorm.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        # TODO(zhreshold): 'spatial' is not properly handled here.
        out = AttrCvt(
            op_name='batch_norm',
            ignores=['spatial', 'is_test', 'consumed_inputs', 'momentum'])(inputs, attr,
                                                                           params)
        return out[0]

class Conv(OnnxOpConverter):
    """ Operator converter for Conv.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        out = AttrCvt(op_name=dimension_picker('conv'),
                      transforms={
                          'kernel_shape': 'kernel_size',
                          'dilations': ('dilation', (0, 0)),
                          'pads': ('padding', (0, 0), revert_caffe2_pad),
                          'group': ('groups', 1)},
                      ignores=['auto_pad'],
                      custom_check=dimension_constraint())(inputs[:2], attr, params)
        use_bias = len(inputs) == 3
        if use_bias:
            out = _op.nn.bias_add(out, inputs[2])
        return out

class ConvTranspose(OnnxOpConverter):
    """ Operator converter for ConvTranspose.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        # get number of channels
        channels = infer_channels(inputs[1], True)
        attr['channels'] = channels
        groups = attr.pop('group')
        attr['groups'] = groups
        out = AttrCvt(
            op_name=dimension_picker('conv', '_transpose'),
            transforms={
                'kernel_shape': 'kernel_size',
                'dilations': ('dilation', (0, 0)),
                'pads': ('padding', (0, 0), revert_caffe2_pad)
            },
            disables=['output_shape'],
            custom_check=dimension_constraint())(inputs[:2], attr, params)
        use_bias = len(inputs) == 3
        if use_bias:
            out = _op.nn.bias_add(out, inputs[2])
        return out

class Div(Elemwise):
    name = 'divide'

class Elu(OnnxOpConverter):
    """ Operator converter for Elu.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        alpha = float(attr.get('alpha', 1.0))
        return _expr.const(-alpha) * _op.nn.relu(_expr.const(1.) - _op.exp(inputs[0])) + \
                                     _op.nn.relu(inputs[0])

class Gemm(OnnxOpConverter):
    """ Operator converter for Gemm.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        assert len(inputs) == 3, "Gemm op take 3 inputs, {} given".format(
            len(inputs))
        # Y = alpha * A * B + beta * C
        alpha = float(attr.get('alpha', 1.0))
        beta = float(attr.get('beta', 1.0))
        transA = int(attr.get('transA', 0))
        transB = int(attr.get('transB', 0))
        # get number of channels
        channels = infer_channels(inputs[1], not transB)
        if transA:
            inputs[0] = _op.transpose(inputs[0], axes=(1, 0))
        if not transB:
            inputs[1] = _op.transpose(inputs[1], axes=(1, 0))
        inputs[0] = _op.nn.batch_flatten(inputs[0])
        out = _op.nn.dense(_expr.const(alpha) * inputs[0],
                           inputs[1], units=channels)
        return _op.nn.bias_add(out, _expr.const(beta) * inputs[2])

class MatMul(OnnxOpConverter):
    """ Operator converter for MatMul.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        assert len(inputs) == 2, "MatMul op take 2 inputs, {} given".format(len(inputs))
        input_1_t = _op.transpose(inputs[1], axes=(1, 0))
        return _op.nn.dense(inputs[0], input_1_t)

class MaxPool(Pool):
    """ Operator converter for MaxPool
    """
    name = 'max_pool'

    @classmethod
    def _impl_v8(cls, inputs, attr, params):
        return AttrCvt(
            op_name=dimension_picker(cls.name),
            transforms={
                'kernel_shape': 'pool_size',
                'pads': ('padding', (0, 0), revert_caffe2_pad),
                'storage_order': ('layout', 'NCHW', onnx_storage_order2layout),
            },
            # very weird attributes here in onnx, force check
            ignores=['dilations', 'auto_pad'],
            # TODO(higumachan): make sure ceil_mode in onnx, and layout?
            extras={'ceil_mode': False},
            custom_check=dimension_constraint())(inputs, attr, params)

    @classmethod
    def _impl_v10(cls, inputs, attr, params):
        return AttrCvt(
            op_name=dimension_picker(cls.name),
            transforms={
                'kernel_shape': 'pool_size',
                'pads': ('padding', (0, 0), revert_caffe2_pad),
                'storage_order': ('layout', 'NCHW', onnx_storage_order2layout),
                'ceil_mode': 'ceil_mode'
            },
            # very weird attributes here in onnx, force check
            ignores=['dilations', 'auto_pad'],
            custom_check=dimension_constraint())(inputs, attr, params)

class Mul(Elemwise):
    name = 'multiply'

class Pad(OnnxOpConverter):
    """ Operator converter for Pad.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        pad_width = []
        pads = attr.pop('paddings')
        dims = int(len(pads) / 2)
        for i in range(dims):
            pad_width.append((pads[i], pads[i+dims]))
        attr['pad_width'] = pad_width

        return AttrCvt(
            _op.nn.pad,
            transforms={
                'value': 'pad_value',
            },
            ignores=['mode'],
            custom_check=(lambda attrs: attrs.get('mode', 'constant').decode("utf-8") == 'constant',
                          'split mode != constant'))(inputs, attr, params)

    @classmethod
    def _impl_v2(cls, inputs, attr, params):
        pad_width = []
        pads = attr.pop('pads')
        dims = int(len(pads) / 2)
        for i in range(dims):
            pad_width.append((pads[i], pads[i+dims]))
        attr['pad_width'] = pad_width

        return AttrCvt(
            'pad',
            transforms={
                'value': 'pad_value',
            },
            ignores=['mode'],
            custom_check=(lambda attrs: attrs.get('mode', 'constant').decode("utf-8") == 'constant',
                          'split mode != constant'))(inputs, attr, params)

class ParametricSoftPlus(OnnxOpConverter):
    """ Operator converter for ParametricSoftPlus.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        alpha = _expr.const(float(attr.get('alpha', 1.0)))
        beta = _expr.const(float(attr.get('beta', 1.0)))
        return _op.log(_op.exp(beta * inputs[0]) + _expr.const(1.)) * alpha

class Prelu(OnnxOpConverter):
    """ Operator converter for Prelu.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        assert len(inputs) == 2, "Prelu need 2 inputs, {} given".format(len(inputs))
        return _op.nn.prelu(inputs[0], inputs[1])

class Reciprocal(OnnxOpConverter):
    """ Operator converter for Reciprocal.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        return _expr.const(1.0) / inputs[0]

class Flatten(OnnxOpConverter):
    """ Operator converter for Flatten.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        axis = attr.get('axis', 1)
        if axis == 1:
            out = _op.nn.batch_flatten(inputs[0])
        else:
            newshape = [0] * (axis + 1)
            newshape[axis] = -1
            out = _op.reshape(inputs[0], list(newshape))
        return out

class Reshape(OnnxOpConverter):
    """ Operator converter for Reshape.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        if 'shape' in attr:
            return _op.reshape(inputs[0], attr['shape'])

        if get_name(inputs[1]) in params:
            shape = tuple(params[inputs[1].name_hint].asnumpy())
            out = _op.reshape(inputs[0], shape)
        else:
            data, shape = inputs
            logging.warning("Constant evaluating Reshape's shape argument, may reduce performance")
            shape_params = analysis.free_vars(shape)
            func = _expr.Function(shape_params, shape)
            mod = _module.Module.from_expr(func)
            seq = _transform.Sequential([_transform.InferType(),
                                         _transform.FoldConstant(),
                                         _transform.FuseOps(0),
                                         _transform.InferType()])
            with tvm.relay.PassContext(opt_level=2):
                mod = seq(mod)
            with tvm.relay.build_config(opt_level=0):
                ex = tvm.relay.create_executor("debug", mod=mod)
                inputs = []
                for sp in shape_params:
                    if not sp.name_hint in params:
                        sh = [int(i) for i in sp.type_annotation.shape]
                        inputs.append(
                            tvm.nd.array(np.random.rand(*sh).astype('float32')))
                static_shape = ex.evaluate()(*inputs, **params)
            out = _op.reshape(data, newshape=tuple(static_shape.asnumpy()))

        return out

class Concat(OnnxOpConverter):
    """ Operator converter for Concat.
    """

    @classmethod
    def _impl_v1(cls, inputs, args, params):
        return AttrCvt(op_name='concatenate')((inputs,), args)

class Scale(OnnxOpConverter):
    """ Operator converter for Scale.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        scale = float(attr.get('scale', 1.0))
        return inputs[0] * _expr.const(scale)

class Selu(OnnxOpConverter):
    """ Operator converter for Selu.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        alpha = float(attr.get('alpha', 1.6732))
        gamma = float(attr.get('gamma', 1.0507))
        return _expr.const(gamma) * (_expr.const(-alpha) *
                                     _op.nn.relu(_expr.const(1.) - _op.exp(inputs[0])) +
                                     _op.nn.relu(inputs[0]))

class ScaledTanh(OnnxOpConverter):
    """ Operator converter for ScaledTanh.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        alpha = float(attr.get('alpha', 1.0))
        beta = float(attr.get('beta', 1.0))
        return _op.tanh(_expr.const(beta) * inputs[0]) * _expr.const(alpha)

class SoftPlus(OnnxOpConverter):
    """ Operator converter for SoftPlus.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        return _op.log(_op.exp(inputs[0]) + _expr.const(1.))

class Softsign(OnnxOpConverter):
    """ Operator converter for Softsign.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        return inputs[0] / (_expr.const(1.) + Absolute.get_converter(1)(inputs, attr, params))

class Sub(Elemwise):
    name = 'subtract'

class Sum(OnnxOpConverter):
    """ Operator converter for Sum.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        # Onnx Sum Operator
        for in_index in range(len(inputs) - 1):
            inputs[in_index + 1] = _op.add(inputs[in_index], inputs[in_index + 1])

        return inputs[len(inputs) - 1]

class ThresholdedRelu(OnnxOpConverter):
    """ Operator converter for ThresholdedRelu.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        alpha = float(attr.get('alpha', 0.0))
        alpha_tensor = _op.full_like(inputs[0], fill_value=_expr.const(alpha))
        mask = _op.greater(inputs[0], alpha_tensor).astype("float32")
        return inputs[0] * mask

def _broadcast_constraint():

    def _broadcast_check(attrs):
        if attrs.get('axis', None):
            return False
        return True

    return _broadcast_check, "Specifying broadcast axis not allowed."

def _fully_connected(opset):

    def _impl(inputs, attr, params):
        # get number of channels
        channels = infer_channels(inputs[1], params)
        attr['units'] = channels
        return AttrCvt('dense', ignores=['axis', 'axis_w'])(inputs, attr)

    return _impl

class Upsample(OnnxOpConverter):
    """ Operator converter for Upsample (nearest mode).
    """

    @classmethod
    def _impl_v9(cls, inputs, attr, params):
        scales = attr.get('scales')
        if not scales:
            #Here we are going to higher OPSET version.
            assert len(inputs) == 2, "Upsample op take 2 inputs, {} given".format(len(inputs))
            scales = params[inputs[1].name_hint].asnumpy()
            inputs = inputs[:1]
        assert len(scales) == 4 and scales[0] == 1.0 and scales[1] == 1.0 and scales[2] == scales[3]
        mode = attr.get('mode')
        if mode == b'nearest':
            method = "NEAREST_NEIGHBOR"
        elif mode == b'linear':
            method = "BILINEAR"
        else:
            raise tvm.error.OpAttributeInvalid(
                'Value {} in attribute "mode" of operator Upsample is not valid.'.format(mode))
        attr = {'scale':int(scales[-1]), 'method':method, 'layout':'NCHW'}
        return AttrCvt('upsampling')(inputs, attr)

class Shape(OnnxOpConverter):
    """ Operator converter for Shape.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        # TODO(@jroesch): use shape_of once it has been fixed)
        return _op.shape_of(inputs[0])

class Cast(OnnxOpConverter):
    """ Operator converter for Cast.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        return AttrCvt(op_name='cast', transforms={'to': 'dtype'})(inputs, attr)

    @classmethod
    def _impl_v5(cls, inputs, attr, params):
        try:
            from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
            attr['to'] = str(TENSOR_TYPE_TO_NP_TYPE[attr['to']])
        except ImportError as e:
            raise ImportError(
                "Unable to import onnx.mapping which is required {}".format(e))
        return AttrCvt(op_name='cast', transforms={'to': 'dtype'})(inputs, attr)

class Unsqueeze(OnnxOpConverter):
    """ Operator converter for Unsqueeze.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        for axes in attr['axes']:
            inputs[0] = _op.expand_dims(inputs[0], axis=axes, num_newaxis=1)
        return inputs[0]

class Split(OnnxOpConverter):
    """ Operator converter for Split.
    """

    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        attr['indices_or_sections'] = []
        index = 0
        for i in attr['split'][:-1]:
            index += i
            attr['indices_or_sections'].append(index)
        return AttrCvt(
            'split',
            ignores=['split'])(inputs, attr, params)

class Slice(OnnxOpConverter):
    """ Operator converter for Slice.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        if isinstance(attr['starts'], int):
            attr['starts'] = (attr['starts'],)
            attr['ends'] = (attr['ends'],)

        try:
            # Update the starts and ends according to axes if required.
            if isinstance(attr['axes'], int):
                attr['axes'] = (attr['axes'],)

            if (max(attr['axes']) + 1) != len(attr['axes']):
                new_axes = []
                new_starts = []
                new_ends = []
                pop_index = 0
                for i in range(max(attr['axes']) + 1):
                    if i in attr['axes']:
                        new_axes.append(i)
                        new_starts.append(attr['starts'][pop_index])
                        new_ends.append(attr['ends'][pop_index])
                        pop_index += 1
                    else:
                        new_axes.append(i)
                        new_starts.append(0)
                        new_ends.append(np.iinfo(np.int32).max)
                attr['axes'] = new_axes
                attr['starts'] = new_starts
                attr['ends'] = new_ends
        except KeyError:
            pass

        return AttrCvt('strided_slice',
                       transforms={'starts': 'begin',
                                   'ends': 'end'},
                       ignores=['axes'])(inputs, attr)

class Gather(OnnxOpConverter):
    """ Operator converter for Gather.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        axis = attr.get('axis', 0)
        return AttrCvt('take',
                       extras={'axis':axis})(inputs, {})
        #return _op.take(inputs[0], inputs[1], axis)

class Greater(OnnxOpConverter):
    """ Operator logical greater.
    """
    @classmethod
    def _impl_v7(cls, inputs, attr, params):
        return _op.greater(inputs[0], inputs[1])

class Less(OnnxOpConverter):
    """ Operator logical less than.
    """
    @classmethod
    def _impl_v7(cls, inputs, attr, params):
        return _op.less(inputs[0], inputs[1])

class LRN(OnnxOpConverter):
    """ Operator converter for Local Response Normalization.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        """LRN support only NCHW format
        https://github.com/onnx/onnx/blob/master/docs/Operators.md#LRN
        """
        axis = 1
        alpha = attr.get('alpha', 0.0001)
        beta = attr.get('beta', 0.75)
        bias = attr.get('bias', 1.0)
        nsize = attr.get('size')
        attr = {'size':nsize, 'axis':axis, 'alpha':alpha, 'beta':beta, 'bias':bias}
        return AttrCvt('lrn')(inputs, attr)

class Maximum(OnnxOpConverter):
    """ Operator converter for Maximum.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        if not isinstance(inputs, list) or len(inputs) < 2:
            raise ValueError("Expect minimum 2 inputs")
        _max = inputs[0]
        for i in range(1, len(inputs)):
            _max = AttrCvt('maximum')([_max, inputs[i]], {})
        return _max

class Minimum(OnnxOpConverter):
    """ Operator converter for Minimum.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        if not isinstance(inputs, list) or len(inputs) < 2:
            raise ValueError("Expect minimum 2 inputs")
        _min = inputs[0]
        for i in range(1, len(inputs)):
            _min = AttrCvt('minimum')([_min, inputs[i]], {})
        return _min

class Mean(OnnxOpConverter):
    """ Operator converter for Mean.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        if not isinstance(inputs, list) or len(inputs) < 2:
            raise ValueError("Expect minimum 2 inputs")
        # avoid overflow
        concat = _op.concatenate([_op.expand_dims(x, axis=0) for x in inputs], axis=0)
        return _op.mean(concat, axis=0, keepdims=False)

class HardSigmoid(OnnxOpConverter):
    """ Operator converter for HardSigmoid.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        alpha = attr.get('alpha', 0.2)
        beta = attr.get('beta', 0.5)
        transformX = (inputs[0] * _expr.const(alpha)) + _expr.const(beta)
        attr = {'a_min':0, 'a_max':1}
        return AttrCvt('clip')([transformX], attr)

class Reduce(OnnxOpConverter):
    """ Operator converter for reduce ops.
    """
    name = ''
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        if 'axes' in attr:
            axis = attr.get('axes', 0)
        else:
            axis_len = len(infer_shape(inputs[0]))
            axis = list(range(axis_len))
        attr = {'axis':axis, 'keepdims':attr.get('keepdims', True)}
        return AttrCvt(cls.name)(inputs, attr)

class ReduceMax(Reduce):
    """ Operator converter for ArgMax.
    """
    name = 'max'

class ReduceMin(Reduce):
    """ Operator converter for ArgMax.
    """
    name = 'min'

class ReduceSum(Reduce):
    """ Operator converter for ArgMax.
    """
    name = 'sum'

class ReduceMean(Reduce):
    """ Operator converter for ArgMax.
    """
    name = 'mean'

class ReduceProd(Reduce):
    """ Operator converter for ArgMax.
    """
    name = 'prod'

class ArgMax(OnnxOpConverter):
    """ Operator converter for ArgMax.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        axis = attr.get('axis', 0)
        keepdims = attr.get('keepdims', True)
        attr = {'axis':axis, 'keepdims':keepdims}
        return AttrCvt('argmax')(inputs, attr)

class ArgMin(OnnxOpConverter):
    """ Operator converter for ArgMin.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        axis = attr.get('axis', 0)
        keepdims = attr.get('keepdims', True)
        attr = {'axis':axis, 'keepdims':keepdims}
        return AttrCvt('argmin')(inputs, attr)

class Softmax(OnnxOpConverter):
    """ Operator converter for Softmax.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        # set default value when axis is not set in the model
        if 'axis' not in attr:
            attr['axis'] = 1
        return AttrCvt('softmax', transforms={'axis': ('axis', 1)})(inputs, attr, params)

class ConstantFill(OnnxOpConverter):
    """ Operator converter for ConstantFill.
    """
    @classmethod
    def _impl_v1(cls, inputs, attr, params):
        num_inputs = len(inputs)
        if 'shape' in attr:
            if num_inputs > 1:
                raise ImportError(
                    "Can't set shape and input tensor at a time")
            shape = attr.pop('shape')
        else:
            if num_inputs == 1:
                raise ImportError(
                    "Either shape attribute or input should be set")
            if 'input_as_shape' in attr and attr['input_as_shape']:
                shape = params[get_name(inputs[0])].asnumpy()
            else:
                if 'extra_shape' in attr:
                    raise tvm.error.OpAttributeInvalid('Attribute "extra_shape" not '
                                                       'supported with "fill_like" for '
                                                       'operator ConstantFill.')
                return _op.full_like(inputs[0], inputs[1])

        if 'extra_shape' in attr:
            shape = shape + attr.pop('extra_shape')
        return _op.full(inputs[0], shape)

# compatible operators that do NOT require any conversion.
_identity_list = []

# _convert_map defines maps of name to converter functor(callable)
# for 1 to 1 mapping, use Renamer if nothing but name is different
# use AttrCvt if attributes need to be converted
# for 1 to N mapping(composed), use custom callable functions
# for N to 1 mapping, currently not supported(?)
def _get_convert_map(opset):
    return {
        # defs/experimental
        'Identity': Renamer('copy'),
        # 'Affine'
        'ThresholdedRelu': ThresholdedRelu.get_converter(opset),
        'ScaledTanh': ScaledTanh.get_converter(opset),
        'ParametricSoftplus': ParametricSoftPlus.get_converter(opset),
        'ConstantFill': ConstantFill.get_converter(opset),
        # 'GivenTensorFill'
        'FC': AttrCvt('dense', ignores=['axis', 'axis_w']),
        'Scale': Scale.get_converter(opset),
        # 'GRUUnit'
        # 'ATen'
        # 'ImageScaler'
        # 'MeanVarianceNormalization'
        # 'Crop'
        # 'Embedding'
        'Upsample' : Upsample.get_converter(opset),
        'SpatialBN': BatchNorm.get_converter(opset),

        # defs/generator
        # 'Constant' # Implemented
        # 'RandomUniform'
        # 'RandomNormal'
        # 'RandomUniformLike'
        # 'RandomNormalLike'

        # defs/logical

        # defs/math
        'Add': Add.get_converter(opset),
        'Sub': Sub.get_converter(opset),
        'Mul': Mul.get_converter(opset),
        'Div': Div.get_converter(opset),
        'Neg': Renamer('negative'),
        'Abs': Absolute.get_converter(opset),
        'Reciprocal': Reciprocal.get_converter(opset),
        'Floor': Renamer('floor'),
        'Ceil': Renamer('ceil'),
        'Sqrt': Renamer('sqrt'),
        'Relu': Renamer('relu'),
        'LeakyRelu': Renamer('leaky_relu'),
        'Selu': Selu.get_converter(opset),
        'Elu': Elu.get_converter(opset),
        'Exp': Renamer('exp'),
        'Greater': Greater.get_converter(opset),
        'Less': Less.get_converter(opset),
        'Log': Renamer('log'),
        'Tanh': Renamer('tanh'),
        'Pow': Renamer('power'),
        'PRelu': Prelu.get_converter(opset),
        'Sigmoid': Renamer('sigmoid'),
        'HardSigmoid': HardSigmoid.get_converter(opset),
        'Max': Maximum.get_converter(opset),
        'Min': Minimum.get_converter(opset),
        'Sum': Sum.get_converter(opset),
        'Mean': Mean.get_converter(opset),
        'Clip': AttrCvt('clip', transforms={'min': 'a_min', 'max': 'a_max'}),
        # softmax default axis is different in onnx
        'Softmax': Softmax.get_converter(opset),
        'LogSoftmax': AttrCvt('log_softmax', {'axis': ('axis', 1)}),
        # 'Hardmax'
        'Softsign': Softsign.get_converter(opset),
        'SoftPlus': SoftPlus.get_converter(opset),
        'Gemm': Gemm.get_converter(opset),
        'MatMul': MatMul.get_converter(opset),

        # defs/nn
        'AveragePool': AveragePool.get_converter(opset),
        'MaxPool': MaxPool.get_converter(opset),
        'Conv': Conv.get_converter(opset),
        'ConvTranspose': ConvTranspose.get_converter(opset),
        'GlobalAveragePool': Renamer('global_avg_pool2d'),
        'GlobalMaxPool': Renamer('global_max_pool2d'),
        'BatchNormalization': BatchNorm.get_converter(opset),
        # 'InstanceNormalization'
        # 'LpNormalization'
        'Dropout': AttrCvt('dropout', {'ratio': 'rate'}, ignores=['is_test']),
        'Flatten': Flatten.get_converter(opset),
        'LRN': LRN.get_converter(opset),

        # defs/reduction
        'ReduceMax': ReduceMax.get_converter(opset),
        'ReduceMin': ReduceMin.get_converter(opset),
        'ReduceSum': ReduceSum.get_converter(opset),
        'ReduceMean': ReduceMean.get_converter(opset),
        'ReduceProd': ReduceProd.get_converter(opset),
        # 'ReduceProd'
        # 'ReduceLogSumExp'
        'ArgMax': ArgMax.get_converter(opset),
        'ArgMin': ArgMin.get_converter(opset),

        # defs/tensor
        'Cast': Cast.get_converter(opset),
        'Reshape': Reshape.get_converter(opset),
        'Concat': Concat.get_converter(opset),
        'Split': Split.get_converter(opset),
        'Slice': Slice.get_converter(opset),
        'Transpose': AttrCvt('transpose', {'perm': 'axes'}),
        'Gather': Gather.get_converter(opset),
        'Squeeze': AttrCvt('squeeze', {'axes': 'axis'}),
        'Unsqueeze': Unsqueeze.get_converter(opset),
        'Pad': Pad.get_converter(opset),
        'Shape': Shape.get_converter(opset),
    }

class GraphProto(object):
    """A helper class for handling Relay expression copying from pb2.GraphProto.
    Definition: https://github.com/onnx/onnx/blob/master/onnx/onnx.proto

        Parameters
    ----------
    shape : dict of str to tuple, optional
        The input shape to the graph

    dtype : str or dict of str to str
        The input types to the graph
    """

    def __init__(self, shape, dtype):
        self._nodes = {}
        self._params = {}
        self._renames = {}
        self._num_input = 0
        self._num_param = 0
        self._shape = shape if shape else {}
        self._dtype = dtype

    def from_onnx(self, graph, opset):
        """Construct Relay expression from ONNX graph.

        Onnx graph is a python protobuf object.
        The companion parameters will be handled automatically.
        However, the input names from onnx graph is vague, mixing inputs and
        network weights/bias such as "1", "2"...
        For convenience, we rename the `real` input names to "input_0",
        "input_1"... And renaming parameters to "param_0", "param_1"...

        Parameters
        ----------
        graph : onnx protobuf object
            The loaded onnx graph

        opset : opset version

        Returns
        -------
        mod : tvm.relay.Module
            The returned relay module

        params : dict
            A dict of name: tvm.nd.array pairs, used as pretrained weights
        """
        # parse network inputs to relay, aka parameters
        for init_tensor in graph.initializer:
            if not init_tensor.name.strip():
                raise ValueError("Tensor's name is required.")
            self._params[init_tensor.name] = self._parse_array(init_tensor)
            self._nodes[init_tensor.name] = new_var(init_tensor.name,
                                                    shape=self._params[init_tensor.name].shape,
                                                    dtype=self._params[init_tensor.name].dtype)
        for i in graph.input:
            # from onnx v0.2, GraphProto.input has type ValueInfoProto,
            #  and the name is 'i.name'
            i_name = self._parse_value_proto(i)
            d_type = self._parse_dtype(i, 'float32')
            if i_name in self._params:
                # i is a param instead of input
                self._num_param += 1
                self._params[i_name] = self._params.pop(i_name)
                self._nodes[i_name] = new_var(i_name,
                                              shape=self._params[i_name].shape,
                                              dtype=self._params[i_name].dtype)
            else:
                self._num_input += 1
                if i_name in self._shape:
                    tshape = self._shape[i_name]
                else:
                    raise ValueError("Must provide an input shape for `{0}`.".format(i_name))
                if isinstance(self._dtype, dict):
                    dtype = self._dtype[i_name] if i_name in self._dtype else d_type
                else:
                    dtype = d_type
                self._nodes[i_name] = new_var(i_name, shape=tshape, dtype=dtype)
        # get list of unsupported ops
        convert_map = _get_convert_map(opset)
        unsupported_ops = set()
        for node in graph.node:
            op_name = node.op_type
            if op_name not in convert_map and \
               op_name != 'Constant' and \
               op_name not in _identity_list:
                unsupported_ops.add(op_name)
        if unsupported_ops:
            msg = 'The following operators are not supported for frontend ONNX: '
            msg += ', '.join(unsupported_ops)
            raise tvm.error.OpNotImplemented(msg)
        # construct nodes, nodes are stored as directed acyclic graph
        for node in graph.node:
            op_name = node.op_type
            attr = self._parse_attr(node.attribute)
            inputs = [self._nodes[self._renames.get(i, i)] for i in node.input]
            if op_name == "Constant":
                t_proto = self._parse_attr(node.attribute)["value"]
                self._num_param += 1
                # We should convert scalar integers to int32, to normalize.
                array = self._parse_array(t_proto)
                if len(array.shape) == 0 and array.dtype == 'int64':
                    array = _nd.array(array.asnumpy().astype('int32'))
                self._params[node.output[0]] = array
                self._nodes[node.output[0]] = new_var(
                    node.output[0],
                    shape=list(t_proto.dims),
                    dtype=array.dtype)
            else:
                if op_name == "ConstantFill":
                    fill_value = attr.get('value', 0.0)
                    dtype = attr.get('dtype', b'int32').decode("utf-8")
                    i_name = node.output[0]
                    self._params[i_name] = fill_value
                    self._nodes[i_name] = new_var(node.output[0], shape=(), dtype=dtype)
                    inputs.append(self._nodes[i_name])

                i_name = self._parse_value_proto(node)
                attr['tvm_custom'] = {}
                attr['tvm_custom']['name'] = i_name

                op = self._convert_operator(op_name, inputs, attr, opset)
                node_output = self._fix_outputs(op_name, node.output)
                if not isinstance(op, _expr.TupleWrapper):
                    outputs_num = 1
                else:
                    outputs_num = len(op)
                assert len(node_output) == outputs_num, (
                    "Number of output mismatch {} vs {} in {}.".format(
                        len(node_output), outputs_num, op_name))
                if outputs_num == 1:
                    self._nodes[node_output[0]] = op
                else:
                    for k, i in zip(list(node_output), range(len(node_output))):
                        self._nodes[k] = op[i]

        # now return the outputs
        outputs = [self._nodes[self._parse_value_proto(i)] for i in graph.output]
        outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)
        func = _expr.Function(analysis.free_vars(outputs), outputs)
        return _module.Module.from_expr(func), self._params

    def _parse_value_proto(self, value_proto):
        """Parse ValueProto or raw str."""
        try:
            name = value_proto.name
        except AttributeError:
            name = value_proto
        return name

    def _parse_dtype(self, value_proto, dtype):
        """Parse dtype."""
        try:
            from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
            return TENSOR_TYPE_TO_NP_TYPE[value_proto.type.tensor_type.elem_type].name
        except AttributeError:
            return dtype

    def _parse_array(self, tensor_proto):
        """Grab data in TensorProto and convert to numpy array."""
        try:
            from onnx.numpy_helper import to_array
        except ImportError as e:
            raise ImportError(
                "Unable to import onnx which is required {}".format(e))
        np_array = to_array(tensor_proto).reshape(tuple(tensor_proto.dims))
        return _nd.array(np_array)

    def _parse_attr(self, attr_proto):
        """Convert a list of AttributeProto to a dict, with names as keys."""
        attrs = {}
        for a in attr_proto:
            for f in ['f', 'i', 's']:
                if a.HasField(f):
                    attrs[a.name] = getattr(a, f)
            for f in ['floats', 'ints', 'strings']:
                if list(getattr(a, f)):
                    assert a.name not in attrs, "Only one type of attr is allowed"
                    attrs[a.name] = tuple(getattr(a, f))
            for f in ['t']:
                if a.HasField(f):
                    attrs[a.name] = getattr(a, f)
            for f in ['tensors']:
                if list(getattr(a, f)):
                    assert a.name not in attrs, "Only one type of attr is allowed"
                    attrs[a.name] = tuple(getattr(a, f))
            for f in ['g']:
                if a.HasField(f):
                    raise NotImplementedError(
                        "Filed {} is not supported in relay.".format(f))
            for f in ['graphs']:
                if list(getattr(a, f)):
                    raise NotImplementedError(
                        "Filed {} is not supported in relay.".format(f))
            if a.name not in attrs:
                raise ValueError("Cannot parse attribute: \n{}\n.".format(a))
        return attrs

    def _convert_operator(self,
                          op_name,
                          inputs,
                          attrs,
                          opset):
        """Convert ONNX operator into a Relay operator.
        The converter must specify conversions explicitly for incompatible name, and
        apply handlers to operator attributes.

        Parameters
        ----------
        op_name : str
            Operator name, such as Convolution, FullyConnected
        inputs : list of tvm.relay.expr.Function
            List of inputs.
        attrs : dict
            Dict of operator attributes
        opset : int
            Opset version

        Returns
        -------
        sym : tvm.relay.expr.Function
            Converted relay function
        """
        convert_map = _get_convert_map(opset)
        if op_name in _identity_list:
            sym = get_relay_op(op_name)(*inputs, **attrs)
        elif op_name in convert_map:
            sym = convert_map[op_name](inputs, attrs, self._params)
        else:
            raise NotImplementedError(
                "Operator {} not implemented.".format(op_name))
        return sym

    def _fix_outputs(self, op_name, outputs):
        """A hack to handle dropout or similar operator that have more than one out
        in ONNX.
        """
        if op_name == 'Dropout':
            if len(outputs) == 1:
                return outputs
            # TODO(zhreshold): support dropout mask?
            outputs = outputs[:-1]
        return outputs

def from_onnx(model,
              shape=None,
              dtype="float32"):
    """Convert a ONNX model into an equivalent Relay Function.

    ONNX graphs are represented as Python Protobuf objects.
    The companion parameters will be handled automatically.
    However, the input names from onnx graph is vague, mixing inputs and
    network weights/bias such as "1", "2"...
    For convenience, we rename the `real` input names to "input_0",
    "input_1"... And renaming parameters to "param_0", "param_1"...

    Parameters
    ----------
    model : protobuf object
        ONNX ModelProto after ONNX v1.1.0

    shape : dict of str to tuple, optional
        The input shape to the graph

    dtype : str or dict of str to str
        The input types to the graph

    Returns
    -------
    mod : tvm.relay.Module
        The relay module for compilation

    params : dict of str to tvm.NDArray
        The parameter dict to be used by relay
    """
    try:
        import onnx
        if hasattr(onnx.checker, 'check_model'):
            # try use onnx's own model checker before converting any model
            try:
                onnx.checker.check_model(model)
            except onnx.onnx_cpp2py_export.checker.ValidationError as e:
                import warnings
                # the checker is a bit violent about errors, so simply print warnings here
                warnings.warn(str(e))
    except ImportError:
        pass
    g = GraphProto(shape, dtype)
    graph = model.graph
    try:
        opset = model.opset_import[0].version if model.opset_import else 1
    except AttributeError:
        opset = 1
    mod, params = g.from_onnx(graph, opset)
    return mod, params


text:
<?php

/**
 * This file is part of the Minty templating library.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Minty\Compiler\Operators\ArithmeticOperators;

use Minty\Compiler\Operators\SimpleBinaryOperator;

class RemainderOperator extends SimpleBinaryOperator
{

    public function operators()
    {
        return '%';
    }

    public function compileOperator()
    {
        return ' % ';
    }
}


text:
<?php

class SiteController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';
	public $defaultAction = 'index';

	/**
	 * Initialize admin page theme
	 */
	public function init()
	{
		$arrThemes = $this->currentTemplate('public');
		Yii::app()->theme = $arrThemes['folder'];
		$this->layout = $arrThemes['layout'];
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','add'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array(),
				'users'=>array('@'),
				'expression'=>'isset(Yii::app()->user->level)',
				//'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level != 1)',
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array(),
				'users'=>array('@'),
				'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level == 1)',
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array(),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$criteria=new CDbCriteria;
		$criteria->condition = 'curdate() BETWEEN `batch_start` AND `batch_finish`';
		$batch = PsbYearBatch::model()->find($criteria);

		if($batch != null)
			$this->redirect(array('add'));

		else {
			$this->pageTitle = 'Psb Registers';
			$this->pageDescription = '';
			$this->pageMeta = '';
			$this->render('front_index');
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionAdd()
	{
		$criteria=new CDbCriteria;
		$criteria->condition = 'curdate() BETWEEN `batch_start` AND `batch_finish`';
		$batch = PsbYearBatch::model()->find($criteria);

		if($batch == null)
			$this->redirect(array('index'));

		else {
			$model=new PsbRegisters;
			$school=new PsbSchools;
			$author=new OmmuAuthors;

			// Uncomment the following line if AJAX validation is needed
			$this->performAjaxValidation($model);

			if(isset($_POST['PsbRegisters'])) {
				$model->attributes=$_POST['PsbRegisters'];
				$school->attributes=$_POST['PsbSchools'];
				$author->attributes=$_POST['OmmuAuthors'];

				$authorModel = OmmuAuthors::model()->find(array(
					'select' => 'author_id, email',
					'condition' => 'publish = 1 AND email = :email',
					'params' => array(
						':email' => strtolower($author->email),
					),
				));
				if($authorModel != null) {
					$model->author_id = $authorModel->author_id;
				} else {
					if($author->save())
						$model->author_id = $author->author_id;
				}

				if($model->save()) {
					Yii::app()->user->setFlash('success', 'PsbRegisters success created.');
					//$this->redirect(array('view','id'=>$model->register_id));
					$this->redirect(array('index'));
				}
			}

			$this->pageTitle = 'Psb Registers';
			$this->pageDescription = '';
			$this->pageMeta = '';
			$this->render('front_add', array(
				'model'=>$model,
				'school'=>$school,
				'author'=>$author,
				'batch'=>$batch->batch_id,
			));
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model = PsbRegisters::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404, Yii::t('phrase', 'The requested page does not exist.'));
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='psb-registers-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


text:
module Jekyll
  module Converters
    class Textile < Converter
      safe true

      pygments_prefix '<notextile>'
      pygments_suffix '</notextile>'

      def setup
        return if @setup
        require 'redcloth'
        @setup = true
      rescue LoadError
        STDERR.puts 'You are missing a library required for Textile. Please run:'
        STDERR.puts '  $ [sudo] gem install RedCloth'
        raise FatalException.new("Missing dependency: RedCloth")
      end

      def matches(ext)
        rgx = '(' + @config['textile_ext'].gsub(',','|') +')'
        ext =~ Regexp.new(rgx, Regexp::IGNORECASE)
      end

      def output_ext(ext)
        ".html"
      end

      def convert(content)
        setup

        # Shortcut if config doesn't contain RedCloth section
        return RedCloth.new(content).to_html if @config['redcloth'].nil?

        # List of attributes defined on RedCloth
        # (from http://redcloth.rubyforge.org/classes/RedCloth/TextileDoc.html)
        attrs = ['filter_classes', 'filter_html', 'filter_ids', 'filter_styles',
                'hard_breaks', 'lite_mode', 'no_span_caps', 'sanitize_html']

        r = RedCloth.new(content)

        # Set attributes in r if they are NOT nil in the config
        attrs.each do |attr|
          r.instance_variable_set("@#{attr}".to_sym, @config['redcloth'][attr]) unless @config['redcloth'][attr].nil?
        end

        r.to_html
      end
    end
  end
end


text:
var EvolutionGame = EvolutionGame || {};

EvolutionGame.Player = function(game, x, y, key, level, isEvolution) {
	Phaser.Sprite.call(this, game, x, y, key);

	this.game = game;

	this.name = 'player' + Utils.getRandomInt(1, 50);
	this.isBox = true;
	this.level = level;
	this.levelData = LevelManager.getDataByLevelId(level);

	this.lastPosition = this.position;

	this.isMoving = false;
	this.lastX = this.position.x;
	this.lastY = this.position.y;

	this.anchor.setTo(0.5);
	// this.scale.setTo(0.1);

	this.inputEnabled = true;

	if (isEvolution) {
		this.openBox(true);
	}

	this.input.pixelPerfectClick = true;

	this.events.onInputUp.add(this.onClick, this);
	// this.input.enableDrag();
    this.events.onDragStart.add(this.onMoveStart, this);
    this.events.onDragStop.add(this.onMoveEnd, this);
    this.events.onDragUpdate.add(this.onMoving, this);

    var animFunc = function() {
    	if (this.isMoving)
    		return;

	    var tweenAnim = this.game.add.tween(this);
		tweenAnim.to({y: this.position.y - 10}, 250);

		tweenAnim.onComplete.add(function(){
			var tweenAnim2 = this.game.add.tween(this);
			var x = tweenAnim2.to({y: this.position.y + 10}, 250, 'Linear', true);
		}, this);
		tweenAnim.start();
    }

    //Cria timer que executa animação a cada 3 segundos
    this.animTimer = this.game.time.events.loop(Phaser.Timer.SECOND * 3, animFunc, this);

};

EvolutionGame.Player.prototype = Object.create(Phaser.Sprite.prototype);
EvolutionGame.Player.prototype.constructor = EvolutionGame.Player;

EvolutionGame.Player.prototype.onClick = function(sprite, pointer) {
	this.openBox(false);
}

EvolutionGame.Player.prototype.openBox = function(isEvolution) {
	if (this.isBox) {
		console.log('Abriu ' + this.name);
		this.isBox = false;
		this.input.enableDrag();

		var newSprite = LevelManager.getSpriteByLevelId(this.level);

		if (!isEvolution) {
			this.loadTexture(newSprite, 0);
		}
		this.scale.setTo(this.levelData.image.scale);
	}
}

EvolutionGame.Player.prototype.onMoveStart = function(sprite, pointer) {
	// console.log('movendo...');

	//Coloca o sprite atual na frente dos outros
	sprite.bringToTop();
};

EvolutionGame.Player.prototype.onMoving = function(sprite, pointer) {
	 // console.log('onMoving...');
	// sprite.bringToTop();
	if (sprite.position.x != this.lastX || sprite.position.y != this.lastY) {
		this.isMoving = true;
	}
};

EvolutionGame.Player.prototype.onMoveEnd = function(sprite, pointer) {

	if (sprite.position.x == this.lastX && sprite.position.y == this.lastY) {
		// console.log('Não pode fundir pois não moveu o personagem.');
		return;
	}
	this.lastX = sprite.position.x;
	this.lastY = sprite.position.y;
	this.isMoving = false;

	var checkOverlap = function(spriteA, spriteB) {
	    var boundsA = spriteA.getBounds();
	    var boundsB = spriteB.getBounds();
	    return Phaser.Rectangle.intersects(boundsA, boundsB);
	};

	for(var element of this.parent.children) {
		if (element != this) {
			if (checkOverlap(this, element)) {
				EvolutionGame.GameState.playerManager.mergePlayers(this, element);
				return;
			}
		}
	}

};

EvolutionGame.Player.prototype.update = function() {

};

EvolutionGame.Player.prototype.destroy = function() {
	this.game.time.events.remove(this.animTimer);

	//chama super
	Phaser.Sprite.prototype.destroy.call(this);
}