text:
module Elastec
  module Connection
    def connection
      Elastec.connection
    end

    SERVER_ERROR = Elasticsearch::Transport::Transport::ServerError
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace IPCUtilities.IpcPmrep.CommandObjects
{
    public class PmrepConnection
    {
        private string _domain;
        private string _repository;
        private string _hostName;
        private string _port;
        private string _userName;
        private string _password;
        private string _timeout;

        public string Domain
        {
            get { return _domain; }
            set { _domain = " -d " + value; }
        }
        public string Repository { get { return _repository; } set { _repository = " -r " + value; } }
        public string HostName { get { return _hostName; } set { _hostName = " -h " + value; } }
        public string Port { get { return _port; } set { _port = " -o " + value; } }
        public string UserName { get { return _userName; } set { _userName = " -n " + value; } }
        public string Password { get { return _password; } set { _password = " -x " + value; } }
        public string Timeout { get { return _timeout; } set { _timeout = " -t " + value; } }
    }
}


text:
package org.apache.commons.vfs2.provider.http5s;

import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.GenericURLFileNameParser;

/**
 * FileNameParser implementation for http5s provider, setting default port to 443.
 *
 * @since 2.5.0
 */
public class Http5sFileNameParser extends GenericURLFileNameParser {

    private static final int DEFAULT_PORT = 443;

    private static final Http5sFileNameParser INSTANCE = new Http5sFileNameParser();

    public Http5sFileNameParser() {
        super(DEFAULT_PORT);
    }

    public static FileNameParser getInstance() {
        return INSTANCE;
    }
}


text:
from __future__ import print_function
from http.server import BaseHTTPRequestHandler,HTTPServer
import argparse
import json
import os
import pysearch
import urllib.parse

DIR = os.path.dirname(__file__)
RESOURCE_PATH = os.path.realpath(os.path.join(DIR, '..', '..', 'data'))
MWM_PATH = os.path.realpath(os.path.join(DIR, '..', '..', 'data'))
PORT=8080

class HTTPHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        result = urllib.parse.urlparse(self.path)
        query = urllib.parse.parse_qs(result.query)

        def sparam(name):
            return query[name][-1]

        def fparam(name):
            return float(sparam(name))

        params = pysearch.Params()
        try:
            params.query = sparam('query')
            params.locale = sparam('locale')
            params.position = pysearch.Mercator(fparam('posx'), fparam('posy'))
            params.viewport = pysearch.Viewport(
                pysearch.Mercator(fparam('minx'), fparam('miny')),
                pysearch.Mercator(fparam('maxx'), fparam('maxy')))
        except KeyError:
            self.send_response(400)
            return

        results = HTTPHandler.engine.query(params)

        responses = [{'name': result.name,
                      'address': result.address,
                      'has_center': result.has_center,
                      'center': {'x': result.center.x,
                                 'y': result.center.y
                                }
                     }
                     for result in results]

        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps(responses).encode())

def main(args):
    pysearch.init(args.r, args.m)
    engine = pysearch.SearchEngine()
    HTTPHandler.engine = pysearch.SearchEngine()

    print('Starting HTTP server on port', PORT)
    server = HTTPServer(('', args.p), HTTPHandler)
    server.serve_forever()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-r', metavar='RESOURCE_PATH', default=RESOURCE_PATH,
                        help='Path to resources directory.')
    parser.add_argument('-m', metavar='MWM_PATH', default=MWM_PATH,
                        help='Path to mwm files.')
    parser.add_argument('-p', metavar='PORT', default=PORT,
                        help='Port for the server to listen')
    args = parser.parse_args()

    main(args)


text:
let state = {
    height: 4,
    spacesAmount: 2,
    symbol: '#',
}

// Getting arguments from the console
process.argv.forEach(arg => {
    arg = arg.split('=');

    switch (arg[0]) {
        case 'height':
            return state.height = parseInt(arg[1], 10);
        case 'spaces':
            return state.spacesAmount = parseInt(arg[1], 10);
        case 'symbol':
            return state.symbol = arg[1];
    }
});

// Prints pyramids
const piramidPrints = state => {
    const { height } = state;

    let str = `Height: ${height}\n`;

    for (let i = 1; i <= height; i++) {
        str += lineCreate(i, state)+'\n';
    }

    console.log(str);
}

// Creates spaces between pyramids
function spacesCreate(amount) {
    let space = '';

    for (let i = 0; i < amount; i++) {
        space += ' ';
    }

    return space;
}

// Creates a line of characters
function lineCreate(i, state) {
    const { height, spacesAmount, symbol } = state;
    let str = '';

    for (let j = 1; j <= height*2; j++) {
        if (j <= (height-i) || j > height+i) {
            str += ' ';
        } else {
            str += symbol;
        }
    }

    // Receiving the slice of the left half lines
    let leftString = str.slice(0,height),
    // Receiving the slice of the right half lines
        rightString = str.slice(height),
    // Receiving the number of spaces
        numberOfSpaces = spacesCreate(spacesAmount);
    // Combining in a single line
    return str = `${leftString}${numberOfSpaces}${rightString}`;
}

// Call piramidPrints function
piramidPrints(state);


text:
/*

	-- -- -- -- -- -- --
	mod_rapid_contact
	-- -- -- -- -- -- --

*/

	.mod_rapid_contact fieldset {
		margin: 0;
		padding: 0;
		border: none;
	}
	.mod_rapid_contact fieldset legend {
		display: none;
	}
	.mod_rapid_contact fieldset label {
		display: block;
	}
	.mod_rapid_contact fieldset .input-wrap {
		margin: 0 0 1.5em 0;
	}
	.mod_rapid_contact fieldset label span.required {
		text-transform: uppercase;
		font-size: xx-small;
		color: red;
	}
	/*.mod_rapid_contact fieldset span.input span.errorMessage {
		display: block;
		line-height: 12px;
		padding-left: 12px;
		position: absolute;
		right: -29.5%;
		top: 0;
		width: 25%;
	}*/
	.mod_rapid_contact fieldset span.input input,
	.mod_rapid_contact fieldset span.input textarea {
		max-width: 100%;
		width: 100%;
	}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Login Page</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

		      			Test APP

Home

LogIn

Register

				<form class="form-horizontal" action="/users/registeruser" role="form" method="post">

						Email:

   							<input type="email" name="email" class="form-control">

						First Name:

   							<input type="text" name="first_name" class="form-control">

						Last Name:

   							<input type="text" name="last_name" class="form-control">

						Password:

   							<input type="password" name="password" class="form-control">

						Confirm Password:

   							<input type="password" name="confirm_password" class="form-control">

      						<button type="submit" class="btn btn-success">Register</button>

      					Already have an account? Login here

      						<?=$this->session->flashdata('error')?>

    			</form>


text:
package cn.wizzer.modules.controllers.platform.wx;

import cn.wizzer.common.annotation.SLog;
import cn.wizzer.common.base.Result;
import cn.wizzer.common.filter.PrivateFilter;
import cn.wizzer.common.page.DataTableColumn;
import cn.wizzer.common.page.DataTableOrder;
import cn.wizzer.modules.models.wx.Wx_config;
import cn.wizzer.modules.models.wx.Wx_user;
import cn.wizzer.modules.services.wx.WxConfigService;
import cn.wizzer.modules.services.wx.WxUserService;
import com.vdurmont.emoji.EmojiParser;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.*;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;
import org.nutz.weixin.spi.WxApi2;
import org.nutz.weixin.spi.WxResp;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Wizzer on 2016/7/8.
 */
@IocBean
@At("/platform/wx/user")
@Filters({@By(type = PrivateFilter.class)})
public class WxUserController {
    private static final Log log = Logs.get();
    @Inject
    WxUserService wxUserService;
    @Inject
    WxConfigService wxConfigService;

    @At({"/index", "/index/?"})
    @Ok("beetl:/platform/wx/user/index.html")
    @RequiresAuthentication
    public void index(String wxid, HttpServletRequest req) {
        List<Wx_config> list = wxConfigService.query(Cnd.NEW());
        if (list.size() > 0 && Strings.isBlank(wxid)) {
            wxid = list.get(0).getId();
        }
        req.setAttribute("wxid", wxid);
        req.setAttribute("wxList", list);
    }

    @At({"/data/","/data/?"})
    @Ok("json:full")
    @RequiresAuthentication
    public Object data(String wxid, @Param("nickname") String nickname, @Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
        Cnd cnd = Cnd.NEW();
        if (!Strings.isBlank(wxid)) {
            cnd.and("wxid", "=", wxid);
        }
        if (!Strings.isBlank(nickname)) {
            cnd.and("nickname", "like", "%" + nickname + "%");
        }
        return wxUserService.data(length, start, draw, order, columns, cnd, null);
    }

    @At("/down/?")
    @Ok("json")
    @RequiresPermissions("wx.user.list.sync")
    @SLog(tag = "同步微信会员", msg = "公众号:${args[1].getAttribute('appname')}")
    public Object down(String wxid, HttpServletRequest req) {
        try {
            Wx_config config = wxConfigService.fetch(wxid);
            req.setAttribute("appname", config.getAppname());
            WxApi2 wxApi2 = wxConfigService.getWxApi2(wxid);
            wxApi2.user_get(new Each<String>() {
                public void invoke(int index, String _ele, int length)
                        throws ExitLoop, ContinueLoop, LoopException {
                    WxResp resp = wxApi2.user_info(_ele, "zh_CN");
                    log.info(Json.toJson(resp));
                    log.debug(index
                            + " : "
                            + _ele
                            + ", nickname: "
                            + resp.user().getNickname());
                    Wx_user usr = Json.fromJson(Wx_user.class, Json.toJson(resp.user()));
                    usr.setOpAt((int) (System.currentTimeMillis() / 1000));
                    usr.setNickname(EmojiParser.parseToAliases(usr.getNickname(), EmojiParser.FitzpatrickAction.REMOVE));
                    usr.setSubscribeAt((int) (resp.user().getSubscribe_time()));
                    usr.setWxid(wxid);
                    if (wxUserService.fetch(Cnd.where("wxid", "=", wxid).and("openid", "=", usr.getOpenid())) == null)
                        wxUserService.insert(usr);
                }
            });
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }
}


text:
codeId: pingback-listener-vc
---
```ruby
require_relative '/path/to/paymentwall-ruby/lib/paymentwall.rb'
Paymentwall::Base::setApiType(Paymentwall::Base::API_VC)
Paymentwall::Base::setAppKey('YOUR_PROJECT_KEY') # available in your Paymentwall merchant area
Paymentwall::Base::setSecretKey('YOUR_SECRET_KEY') # available in your Paymentwall merchant area

pingback = Paymentwall::Pingback.new(request_get_params, request_ip_address)
if pingback.validate()
    virtualCurrency = pingback.getVirtualCurrencyAmount()
    if pingback.isDeliverable()
        # deliver the virtual currency
    elsif pingback.isCancelable()
        # withdraw the virual currency
    end
    puts 'OK' # Paymentwall expects response to be OK, otherwise the pingback will be resent
else
    puts pingback.getErrorSummary()
end
```


text:
package com.cloudera.sqoop.hbase;

import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

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

import static java.util.Arrays.asList;
import static org.apache.commons.lang.StringUtils.join;

@RunWith(Parameterized.class)
public class HBaseImportAddRowKeyTest extends HBaseTestCase {

  @Parameterized.Parameters(name = "bulkLoad = {0}")
  public static Iterable<? extends Object> bulkLoadParameters() {
    return Arrays.asList(new Boolean[] { false } , new Boolean[] { true } );
  }

  private String[] columnTypes;

  private String[] columnValues;

  private String hbaseTableName;

  private String hbaseColumnFamily;

  private String hbaseTmpDir;

  private String hbaseBulkLoadDir;

  private boolean bulkLoad;

  public HBaseImportAddRowKeyTest(boolean bulkLoad) {
    this.bulkLoad = bulkLoad;
  }

  @Before
  public void setUp() {
    super.setUp();
    columnTypes = new String[] { "INT", "INT" };
    columnValues = new String[] { "0", "1" };
    hbaseTableName = "addRowKeyTable";
    hbaseColumnFamily = "addRowKeyFamily";
    hbaseTmpDir = TEMP_BASE_DIR + "hbaseTmpDir";
    hbaseBulkLoadDir = TEMP_BASE_DIR + "hbaseBulkLoadDir";
    createTableWithColTypes(columnTypes, columnValues);
  }

  @Test
  public void testAddRowKey() throws IOException {
    String[] argv = getImportArguments(true, hbaseTableName, hbaseColumnFamily);

    runImport(argv);

    // Row key should have been added
    verifyHBaseCell(hbaseTableName, columnValues[0], hbaseColumnFamily, getColName(0), columnValues[0]);
    verifyHBaseCell(hbaseTableName, columnValues[0], hbaseColumnFamily, getColName(1), columnValues[1]);
  }

  @Test
  public void testAddRowKeyDefault() throws IOException {
    String[] argv = getImportArguments(false, hbaseTableName, hbaseColumnFamily);

    runImport(argv);

    // Row key should not be added by default
    verifyHBaseCell(hbaseTableName, columnValues[0], hbaseColumnFamily, getColName(0), null);
    verifyHBaseCell(hbaseTableName, columnValues[0], hbaseColumnFamily, getColName(1), columnValues[1]);
  }

  @Test
  public void testAddCompositeKey() throws IOException {
    String rowKey = getColName(0)+","+getColName(1);

    String[] argv = getImportArguments(true, hbaseTableName, hbaseColumnFamily, rowKey);

    runImport(argv);

    // Row key should have been added
    verifyHBaseCell(hbaseTableName, join(columnValues, '_'), hbaseColumnFamily, getColName(0), columnValues[0]);
    verifyHBaseCell(hbaseTableName, join(columnValues, '_'), hbaseColumnFamily, getColName(1), columnValues[1]);
  }

  private String[] getImportArguments(boolean addRowKey, String hbaseTableName, String hbaseColumnFamily) {
    return getImportArguments(addRowKey, hbaseTableName, hbaseColumnFamily, null);
  }

  private String[] getImportArguments(boolean addRowKey, String hbaseTableName, String hbaseColumnFamily, String rowKey) {
    List<String> result = new ArrayList<>();

    if (addRowKey) {
      result.add("-D");
      result.add("sqoop.hbase.add.row.key=true");
    }
    result.add("-D");
    result.add("hbase.fs.tmp.dir=" + hbaseTmpDir);

    result.addAll(asList(getArgv(true, hbaseTableName, hbaseColumnFamily, true, null)));

    if(bulkLoad) {
      result.add("--target-dir");
      result.add(hbaseBulkLoadDir);
      result.add("--hbase-bulkload");
    }

    if (!StringUtils.isBlank(rowKey)) {
      result.add("--hbase-row-key");
      result.add(rowKey);
    }

    return result.toArray(new String[result.size()]);
  }

}


text:
Difficulty: Medium

https://leetcode.com/problems/print-words-vertically/

Given a string s. Return all the words vertically in the same order in which they appear in s.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.

**Example 1:**
```
Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically.
 "HAY"
 "ORO"
 "WEU"
```

**Example 2:**
```
Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed.
"TBONTB"
"OEROOE"
"   T"
```

**Example 3:**
```
Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]
```

**Constraints:**

* 1 <= s.length <= 200
* s contains only upper case English letters.
* It's guaranteed that there is only one space between 2 words.


text:
"""
Hooks for customizing login with social providers
https://django-allauth.readthedocs.io/en/latest/advanced.html
"""
from allauth.account.signals import user_logged_in
from common.helpers.front_end import section_url
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth.account.adapter import DefaultAccountAdapter
from django.dispatch import receiver
from common.helpers.constants import FrontEndSection
from common.helpers.error_handlers import ReportableError
from common.helpers.s3 import copy_external_thumbnail_to_s3
from civictechprojects.models import ProjectFile, FileCategory
from democracylab.models import Contributor
from django.contrib.auth.models import User
from django.utils import timezone
import simplejson as json

class MissingOAuthFieldError(ReportableError):
    """Exception raised when required fields are not returned from OAuth

    Attributes:
        missing_fields -- description of missing fields
        message -- explanation of the error to be reported in the logs
    """

    def __init__(self, message, provider, missing_fields):
        super().__init__(message, {'provider': provider, 'missing_fields': missing_fields})

class MyAccountAdapter(DefaultAccountAdapter):
    def get_login_redirect_url(self, request):
        if 'prev_page' in request.session:
            prev_page = request.session['prev_page']
            prev_page_args = request.session['prev_page_args']
            del request.session['prev_page']
            del request.session['prev_page_args']
            redirect_url = '/' if prev_page.strip('/') == '' else section_url(prev_page, prev_page_args)
        else:
            redirect_url = section_url(FrontEndSection.Home)
        return redirect_url

class SocialAccountAdapter(DefaultSocialAccountAdapter):

    def new_user(self, request, sociallogin):
        email = sociallogin.account.get_provider().extract_common_fields(
                                                   sociallogin.account.extra_data).get('email').lower()
        assert email
        # This account may actually belong to an existing user
        user = User.objects.filter(username=email).first()
        if user:
            # Preserve current password (sociallogin assigns an unusable password)
            if user.has_usable_password():
                sociallogin.account.extra_data.update(password=user.password)
            return Contributor.objects.get_by_natural_key(user.username)
        else:
            return Contributor(email_verified=True, last_login=timezone.now())

    def pre_social_login(self, request, sociallogin):
        """
        Invoked just after a user successfully authenticates via a
        social provider, but before the login is actually processed.

        You can use this hook to intervene, e.g. abort the login by
        raising an ImmediateHttpResponse
        """
        # standardizing fields across different providers
        provider = sociallogin.account.get_provider()
        data = provider.extract_common_fields(
            sociallogin.account.extra_data)

        full_name = data.get('name')
        first_name = data.get('first_name')
        last_name = data.get('last_name')

        if full_name or (first_name and last_name):
            sociallogin.user.first_name = first_name or full_name.split()[0]
            sociallogin.user.last_name = last_name or ' '.join(full_name.split()[1:])
        # Set username to lowercase email
        sociallogin.user.username = sociallogin.user.email.lower()

        password = sociallogin.account.extra_data.get('password')
        if password:
            sociallogin.user.password = password

        if sociallogin.is_existing:
            sociallogin.user.save()  # Update only the user
            return

        # Upsert the User and the SocialAccount
        sociallogin.connect(request, sociallogin.user)

    @receiver(user_logged_in)
    def set_avatar_at_login(sender, sociallogin, **kwargs):
        owner = sociallogin.user.contributor
        user_avatar_url = sociallogin.account.get_provider().get_avatar_url(sociallogin)

        if user_avatar_url:
            file_json = copy_external_thumbnail_to_s3(user_avatar_url, sociallogin.account.provider, owner)
            ProjectFile.replace_single_file(owner, FileCategory(file_json['file_category']), file_json)


text:
import React from 'react';
import $ from 'jquery';
import PortfolioBox from './PortfolioBox';
import Resume from './Resume';
import ResumeColumn from './ResumeColumn';
import OtherSkills from './OtherSkills';
import axios from 'axios';

export default class HomePage extends React.Component {
  constructor() {
    super();
    this.state = {
      showResume: false,
      buttonText1: 'Show résumé?',
      buttonText2: 'Hide résumé?',
      buttonText: 'Show résumé?'
    };

    this.resumeColumnClick = this.resumeColumnClick.bind(this);
    this.resumeClick = this.resumeClick.bind(this);
  }

  componentDidMount() {
    window.addEventListener(
      'scroll',
      function() {
        let top = this.scrollY;
        // let left = this.scrollX;
        let height0 = $('#section0Box').outerHeight(true);
        let height1 = $('#section1Box').outerHeight(true);
        let height2 = $('#section2Box').outerHeight(true);
        // let height3 = $('#section3Box').outerHeight(true);
        let totalHeight = height0 + height1 + height2 - 150;
        if (top > totalHeight) {
          document.getElementById('section0Nav').className = 'section0Gone';
          document.getElementById('navText').className = 'nav1TextGone';
        }
        if (top <= totalHeight) {
          document.getElementById('section0Nav').className = 'section0';
          document.getElementById('navText').className = 'nav1Text';
        }
      },
      false
    );
  }

  componentWillUnmount() {
    window.removeEventListener('scroll');
  }

  resumeColumnClick(e) {
    e.preventDefault();
    if (!this.state.showResume) {
      document.getElementById('resumeColumn').className = 'resumeBox';
      document.getElementById('resumeColumnButton').className =
        'tabBarTabResume';
      document.getElementById('resumeButton').className = 'tabBarTabResume';
      this.setState({
        showResume: true,
        buttonText: this.state.buttonText2
      });
    } else {
      document.getElementById('resumeColumn').className = 'resumeBoxHide';
      document.getElementById('resumeColumnButton').className =
        'tabBarTabActiveResume';
      document.getElementById('resumeButton').className =
        'tabBarTabActiveResume';
      this.setState({
        showResume: false,
        buttonText: this.state.buttonText1
      });
    }
  }

  resumeClick(e) {
    e.preventDefault();
    if (!this.state.showResume) {
      document.getElementById('resume').className = 'resumeBox';
      document.getElementById('resumeButton').className = 'tabBarTabResume';
      document.getElementById('resumeColumnButton').className =
        'tabBarTabResume';
      this.setState({
        showResume: true,
        buttonText: this.state.buttonText2
      });
    } else {
      document.getElementById('resume').className = 'resumeBoxHide';
      document.getElementById('resumeButton').className =
        'tabBarTabActiveResume';
      document.getElementById('resumeColumnButton').className =
        'tabBarTabActiveResume';
      this.setState({
        showResume: false,
        buttonText: this.state.buttonText1
      });
    }
  }

  render() {
    return (

        {/*
 */}

          {/*  */}
          {/*

           */}

                  richardmands.com

              {/*

 */}

Richard Mands

Full-Stack Developer

                 |

                 |

                {/*  |
                 */}

                  Please allow me to introduce myself...

                  {/* {bioFull} */}

                    I'm a full-stack developer with primary experience in
                    JavaScript. I'm proficient with a JS stack based around
                    React, Redux, Node, Express and Webpack. I've also worked
                    with a variety of other React adjacent technologies such as
                    MongoDB, Mongoose, Gatsby, Parcel, Flux, etc, as well as
                    Ruby (Rails, Sinatra) AWS (Lambda, SNS/SQS, Serverless) and
                    have experience of technologies such as Socket.io, DynamoDB,
                    Firebase, Google APIs and others.

                    A quick study who has learned how to learn, I have a strong
                    leadership background, adapt easily to new technologies and
                    bring with me a real passion for what I do, a fierce
                    work-ethic and an honest desire to leave the world a better
                    place each day.

                    I am currently working as a Lead Software Engineer at{' '}

                      {' '}
                      Bede Gaming
                    {' '}
                    . Prior to that I was a Software Engineer at{' '}

                      {' '}
                      Sage
                    {' '}
                    and previously spent 3 years coding, designing and marketing
                    as co-founder of

                      {' '}
                      Cinderhouse Creative

                    .

                    Through Cinderhouse Creative, I was a co-founder / developer
                    of{' '}

                      Eduku

                    , a social enterprise (self-funded charity), that aimed to
                    raise funds for those lacking educational opportunities in
                    low-income countries via an online learning platform.

                    I was also part of the team that won Cisco's first prize at
                    AngelHack's Lady Problems hackathon in San Francisco in
                    October 2016 for creating Entable (an sms-based online
                    banking platform aimed specifically at supporting women in
                    low-income countries by offering wider access to
                    microfinance).

            <PortfolioBox />

          {/*

              MINI-PROJECTS

              These projects are designed to showcase the usage of basic javascript technologies.

                  React-DnD - Drag and drop using React and React-dnd

                  Study Bubble - A VR learning environment built using A-Frame

                  Friendalizer - IBM Watson and Microsoft Cognitive Services

                  PokeAPI - Using data from an external API

 */}

CONTACT

richard@eduku.org

                   |

                   |

                  {/*  |
                 */}

RÉSUMÉ

                  Download pdf

                 /

                  Download word

              {/*

              Lorem oopsum lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

 */}
              <ResumeColumn
                resumeColumnClick={this.resumeColumnClick}
                buttonText={this.state.buttonText}
                showResume={this.state.showResume}
              />
              <Resume
                resumeClick={this.resumeClick}
                buttonText={this.state.buttonText}
                showResume={this.state.showResume}
              />

          <OtherSkills />

            {/*
 */}

richardmands.com

created by Richard Mands

                 |

                 |

                {/*  |
               */}

    );
  }
}


text:
/************************************************************************
 *
 * billboard.cpp
 * BillBoard class implementation
 *
 ************************************************************************/

#include "billboard.h"

#include <GL/gl.h>

/**
 * Constructor. The texture does not belong to the billboard and must
 * be kept valid while the billboard is used. The texture may be NULL.
 */
BillBoard::BillBoard(Texture *tex)
    : tex(tex)
{
    h = 0.5;
}
/**
 * Destructor.
 */
BillBoard::~BillBoard()
{
    //nothing to destruct.
}

/**
 * Render the billboard.
 */
void BillBoard::render(float dt)
{
    if (!isVisible()) {
        return;
    }
    if (!tex) {
        return;
    }

    glPushMatrix();
    glTranslatef(getPosition().x, getPosition().y, getPosition().z);
    glRotatef(getRotation()*180.0/M_PI, 0, 1, 0);

    //get the modelview matrix
    float matrix[16];
    glGetFloatv(GL_MODELVIEW_MATRIX, matrix);

    //Get the correct vectors for billboarding
    vector4 right(matrix[0], matrix[4], matrix[8]);
    vector4 up(matrix[1], matrix[5], matrix[9]);

    //Scale the up and right vectors to the right height and aspect ratio
    up = up * h;
    right = right * h * tex->getAspectRatio();

    glEnable(GL_TEXTURE_2D);
    glDisable(GL_LIGHTING);

    //Bind the texture
    tex->bind();

    //this will only draw visible pixels
    glEnable(GL_ALPHA_TEST);
    glAlphaFunc(GL_GREATER, 0);

    glColor4f(1,1,1,1);

    //Draw particles
    glBegin(GL_POLYGON);

    //vector4 normal = right % up;
    //glNormal3d(normal.x, normal.y, normal.z);

    vector4 calc = (right + up);
    glTexCoord2f(1.0, 0.0);
    glVertex3d(calc.x, calc.y, calc.z);

    calc = (right - up);
    glTexCoord2f(1.0, 1.0);
    glVertex3d(calc.x, calc.y, calc.z);

    calc = (-right - up);
    glTexCoord2f(0.0, 1.0);
    glVertex3d(calc.x, calc.y, calc.z);

    calc = (up - right);
    glTexCoord2f(0.0, 0.0);
    glVertex3d(calc.x, calc.y, calc.z);

    glEnd();

    //return everything to the way it was
    glEnable(GL_LIGHTING);
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_ALPHA_TEST);

    glPopMatrix();
}


text:
package edu.ufl.bmi.ontology;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.regex.Pattern;

import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLNamedIndividual;

import edu.ufl.bmi.misc.DataObject;
import edu.ufl.bmi.misc.IriLookup;

public class RdfConversionQueryIndividualByAttributeValueInstruction extends RdfConversionInstruction {

	/*
		Here, the variableName is the varible in the file currently being processed, whose
			value we will use to query for the IRI of an already existing individual
			created while we processed a previous file.

		Loosely speaking (and drawing analogy to relational data), this field is the
			foreigh key.
	*/
	String variableName;
	IRI classIri;
	IRI annotationPropertyIri;
	AnnotationValueBuilder avb;
	boolean alwaysCreate;
	ArrayList<ArrayList<String>> conditions;
	IriRepository iriRepository;
	String iriRepositoryPrefix;

	String iriPrefix;
	String queryIriPrefix;
	String externalFileFieldName;
	String externalFileRowTypeName;
	String lookupValueFieldName;
	String lookupVariableName;
	String lookupUniqueIdFieldName;
	ArrayList<String> searchInstructions;
	//int lookupValueFieldIndex;

	public RdfConversionQueryIndividualByAttributeValueInstruction(IriLookup iriMap, OWLDataFactory odf, String variableName,
			IriRepository iriRepository, String iriRepositoryPrefix, String externalFileFieldName, String externalFileRowTypeName, String iriPrefix,
			String lookupValueFieldName, String lookupUniqueIdFieldName, String searchInstructions) {
		super(iriMap, odf);
		this.variableName = variableName.replaceFirst("[\\[]","");
		if (variableName.endsWith("]")) {
			int len = this.variableName.length();
			this.variableName = this.variableName.substring(0, len-1);
		}

		//this.variableName = (variableName.startsWith("[")) ? variableName.replace("[","").replace("]","") : variableName ;
		this.iriRepository = iriRepository;
		this.iriRepositoryPrefix = iriRepositoryPrefix;
		this.externalFileFieldName = externalFileFieldName;
		this.externalFileRowTypeName = externalFileRowTypeName;
		this.iriPrefix = iriPrefix;
		this.queryIriPrefix = this.iriPrefix + this.externalFileRowTypeName;
		//this.lookupValueFieldName = lookupValueFieldName.replace("[","").replace("]","");
		this.lookupValueFieldName = lookupValueFieldName.replaceFirst("[\\[]","");
		if (lookupValueFieldName.endsWith("]")) {
			int len = this.lookupValueFieldName.length();
			this.lookupValueFieldName = this.lookupValueFieldName.substring(0, len-1);
		}
		this.lookupUniqueIdFieldName = lookupUniqueIdFieldName.replaceFirst("[\\[]","");
		if (lookupUniqueIdFieldName.endsWith("]")) {
			int len = this.lookupUniqueIdFieldName.length();
			this.lookupUniqueIdFieldName = this.lookupUniqueIdFieldName.substring(0, len-1);
		}

		if (searchInstructions != null) initializeSearchInstructions(searchInstructions);
		//System.out.println(lookupValueFieldName);
		//this.lookupValueFieldIndex = fieldNameToIndex.get(this.lookupValueFieldName);
	}

	protected void initializeSearchInstructions(String instructions) {
		String[] instructionArray = instructions.split(Pattern.quote(","));
		this.searchInstructions = new ArrayList<String>();
		for (String instruction : instructionArray) {
			this.searchInstructions.add(instruction);
		}
	}

/*
	@Override
	public void execute(OWLNamedIndividual rowIndividual, ArrayList<String> recordFields, HashMap<String, OWLNamedIndividual> variables, OWLOntology oo) {
		HashMap<IRI, String> repoAnnotations = new HashMap<IRI, String>();
		IRI externalFieldIri = IRI.create(queryIriPrefix + "/" + externalFileFieldName);
		repoAnnotations.put(externalFieldIri, recordFields.get(fieldNameToIndex.get(this.lookupValueFieldName)));
		IRI externalVarNameIri = IRI.create(queryIriPrefix + "/variableName");
		repoAnnotations.put(externalVarNameIri, "row individual");

		Set<IRI> resultSet = iriRepository.queryIris(null, repoAnnotations);
		int resultCount = resultSet.size();
		if (resultCount > 1) {
			throw new RuntimeException("resultSet should be size 1, but got " + resultCount);
		}
		OWLNamedIndividual oni = (resultCount == 1) ?
			odf.getOWLNamedIndividual(resultSet.iterator().next()) :
			null;

		//System.out.println("Adding the following to variables: " + variableName + "\t" + oni);
		if (oni != null) variables.put(variableName, oni);
		//iriRepository.addIris(oni.getIRI(), null, repoAnnotations);
	}
*/

	public void setLookupVariableName(String lookupVariableName) {
		this.lookupVariableName = lookupVariableName;
	}

	public void execute(OWLNamedIndividual rowIndividual, DataObject dataObject, DataObject parentObject, HashMap<String, OWLNamedIndividual> variables, OWLOntology oo) {
		//if for some reason we already found it, or maybe in some circumstances I haven't foreseen yet, created it, then just return
		if (variables.containsKey(this.variableName) && variables.get(this.variableName) != null) {
			System.err.println("variable [" + this.variableName + "] already set to " + variables.get(this.variableName));
			return;
		}
		String lookupValue = dataObject.getDataElementValue(lookupValueFieldName);
		if (lookupValue == null || lookupValue.length() == 0) return;

		lookupValue = processSearchInstructions(lookupValue);

		HashMap<IRI, String> repoAnnotations = new HashMap<IRI, String>();
		System.out.println("query instruction is looking for " + this.externalFileFieldName + " == " + lookupValue);

		IRI externalVarNameIri = IRI.create(queryIriPrefix + "/variableName");
		repoAnnotations.put(externalVarNameIri, this.externalFileFieldName);
		repoAnnotations.put(iriMap.lookupAnnPropIri("label"), lookupValue);

		// If looking up by abbreviation for example this will return the IRI of the abbreviation individual
		Set<IRI> resultSet = iriRepository.queryIris(null, repoAnnotations);
		int resultCount = resultSet.size();
		if (resultCount > 1 || resultCount == 0) {
			//throw new RuntimeException("resultSet should be size 1, but got " + resultCount);
			System.err.println("resultSet size should be 1, but is " + resultCount);
			System.err.println("\tlookup variable is " + this.lookupValueFieldName);
			System.err.println("\tlookup value is " + lookupValue);

		}
		if (resultCount == 0) return;
		//OWLNamedIndividual oni = (resultCount == 1) ?
		//	odf.getOWLNamedIndividual(resultSet.iterator().next()) :
		//	null;
		// Once we have the IRI for the abbreviation, we need to get the ID annotation off that individual
		//  So this class needs the unique ID field for the schema of the type of data object passed in
		IRI uniqueFieldIri = IRI.create(queryIriPrefix + "/" + this.lookupUniqueIdFieldName);
		IRI individualIri = resultSet.iterator().next();
		Set<String> resultSetString = iriRepository.queryAnnotationValueForIri(individualIri, uniqueFieldIri);

		String idValue = resultSetString.iterator().next();
		resultCount = resultSetString.size();
		if (resultCount > 1) {
			//throw new RuntimeException("resultSet should be size 1, but got " + resultCount);
			System.err.println("resultSet size should be 1, but is " + resultCount);
			System.err.println("\tlookup annotation IRI is " + uniqueFieldIri);
			System.err.println("\tlookup individual IRI is " + individualIri);

		}
		//  Then we'll ask for row individual with ID field set to value we got back from previous query
		HashMap<IRI, String> repoAnnotations2 = new HashMap<IRI, String>();
		repoAnnotations2.put(uniqueFieldIri, idValue);
		repoAnnotations2.put(externalVarNameIri, "row individual");
		resultSet = iriRepository.queryIris(null, repoAnnotations2);
		resultCount = resultSet.size();
		if (resultCount > 1) {
			//throw new RuntimeException("resultSet should be size 1, but got " + resultCount);
			System.err.println("resultSet size should be 1, but is " + resultCount);
			System.err.println("\tlookup variable is " + this.lookupUniqueIdFieldName);
			System.err.println("\tlookup value is " + idValue);

		}

		OWLNamedIndividual oni = (resultCount > 0) ?
			odf.getOWLNamedIndividual(resultSet.iterator().next()) :
			null;

		System.err.println("for " + this.lookupValueFieldName + " == " + lookupValue + ", returning IRI == " + oni.getIRI());
		//System.out.println("Adding the following to variables: " + variableName + "\t" + oni);
		if (oni != null) variables.put(variableName, oni);
		//iriRepository.addIris(oni.getIRI(), null, repoAnnotations);
	}

	/*
	 *	So right now we just do transformations to upper case or lower case.
	 *   Future modifications could also remove punctuation like . , ( ) : ; ' " { } [ ] \ / | + - * & ^ % $ # @ ! ~ ` < > ?
	 *   with various levels of granular control.
	 */
	protected String processSearchInstructions(String lookupValue) {
		String processedValue = lookupValue;
		if (this.searchInstructions != null) {
			for (String instruction : this.searchInstructions) {
				String[] components = instruction.split(Pattern.quote(";"));
				String theInstructionItself = components[0];
				switch (theInstructionItself) {
					case "uppercase":
						processedValue = processedValue.toUpperCase();
						break;
					case "lowercase":
						processedValue = processedValue.toLowerCase();
						break;
					case "removeword":
						String beginning = components[1]+" ";
						String end = " "+components[1];
						String beginningUpper = beginning.toUpperCase();
						String beginningLower = beginning.toLowerCase();
						String endUpper = end.toUpperCase();
						String endLower = end.toLowerCase();
						processedValue = processedValue.replace(beginning,"").replace(end,"").replace(beginningUpper,"")
							.replace(beginningLower,"").replace(endUpper,"").replace(endLower,"");
						break;
					default:
						System.err.println("don't understand search instruction " + instruction);
						break;
				}
			}

		}
		return processedValue;
	}
}


text:
Deface::Override.new(
    :virtual_path => 'issues/new',
    :name => 'issues_new_watchers',
    :replace => 'p#watchers_form',
    :partial => 'simple/issues/watchers_form')


text:
namespace media {
#if !defined(ARCH_CPU_ARM_FAMILY) && !defined(ARCH_CPU_MIPS_FAMILY)
// Size of raw image.
static const int kSourceWidth = 640;
static const int kSourceHeight = 360;
static const int kSourceYSize = kSourceWidth * kSourceHeight;
static const int kSourceUOffset = kSourceYSize;
static const int kSourceVOffset = kSourceYSize * 5 / 4;
static const int kBpp = 4;

// Width of the row to convert. Odd so that we exercise the ending
// one-pixel-leftover case.
static const int kWidth = 639;

// Surface sizes for various test files.
static const int kYUV12Size = kSourceYSize * 12 / 8;
static const int kRGBSize = kSourceYSize * kBpp;

static const int kPerfTestIterations = 2000;

class YUVConvertPerfTest : public testing::Test {
 public:
  YUVConvertPerfTest()
      : yuv_bytes_(new uint8_t[kYUV12Size]),
        rgb_bytes_converted_(new uint8_t[kRGBSize]) {
    base::FilePath path;
    CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &path));
    path = path.Append(FILE_PATH_LITERAL("media"))
               .Append(FILE_PATH_LITERAL("test"))
               .Append(FILE_PATH_LITERAL("data"))
               .Append(FILE_PATH_LITERAL("bali_640x360_P420.yuv"));

    // Verify file size is correct.
    int64_t actual_size = 0;
    base::GetFileSize(path, &actual_size);
    CHECK_EQ(actual_size, kYUV12Size);

    // Verify bytes read are correct.
    int bytes_read = base::ReadFile(
        path, reinterpret_cast<char*>(yuv_bytes_.get()), kYUV12Size);

    CHECK_EQ(bytes_read, kYUV12Size);
  }

  std::unique_ptr<uint8_t[]> yuv_bytes_;
  std::unique_ptr<uint8_t[]> rgb_bytes_converted_;

 private:
  DISALLOW_COPY_AND_ASSIGN(YUVConvertPerfTest);
};

TEST_F(YUVConvertPerfTest, ConvertYUVToRGB32Row_SSE) {
  ASSERT_TRUE(base::CPU().has_sse());

  base::TimeTicks start = base::TimeTicks::Now();
  for (int i = 0; i < kPerfTestIterations; ++i) {
    for (int row = 0; row < kSourceHeight; ++row) {
      int chroma_row = row / 2;
      ConvertYUVToRGB32Row_SSE(
          yuv_bytes_.get() + row * kSourceWidth,
          yuv_bytes_.get() + kSourceUOffset + (chroma_row * kSourceWidth / 2),
          yuv_bytes_.get() + kSourceVOffset + (chroma_row * kSourceWidth / 2),
          rgb_bytes_converted_.get(),
          kWidth,
          GetLookupTable(YV12));
    }
  }
  media::EmptyRegisterState();
  double total_time_seconds = (base::TimeTicks::Now() - start).InSecondsF();
  perf_test::PrintResult(
      "yuv_convert_perftest", "", "ConvertYUVToRGB32Row_SSE",
      kPerfTestIterations / total_time_seconds, "runs/s", true);
}

#ifdef HAS_I422TOARGBROW_SSSE3
TEST_F(YUVConvertPerfTest, I422ToARGBRow_SSSE3) {
  ASSERT_TRUE(base::CPU().has_ssse3());

  base::TimeTicks start = base::TimeTicks::Now();
  for (int i = 0; i < kPerfTestIterations; ++i) {
    for (int row = 0; row < kSourceHeight; ++row) {
      int chroma_row = row / 2;
      libyuv::I422ToARGBRow_SSSE3(
          yuv_bytes_.get() + row * kSourceWidth,
          yuv_bytes_.get() + kSourceUOffset + (chroma_row * kSourceWidth / 2),
          yuv_bytes_.get() + kSourceVOffset + (chroma_row * kSourceWidth / 2),
          rgb_bytes_converted_.get(), &libyuv::kYuvI601Constants, kWidth);
    }
  }
  double total_time_seconds = (base::TimeTicks::Now() - start).InSecondsF();
  perf_test::PrintResult("yuv_convert_perftest", "", "I422ToARGBRow_SSSE3",
                         kPerfTestIterations / total_time_seconds, "runs/s",
                         true);
}
#endif

TEST_F(YUVConvertPerfTest, ConvertYUVAToARGBRow_MMX) {
  ASSERT_TRUE(base::CPU().has_sse());

  base::TimeTicks start = base::TimeTicks::Now();
  for (int i = 0; i < kPerfTestIterations; ++i) {
    for (int row = 0; row < kSourceHeight; ++row) {
      int chroma_row = row / 2;
      ConvertYUVAToARGBRow_MMX(
          yuv_bytes_.get() + row * kSourceWidth,
          yuv_bytes_.get() + kSourceUOffset + (chroma_row * kSourceWidth / 2),
          yuv_bytes_.get() + kSourceVOffset + (chroma_row * kSourceWidth / 2),
          yuv_bytes_.get() + row * kSourceWidth,  // hack: use luma for alpha
          rgb_bytes_converted_.get(), kWidth, GetLookupTable(YV12));
    }
  }
  media::EmptyRegisterState();
  double total_time_seconds = (base::TimeTicks::Now() - start).InSecondsF();
  perf_test::PrintResult("yuv_convert_perftest", "", "ConvertYUVAToARGBRow_MMX",
                         kPerfTestIterations / total_time_seconds, "runs/s",
                         true);
}

#ifdef HAS_I422ALPHATOARGBROW_SSSE3
TEST_F(YUVConvertPerfTest, I422AlphaToARGBRow_SSSE3) {
  ASSERT_TRUE(base::CPU().has_ssse3());

  base::TimeTicks start = base::TimeTicks::Now();
  for (int i = 0; i < kPerfTestIterations; ++i) {
    for (int row = 0; row < kSourceHeight; ++row) {
      int chroma_row = row / 2;
      libyuv::I422AlphaToARGBRow_SSSE3(
          yuv_bytes_.get() + row * kSourceWidth,
          yuv_bytes_.get() + kSourceUOffset + (chroma_row * kSourceWidth / 2),
          yuv_bytes_.get() + kSourceVOffset + (chroma_row * kSourceWidth / 2),
          yuv_bytes_.get() + row * kSourceWidth,  // hack: use luma for alpha
          rgb_bytes_converted_.get(), &libyuv::kYuvI601Constants, kWidth);
    }
  }
  double total_time_seconds = (base::TimeTicks::Now() - start).InSecondsF();
  perf_test::PrintResult("yuv_convert_perftest", "", "I422AlphaToARGBRow_SSSE3",
                         kPerfTestIterations / total_time_seconds, "runs/s",
                         true);
}
#endif

// 64-bit release + component builds on Windows are too smart and optimizes
// away the function being tested.
#if defined(OS_WIN) && (defined(ARCH_CPU_X86) || !defined(COMPONENT_BUILD))
TEST_F(YUVConvertPerfTest, ScaleYUVToRGB32Row_SSE) {
  ASSERT_TRUE(base::CPU().has_sse());

  const int kSourceDx = 80000;  // This value means a scale down.

  base::TimeTicks start = base::TimeTicks::Now();
  for (int i = 0; i < kPerfTestIterations; ++i) {
    for (int row = 0; row < kSourceHeight; ++row) {
      int chroma_row = row / 2;
      ScaleYUVToRGB32Row_SSE(
          yuv_bytes_.get() + row * kSourceWidth,
          yuv_bytes_.get() + kSourceUOffset + (chroma_row * kSourceWidth / 2),
          yuv_bytes_.get() + kSourceVOffset + (chroma_row * kSourceWidth / 2),
          rgb_bytes_converted_.get(),
          kWidth,
          kSourceDx,
          GetLookupTable(YV12));
    }
  }
  media::EmptyRegisterState();
  double total_time_seconds = (base::TimeTicks::Now() - start).InSecondsF();
  perf_test::PrintResult(
      "yuv_convert_perftest", "", "ScaleYUVToRGB32Row_SSE",
      kPerfTestIterations / total_time_seconds, "runs/s", true);
}

TEST_F(YUVConvertPerfTest, LinearScaleYUVToRGB32Row_SSE) {
  ASSERT_TRUE(base::CPU().has_sse());

  const int kSourceDx = 80000;  // This value means a scale down.

  base::TimeTicks start = base::TimeTicks::Now();
  for (int i = 0; i < kPerfTestIterations; ++i) {
    for (int row = 0; row < kSourceHeight; ++row) {
      int chroma_row = row / 2;
      LinearScaleYUVToRGB32Row_SSE(
          yuv_bytes_.get() + row * kSourceWidth,
          yuv_bytes_.get() + kSourceUOffset + (chroma_row * kSourceWidth / 2),
          yuv_bytes_.get() + kSourceVOffset + (chroma_row * kSourceWidth / 2),
          rgb_bytes_converted_.get(),
          kWidth,
          kSourceDx,
          GetLookupTable(YV12));
    }
  }
  media::EmptyRegisterState();
  double total_time_seconds = (base::TimeTicks::Now() - start).InSecondsF();
  perf_test::PrintResult(
      "yuv_convert_perftest", "", "LinearScaleYUVToRGB32Row_SSE",
      kPerfTestIterations / total_time_seconds, "runs/s", true);
}
#endif  // defined(OS_WIN) && (ARCH_CPU_X86 || COMPONENT_BUILD)

#endif  // !defined(ARCH_CPU_ARM_FAMILY) && !defined(ARCH_CPU_MIPS_FAMILY)

}  // namespace media


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/spf13/cobra"

	"istio.io/istio/pkg/log"
	"istio.io/istio/pkg/test/fakes/policy"
)

var (
	port       int
	address    string
	logOptions *log.Options
)

func main() {

	rootCmd := &cobra.Command{
		Use:          "policybackend",
		Short:        "Fake Policy Backend.",
		SilenceUsage: true,
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			if len(args) > 0 {
				return fmt.Errorf("'%s' is an invalid argument", args[0])
			}
			return nil
		},
	}

	serviceCmd := &cobra.Command{
		Use:          "server",
		Short:        "Start backend as server.",
		SilenceUsage: true,
		Run: func(cmd *cobra.Command, args []string) {
			runServer()
		},
	}
	rootCmd.AddCommand(serviceCmd)

	resetCmd := &cobra.Command{
		Use:          "reset",
		Short:        "Reset a target Policy Backend.",
		SilenceUsage: true,
		Run: func(cmd *cobra.Command, args []string) {
			runReset()
		},
	}
	rootCmd.AddCommand(resetCmd)

	rootCmd.SetArgs(os.Args[1:])
	rootCmd.PersistentFlags().AddGoFlagSet(flag.CommandLine)

	logOptions = log.DefaultOptions()
	logOptions.AttachCobraFlags(rootCmd)

	rootCmd.PersistentFlags().IntVar(&port, "port", policy.DefaultPort, "GRPC port")
	rootCmd.PersistentFlags().StringVar(&address, "address", "", "Address of the service")

	if err := rootCmd.Execute(); err != nil {
		fmt.Printf("Error during execution: %v", err)
		os.Exit(-1)
	}
}

func runServer() {
	if err := log.Configure(logOptions); err != nil {
		os.Exit(-1)
	}
	log.Infof("Starting up the policy backend: %v", port)

	b := policy.NewPolicyBackend(port)

	if err := b.Start(); err != nil {
		log.Errora(err)
		os.Exit(-1)
	}

	// Wait for the process to be shutdown.
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	<-sigs
}

func runReset() {
	if err := log.Configure(logOptions); err != nil {
		os.Exit(-1)
	}

	controller, err := policy.NewController(address)
	if err != nil {
		os.Exit(-1)
	}

	if err := controller.Reset(); err != nil {
		os.Exit(-1)
	}
}


text:
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Remote jGallery • Example</title>

Remote jGallery • Example

In this you can see the result of the script with some css applied.


text:
namespace Google.Cloud.Domains.V1.Snippets
{
    // [START domains_v1_generated_Domains_ListRegistrations_async_flattened]
    using Google.Api.Gax;
    using Google.Cloud.Domains.V1;
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDomainsClientSnippets
    {
        /// <summary>Snippet for ListRegistrationsAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task ListRegistrationsAsync()
        {
            // Create client
            DomainsClient domainsClient = await DomainsClient.CreateAsync();
            // Initialize request argument(s)
            string parent = "projects/[PROJECT]/locations/[LOCATION]";
            // Make the request
            PagedAsyncEnumerable<ListRegistrationsResponse, Registration> response = domainsClient.ListRegistrationsAsync(parent);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Registration item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListRegistrationsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Registration item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Registration> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Registration item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END domains_v1_generated_Domains_ListRegistrations_async_flattened]
}


text:
package org.dflow.compiler.tojava.language;

import java.util.LinkedList;
import java.util.List;

import org.dflow.compiler.io.writing.Writeable;
import org.dflow.compiler.io.writing.Writer;

public class Argument implements Writeable, Annotated {

	private final Type type;
	private final String name;

	private final List<Annotation> annotations = new LinkedList<>();

	public Argument(Type type, String name) {
		this.type = type;
		this.name = name;
	}

	public Type getType() {
		return type;
	}

	public String getName() {
		return name;
	}

	@Override
	public Argument addAnnotation(Annotation annotation) {
		annotations.add(annotation);
		return this;
	}

	@Override
	public String toString() {
		return getName();
	}

	@Override
	public void write(Writer writer) {
		for (Annotation a : annotations) {
			writer.write(a).write(" ");
		}

		writer.write(getType()).write(getName());
	}

}


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

#import <Foundation/Foundation.h>

/// Encapsulates the interaction with an interpreter for running scripts.
// This class manages the interaction with some command-line interpreter (e.g.,
// a shell, perl, python) and allows you to run expressions through the
// interpreter, and even full scripts that reside in files on disk.  By default,
// the "/bin/sh" interpreter is used, but others may be explicitly specified.
// This can be a convenient way to run quick shell commands from Cocoa, or even
// interact with other shell tools such as "bc", or even "gdb".
//
// It's important to note that by default commands and scripts will have their
// environments erased before execution. You can control the environment they
// get with the -setEnvironment: method.
//
// The best way to show what this class does is to show some examples.
//
// Examples:
//
// GTMScriptRunner *sr = [GTMScriptRunner runner];
// NSString *output = [sr run:@"ls -l /dev/null"];
// /* output == "crw-rw-rw-   1 root  wheel    3,   2 Mar 22 10:35 /dev/null" */
//
// GTMScriptRunner *sr = [GTMScriptRunner runner];
// NSString *output = [sr runScript:@"/path/to/my/script.sh"];
// /* output == the standard output from the script*/
//
// GTMScriptRunner *sr = [GTMScriptRunner runnerWithPerl];
// NSString *output = [sr run:@"print 'A'x4"];
// /* output == "AAAA" */
//
// See the unit test file for more examples.
//
@interface GTMScriptRunner : NSObject {
 @private
  NSString *interpreter_;
  NSArray  *interpreterArgs_;
  NSDictionary *environment_;
  BOOL trimsWhitespace_;
}

// Convenience methods for returning autoreleased GTMScriptRunner instances, that
// are associated with the specified interpreter.  The default interpreter
// (returned from +runner is "/bin/sh").
+ (GTMScriptRunner *)runner;
+ (GTMScriptRunner *)runnerWithBash;
+ (GTMScriptRunner *)runnerWithPerl;
+ (GTMScriptRunner *)runnerWithPython;

// Returns an autoreleased GTMScriptRunner instance associated with the specified
// interpreter, and the given args.  The specified args are the arguments that
// should be applied to the interpreter itself, not scripts run through the
// interpreter.  For example, to start an interpreter using "perl -w", you could
// do:
//   [GTMScriptRunner runnerWithInterpreter:@"/usr/bin/perl"
//                                withArgs:[NSArray arrayWithObject:@"-w"]];
//
+ (GTMScriptRunner *)runnerWithInterpreter:(NSString *)interp;
+ (GTMScriptRunner *)runnerWithInterpreter:(NSString *)interp
                                  withArgs:(NSArray *)args;

// Returns a GTMScriptRunner associated with |interp|
- (id)initWithInterpreter:(NSString *)interp;

// Returns a GTMScriptRunner associated with |interp| and |args| applied to the
// specified interpreter.  This method is the designated initializer.
- (id)initWithInterpreter:(NSString *)interp withArgs:(NSArray *)args;

// Runs the specified command string by sending it through the interpreter's
// standard input.  The standard output is returned.  The standard error is
// discarded.
- (NSString *)run:(NSString *)cmds;
// Same as the previous method, except the standard error is returned in |err|
// if specified.
- (NSString *)run:(NSString *)cmds standardError:(NSString **)err;

// Runs the file at |path| using the interpreter.
- (NSString *)runScript:(NSString *)path;
// Runs the file at |path|, passing it |args| as arguments.
- (NSString *)runScript:(NSString *)path withArgs:(NSArray *)args;
// Same as above, except the standard error is returned in |err| if specified.
- (NSString *)runScript:(NSString *)path withArgs:(NSArray *)args
          standardError:(NSString **)err;

// Returns the environment dictionary to use for the inferior process that will
// run the interpreter. A return value of nil means that the interpreter's
// environment should be erased.
- (NSDictionary *)environment;

// Sets the environment dictionary to use for the interpreter process. See
// NSTask's -setEnvironment: documentation for details about the dictionary.
// Basically, it's just a dict of key/value pairs corresponding to environment
// keys and values. Setting a value of nil means that the environment should be
// erased before running the interpreter.
//
// *** The default is nil. ***
//
// By default, all interpreters will run with a clean environment. If you want
// the interpreter process to inherit your current environment you'll need to
// do the following:
//
// GTMScriptRunner *sr = [GTMScriptRunner runner];
// [sr setEnvironment:[[NSProcessInfo processInfo] environment]];
//
// SECURITY NOTE: That said, in general you should NOT do this because an
// attacker can modify the environment that would then get sent to your scripts.
// And if your binary is suid, then  you ABSOLUTELY should not do this.
//
- (void)setEnvironment:(NSDictionary *)newEnv;

// Sets (and returns) whether or not whitespace is automatically trimmed from
// the ends of the returned strings.  The default is YES, so trailing newlines
// will be removed.
- (BOOL)trimsWhitespace;
- (void)setTrimsWhitespace:(BOOL)trim;

@end


text:
if(Meteor.isClient){

  // ReactiveDict - status of completion defined here
  Template.MasterTemplate.onCreated( function (){

    this.showResult = new ReactiveDict();
    this.showResult.set('message', "N/A");
    //console.log(this.showResult);
  });
  // Get the state of ReactiveDict
  Template.MasterTemplate.helpers({
    state : function(){
      //console.log(Template.instance().showResult.get('message'));
      return Template.instance().showResult.get('message');

    }

  });
  //Submission Event handling and mapping answers
  Template.MasterTemplate.events({
    'submit form': function(event, template){
      event.preventDefault();
      var exercisesID = event.target.exercisesID.value
      var selected = template.findAll( "input[type=checkbox]:checked");
      var array = _.map(selected, function(item) {
        return item.defaultValue;
      });

      //console.log(array);
      //console.log(exercisesID);

    }
  });

  Template.MasterTemplate.events({

    'submit form': function(event, template){
      event.preventDefault();
      var exercisesID = event.target.exercisesID.value;
      var type = event.target.type.value;

      function test (){
        Meteor.call('verifyExercise', array, exercisesID, function (error, result){
          if (result) {
            console.log("Correct!");
            template.showResult.set('message', {
              text : "Good Job!",
              type : "alert-success"
            });
            //console.log(Template.instance().showResult.get('message'));
          } else {
            console.log("You got it Wrong!");
            template.showResult.set('message', {
              text: "Not quite right. Try another time!",
              type: "alert-danger"
            });
            //console.log(Template.instance().showResult.get('message'));

          }
          console.log(error);
        });
      }

      // Exercise Correction Mechanism
      switch (type) {
        case "matching":
        console.log(type);

        var selected = template.findAll( "input[type=radio]:checked");
        var array = _.map(selected, function(item){
          return [item.value, item.name]
        });
        test();
        break;

        case "Listening-matching":
        console.log(type);

        var selected = template.findAll( "input[type=radio]:checked");
        var array = _.map(selected, function(item){
          return [item.value, item.name]
        });
        test();

        break;

        case "odd-one-out":

        var selected = template.findAll( "input[type=radio]:checked");
        var array = _.map(selected, function(item) {
          return item.defaultValue;
        });

        console.log(array);
        console.log(exercisesID);
        test();

        break;
      }
    }}
  );

}


text:
package me.anchore.io.nio;

import me.anchore.io.LongIo;
import me.anchore.io.nio.NioConf.IoType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * @author anchore
 * @date 2018/7/21
 */
public class LongIoTest extends BaseIoTest {

    @Before
    public void setUp() {
        pageSize = 5;
    }

    @Test
    public void test() {
        LongIo io = new LongNio(new NioConf(path, IoType.OVERWRITE, pageSize, pageSize, false));
        for (int i = 0; i < data.length; i++) {
            io.putLong(i, data[i]);
        }
        io.release();
        io = new LongNio(new NioConf(path, IoType.READ, pageSize, pageSize, false));
        for (int i = 0; i < data.length; i++) {
            Assert.assertEquals(data[i], io.getLong(i));
        }
        io.release();

        io = new LongNio(new NioConf(path, IoType.OVERWRITE, pageSize, pageSize, false));
        io.putLong(2, 5);
        io.putLong(9, 4);
        io.release();
        io = new LongNio(new NioConf(path, IoType.OVERWRITE, pageSize, pageSize, false));
        for (int i = 0; i < data.length; i++) {
            if (i == 2) {
                Assert.assertEquals(5, io.getLong(i));
                continue;
            }
            if (i == 9) {
                Assert.assertEquals(4, io.getLong(i));
                continue;
            }
            Assert.assertEquals(data[i], io.getLong(i));
        }
        io.release();
    }
}


text:
#![deny(warnings)]
#![deny(rust_2018_idioms)]
#![deny(clippy::all)]

mod artifact_map;
pub mod build_project;
pub mod compiler;
pub mod compiler_state;
pub mod config;
pub mod errors;
mod file_source;
mod graphql_asts;
mod operation_persister;
mod red_to_green;
pub mod saved_state;
pub mod status_reporter;

pub use build_project::{
    add_to_mercurial,
    artifact_writer::{
        ArtifactDifferenceWriter, ArtifactFileWriter, ArtifactValidationWriter, ArtifactWriter,
        NoopArtifactWriter,
    },
    build_programs, build_raw_program, build_schema, create_path_for_artifact, generate_artifacts,
    generate_extra_artifacts::GenerateExtraArtifactsFn,
    path_for_artifact, transform_program, validate, validate_program, AdditionalValidations,
    Artifact, ArtifactContent, ArtifactGeneratedTypes, BuildProjectFailure, SourceHashes,
};
pub use config::{
    ConfigFileProject, FileSourceKind, LocalPersistConfig, OperationPersister, PersistConfig,
    ProjectConfig, RemotePersistConfig, SchemaLocation,
};
pub use file_source::{
    source_for_location, FileCategorizer, FileGroup, FileSource, FileSourceResult,
    FileSourceSubscription, FileSourceSubscriptionNextChange, FsSourceReader,
    SourceControlUpdateStatus, SourceReader,
};
pub use graphql_asts::GraphQLAsts;
pub use operation_persister::{LocalPersister, RemotePersister};


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.7-6-a-12
description: >
    Object.defineProperties - 'O' is a Function object which
    implements its own [[GetOwnProperty]] method to get 'P' (8.12.9
    step 1 )
includes: [propertyHelper.js]
---*/

var fun = function () { };

Object.defineProperty(fun, "prop", {
    value: 11,
    configurable: false
});

try {
    Object.defineProperties(fun, {
        prop: {
            value: 12,
            configurable: true
        }
    });
    $ERROR("Expected an exception.");
} catch (e) {
    verifyEqualTo(fun, "prop", 11);

    verifyNotWritable(fun, "prop");

    verifyNotEnumerable(fun, "prop");

    verifyNotConfigurable(fun, "prop");

    if (!(e instanceof TypeError)) {
        $ERROR("Expected TypeError, got " + e);
    }

}


text:
This is based on an incomplete go version of the docker registry living
in upstream github.com/docker/docker-registry/contrib/golang_impl and
heavily reworked to be usable.

FOR TLS SUPPORT TESTING:

$ curl -siv "https://registry:5050/v1/_ping" --cacert ./tls/root.cer

echo -n "username:password" | base64

now edit .dockercfg manually

	"https://localhost:5050/" : {
		"username" : "USERNAME",
		"auth":"BASE64"
	}


text:
namespace elsa {
	namespace vm {

		CallStack::CallStack()
		{
		}

		CallStack::~CallStack()
		{
			while (stack_.size() > 0)
			{
				delete stack_.back();
				stack_.pop_back();
			}
		}

		void CallStack::push(StackFrame* frame)
		{
			stack_.push_back(frame);
		}

		StackFrame* CallStack::pop()
		{
			if (stack_.size() == 0)
				throw RuntimeException("Can not call pop on an empty call stack.");

			auto last = stack_.back();
			stack_.pop_back();

			return last;
		}

		std::size_t CallStack::size()
		{
			return stack_.size();
		}

		StackFrame* CallStack::current()
		{
			return stack_.back();
		}

		void CallStack::dump_stack_trace()
		{
			for (int i = static_cast<int>(stack_.size()) - 1; i >= 0; --i)
			{
				const auto fi = stack_[i]->get_function_info();
				std::wcout << fi->get_name() << L" at: " << fi->get_addr() << std::endl;
			}
		}
	}
}


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Generate .stp file that outputs simpletrace binary traces (DTrace with SystemTAP only).
"""

__author__     = "Stefan Hajnoczi <redhat.com>"
__copyright__  = "Copyright (C) 2014, Red Hat, Inc."
__license__    = "GPL version 2 or (at your option) any later version"

__maintainer__ = "Stefan Hajnoczi"
__email__      = "stefanha@redhat.com"

from tracetool import out
from tracetool.backend.dtrace import binary, probeprefix
from tracetool.backend.simple import is_string
from tracetool.format.stap import stap_escape

def generate(events, backend):
    out('/* This file is autogenerated by tracetool, do not edit. */',
        '')

    for event_id, e in enumerate(events):
        if 'disable' in e.properties:
            continue

        out('probe %(probeprefix)s.simpletrace.%(name)s = %(probeprefix)s.%(name)s ?',
            '{',
            probeprefix=probeprefix(),
            name=e.name)

        # Calculate record size
        sizes = ['24'] # sizeof(TraceRecord)
        for type_, name in e.args:
            name = stap_escape(name)
            if is_string(type_):
                out('    try {',
                    '        arg%(name)s_str = %(name)s ? user_string_n(%(name)s, 512) : "<null>"',
                    '    } catch {}',
                    '    arg%(name)s_len = strlen(arg%(name)s_str)',
                    name=name)
                sizes.append('4 + arg%s_len' % name)
            else:
                sizes.append('8')
        sizestr = ' + '.join(sizes)

        # Generate format string and value pairs for record header and arguments
        fields = [('8b', str(event_id)),
                  ('8b', 'gettimeofday_ns()'),
                  ('4b', sizestr),
                  ('4b', 'pid()')]
        for type_, name in e.args:
            name = stap_escape(name)
            if is_string(type_):
                fields.extend([('4b', 'arg%s_len' % name),
                               ('.*s', 'arg%s_len, arg%s_str' % (name, name))])
            else:
                fields.append(('8b', name))

        # Emit the entire record in a single SystemTap printf()
        fmt_str = '%'.join(fmt for fmt, _ in fields)
        arg_str = ', '.join(arg for _, arg in fields)
        out('    printf("%%%(fmt_str)s", %(arg_str)s)',
            fmt_str=fmt_str, arg_str=arg_str)

        out('}')

    out()


text:
--------------------------------
-- Change the clipping type of layout.

-- On default, the clipping type is `ClippingType::STENCIL`.

-- see `ClippingType`

-- param type The clipping type of layout.
-- @function [parent=#Layout] setClippingType
-- @param self
-- @param #int type
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Sets Color Type for layout's background

-- param type   @see `BackGroundColorType`
-- @function [parent=#Layout] setBackGroundColorType
-- @param self
-- @param #int type
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- If a layout is loop focused which means that the focus movement will be inside the layout

-- param loop  pass true to let the focus movement loop inside the layout
-- @function [parent=#Layout] setLoopFocus
-- @param self
-- @param #bool loop
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Set layout's background image color.

-- param color Background color value in `Color3B`.
-- @function [parent=#Layout] setBackGroundImageColor
-- @param self
-- @param #color3b_table color
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Get the layout's background color vector.

-- return Background color vector.
-- @function [parent=#Layout] getBackGroundColorVector
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)

--------------------------------
-- see `setClippingType(ClippingType)`
-- @function [parent=#Layout] getClippingType
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
--
-- @function [parent=#Layout] getRenderFile
-- @param self
-- @return ResourceData#ResourceData ret (return value: cc.ResourceData)

--------------------------------
-- return If focus loop is enabled, then it will return true, otherwise it returns false. The default value is false.
-- @function [parent=#Layout] isLoopFocus
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- Remove the background image of layout.
-- @function [parent=#Layout] removeBackGroundImage
-- @param self
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Get the layout's background color opacity.

-- return Background color opacity value.
-- @function [parent=#Layout] getBackGroundColorOpacity
-- @param self
-- @return unsigned char#unsigned char ret (return value: unsigned char)

--------------------------------
-- Gets if layout is clipping enabled.

-- return if layout is clipping enabled.
-- @function [parent=#Layout] isClippingEnabled
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- Set opacity of background image.

-- param opacity Background image opacity in GLubyte.
-- @function [parent=#Layout] setBackGroundImageOpacity
-- @param self
-- @param #unsigned char opacity
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Sets a background image for layout.

-- param fileName image file path.

-- param texType @see TextureResType.
-- @function [parent=#Layout] setBackGroundImage
-- @param self
-- @param #string fileName
-- @param #int texType
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- @overload self, color3b_table, color3b_table
-- @overload self, color3b_table
-- @function [parent=#Layout] setBackGroundColor
-- @param self
-- @param #color3b_table startColor
-- @param #color3b_table endColor
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- request to refresh widget layout
-- @function [parent=#Layout] requestDoLayout
-- @param self
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Query background image's capInsets size.

-- return The background image capInsets.
-- @function [parent=#Layout] getBackGroundImageCapInsets
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)

--------------------------------
-- Query the layout's background color.

-- return Background color in Color3B.
-- @function [parent=#Layout] getBackGroundColor
-- @param self
-- @return color3b_table#color3b_table ret (return value: color3b_table)

--------------------------------
-- Toggle layout clipping.

-- If you do need clipping, you pass true to this function.

-- param enabled Pass true to enable clipping, false otherwise.
-- @function [parent=#Layout] setClippingEnabled
-- @param self
-- @param #bool enabled
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Get color of layout's background image.

-- return Layout's background image color.
-- @function [parent=#Layout] getBackGroundImageColor
-- @param self
-- @return color3b_table#color3b_table ret (return value: color3b_table)

--------------------------------
-- Query background image scale9 enable status.

-- return Whether background image is scale9 enabled or not.
-- @function [parent=#Layout] isBackGroundImageScale9Enabled
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- Query the layout's background color type.

-- return The layout's background color type.
-- @function [parent=#Layout] getBackGroundColorType
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
-- Get the gradient background end color.

-- return Gradient background end color value.
-- @function [parent=#Layout] getBackGroundEndColor
-- @param self
-- @return color3b_table#color3b_table ret (return value: color3b_table)

--------------------------------
-- Sets background color opacity of layout.

-- param opacity The opacity in `GLubyte`.
-- @function [parent=#Layout] setBackGroundColorOpacity
-- @param self
-- @param #unsigned char opacity
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Get the opacity of layout's background image.

-- return The opacity of layout's background image.
-- @function [parent=#Layout] getBackGroundImageOpacity
-- @param self
-- @return unsigned char#unsigned char ret (return value: unsigned char)

--------------------------------
-- return To query whether the layout will pass the focus to its children or not. The default value is true
-- @function [parent=#Layout] isPassFocusToChild
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- Sets a background image capinsets for layout, it only affects the scale9 enabled background image

-- param capInsets  The capInsets in Rect.
-- @function [parent=#Layout] setBackGroundImageCapInsets
-- @param self
-- @param #rect_table capInsets
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Gets background image texture size.

-- return background image texture size.
-- @function [parent=#Layout] getBackGroundImageTextureSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
-- force refresh widget layout
-- @function [parent=#Layout] forceDoLayout
-- @param self
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Query layout type.

-- return Get the layout type.
-- @function [parent=#Layout] getLayoutType
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
-- param pass To specify whether the layout pass its focus to its child
-- @function [parent=#Layout] setPassFocusToChild
-- @param self
-- @param #bool pass
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Get the gradient background start color.

-- return  Gradient background start color value.
-- @function [parent=#Layout] getBackGroundStartColor
-- @param self
-- @return color3b_table#color3b_table ret (return value: color3b_table)

--------------------------------
-- Enable background image scale9 rendering.

-- param enabled  True means enable scale9 rendering for background image, false otherwise.
-- @function [parent=#Layout] setBackGroundImageScale9Enabled
-- @param self
-- @param #bool enabled
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Change the layout type.

-- param type Layout type.
-- @function [parent=#Layout] setLayoutType
-- @param self
-- @param #int type
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Create a empty layout.
-- @function [parent=#Layout] create
-- @param self
-- @return Layout#Layout ret (return value: ccui.Layout)

--------------------------------
--
-- @function [parent=#Layout] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)

--------------------------------
-- @overload self, cc.Node, int
-- @overload self, cc.Node
-- @overload self, cc.Node, int, int
-- @overload self, cc.Node, int, string
-- @function [parent=#Layout] addChild
-- @param self
-- @param #cc.Node child
-- @param #int localZOrder
-- @param #string name
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Returns the "class name" of widget.
-- @function [parent=#Layout] getDescription
-- @param self
-- @return string#string ret (return value: string)

--------------------------------
-- Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter.

-- param cleanup   true if all running actions on all children nodes should be cleanup, false otherwise.

-- js removeAllChildren

-- lua removeAllChildren
-- @function [parent=#Layout] removeAllChildrenWithCleanup
-- @param self
-- @param #bool cleanup
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Removes all children from the container with a cleanup.

-- see `removeAllChildrenWithCleanup(bool)`
-- @function [parent=#Layout] removeAllChildren
-- @param self
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- When a widget is in a layout, you could call this method to get the next focused widget within a specified direction.

-- If the widget is not in a layout, it will return itself

-- param direction the direction to look for the next focused widget in a layout

-- param current  the current focused widget

-- return the next focused widget in a layout
-- @function [parent=#Layout] findNextFocusedWidget
-- @param self
-- @param #int direction
-- @param #ccui.Widget current
-- @return Widget#Widget ret (return value: ccui.Widget)

--------------------------------
--
-- @function [parent=#Layout] removeChild
-- @param self
-- @param #cc.Node child
-- @param #bool cleanup
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
--
-- @function [parent=#Layout] init
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- Override function. Set camera mask, the node is visible by the camera whose camera flag & node's camera mask is true.

-- param mask Mask being set

-- param applyChildren If true call this function recursively from this node to its children.
-- @function [parent=#Layout] setCameraMask
-- @param self
-- @param #unsigned short mask
-- @param #bool applyChildren
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
--
-- @function [parent=#Layout] setGlobalZOrder
-- @param self
-- @param #float globalZOrder
-- @return Layout#Layout self (return value: ccui.Layout)

--------------------------------
-- Default constructor

-- js ctor

-- lua new
-- @function [parent=#Layout] Layout
-- @param self
-- @return Layout#Layout self (return value: ccui.Layout)

return nil


text:
// <copyright file="IBatchObject.cs" company="Glenn Watson">
// Copyright (c) 2018 Glenn Watson. All rights reserved.
// See LICENSE file in the project root for full license information.
// </copyright>

namespace GitLfs.Core.BatchResponse
{
    /// <summary>
    /// A batch object returned or sent to a LFS server.
    /// </summary>
    public interface IBatchObject
    {
        /// <summary>
        /// Gets or sets the id of the batch object.
        /// </summary>
        ObjectId Id { get; set; }
    }
}


text:
// Qt includes
#include <QAbstractScrollArea>
#include <QApplication>
#include <QDebug>
#include <QScrollBar>
#include <QStylePainter>
#include <QWheelEvent>

// CTK includes
#include "ctkComboBox.h"

// -------------------------------------------------------------------------
class ctkComboBoxPrivate
{
  Q_DECLARE_PUBLIC(ctkComboBox);
protected:
  ctkComboBox* const q_ptr;
public:
  ctkComboBoxPrivate(ctkComboBox& object);
  void initStyleOption(QStyleOptionComboBox* opt)const;
  QSize recomputeSizeHint(QSize &sh) const;
  QString DefaultText;
  QIcon   DefaultIcon;
  bool    ForceDefault;
  Qt::TextElideMode ElideMode;
  ctkComboBox::ScrollEffect ScrollWheelEffect;

  mutable QSize MinimumSizeHint;
  mutable QSize SizeHint;
};

// -------------------------------------------------------------------------
ctkComboBoxPrivate::ctkComboBoxPrivate(ctkComboBox& object)
  :q_ptr(&object)
{
  this->DefaultText = "";
  this->ForceDefault = false;
  this->ElideMode = Qt::ElideNone;
  this->ScrollWheelEffect = ctkComboBox::AlwaysScroll;
}

// -------------------------------------------------------------------------
QSize ctkComboBoxPrivate::recomputeSizeHint(QSize &sh) const
{
  Q_Q(const ctkComboBox);
  if (sh.isValid())
    {
    return sh.expandedTo(QApplication::globalStrut());
    }

  bool hasIcon = false;
  int count = q->count();
  QSize iconSize = q->iconSize();
  const QFontMetrics &fm = q->fontMetrics();

  // text width
  if (&sh == &this->SizeHint || q->minimumContentsLength() == 0)
    {
    switch (q->sizeAdjustPolicy())
      {
      case QComboBox::AdjustToContents:
      case QComboBox::AdjustToContentsOnFirstShow:
        if (count == 0 || this->ForceDefault)
          {
          #if (QT_VERSION >= QT_VERSION_CHECK(5,11,0))
          int character_pixel_width = fm.horizontalAdvance(QLatin1Char('x'));
          #else
          int character_pixel_width = fm.width(QLatin1Char('x'));
          #endif
          sh.rwidth() = this->DefaultText.isEmpty() ?
            7 * character_pixel_width :
            fm.boundingRect(this->DefaultText).width();
          if (!this->DefaultIcon.isNull())
            {
            hasIcon = true;
            sh.rwidth() += iconSize.width() + 4;
            }
          }
        for (int i = 0; i < count; ++i)
          {
          if (!q->itemIcon(i).isNull())
            {
            hasIcon = true;
            sh.setWidth(qMax(sh.width(), fm.boundingRect(q->itemText(i)).width() + iconSize.width() + 4));
            }
          else
            {
            sh.setWidth(qMax(sh.width(), fm.boundingRect(q->itemText(i)).width()));
            }
          }
        break;
      case QComboBox::AdjustToMinimumContentsLengthWithIcon:
        hasIcon = true;
        break;
      default:
        break;
      }
    }
  else // minimumsizehint is computing and minimumcontentslenght is > 0
    {
    if ((count == 0 || this->ForceDefault) && !this->DefaultIcon.isNull())
      {
      hasIcon = true;
      }

    for (int i = 0; i < count && !hasIcon; ++i)
      {
      hasIcon = !q->itemIcon(i).isNull();
      }
    }
  if (q->minimumContentsLength() > 0)
    {
    #if (QT_VERSION >= QT_VERSION_CHECK(5,11,0))
    int character_pixel_width = fm.horizontalAdvance(QLatin1Char('x'));
    #else
    int character_pixel_width = fm.width(QLatin1Char('x'));
    #endif
    sh.setWidth(qMax(sh.width(),
                     q->minimumContentsLength() * character_pixel_width
                     + (hasIcon ? iconSize.width() + 4 : 0)));
    }

  // height
  sh.setHeight(qMax(fm.height(), 14) + 2);
  if (hasIcon)
    {
    sh.setHeight(qMax(sh.height(), iconSize.height() + 2));
    }

  // add style and strut values
  QStyleOptionComboBox opt;
  this->initStyleOption(&opt);
  sh = q->style()->sizeFromContents(QStyle::CT_ComboBox, &opt, sh, q);
  return sh.expandedTo(QApplication::globalStrut());
}

// -------------------------------------------------------------------------
void ctkComboBoxPrivate::initStyleOption(QStyleOptionComboBox* opt)const
{
  Q_Q(const ctkComboBox);
  q->initStyleOption(opt);
  if (q->currentIndex() == -1 ||
      this->ForceDefault)
    {
    opt->currentText = this->DefaultText;
    opt->currentIcon = this->DefaultIcon;
    }
  QRect textRect = q->style()->subControlRect(
    QStyle::CC_ComboBox, opt, QStyle::SC_ComboBoxEditField, q);
  // TODO substract icon size
  opt->currentText = opt->fontMetrics.elidedText(opt->currentText,
                                                 this->ElideMode,
                                                 textRect.width());
}

// -------------------------------------------------------------------------
ctkComboBox::ctkComboBox(QWidget* _parent)
  : QComboBox(_parent)
  , d_ptr(new ctkComboBoxPrivate(*this))
{
}

// -------------------------------------------------------------------------
ctkComboBox::~ctkComboBox()
{
}

// -------------------------------------------------------------------------
void ctkComboBox::setDefaultText(const QString& newDefaultText)
{
  Q_D(ctkComboBox);
  d->DefaultText = newDefaultText;
  d->SizeHint = QSize();
  this->update();
}

// -------------------------------------------------------------------------
QString ctkComboBox::defaultText()const
{
  Q_D(const ctkComboBox);
  return d->DefaultText;
}

// -------------------------------------------------------------------------
void ctkComboBox::setDefaultIcon(const QIcon& newIcon)
{
  Q_D(ctkComboBox);
  d->DefaultIcon = newIcon;
  d->SizeHint = QSize();
  this->update();
}

// -------------------------------------------------------------------------
QIcon ctkComboBox::defaultIcon()const
{
  Q_D(const ctkComboBox);
  return d->DefaultIcon;
}

// -------------------------------------------------------------------------
void ctkComboBox::forceDefault(bool newForceDefault)
{
  Q_D(ctkComboBox);
  if (newForceDefault == d->ForceDefault)
    {
    return;
    }
  d->ForceDefault = newForceDefault;
  d->SizeHint = QSize();
  this->updateGeometry();
}

// -------------------------------------------------------------------------
void ctkComboBox::setElideMode(const Qt::TextElideMode& newMode)
{
  Q_D(ctkComboBox);
  d->ElideMode = newMode;
  this->update();
}
// -------------------------------------------------------------------------
Qt::TextElideMode ctkComboBox::elideMode()const
{
  Q_D(const ctkComboBox);
  return d->ElideMode;
}

// -------------------------------------------------------------------------
bool ctkComboBox::isDefaultForced()const
{
  Q_D(const ctkComboBox);
  return d->ForceDefault;
}

// -------------------------------------------------------------------------
ctkComboBox::ScrollEffect ctkComboBox::scrollWheelEffect()const
{
  Q_D(const ctkComboBox);
  return d->ScrollWheelEffect;
}

// -------------------------------------------------------------------------
void ctkComboBox::setScrollWheelEffect(ctkComboBox::ScrollEffect scroll)
{
  Q_D(ctkComboBox);
  d->ScrollWheelEffect = scroll;
  this->setFocusPolicy( d->ScrollWheelEffect == ctkComboBox::ScrollWithFocus ?
                        Qt::StrongFocus : Qt::WheelFocus );
}

// -------------------------------------------------------------------------
void ctkComboBox::paintEvent(QPaintEvent*)
{
  Q_D(ctkComboBox);
  QStylePainter painter(this);
  painter.setPen(palette().color(QPalette::Text));

  QStyleOptionComboBox opt;
  d->initStyleOption(&opt);

  // draw the combobox frame, focusrect and selected etc.
  painter.drawComplexControl(QStyle::CC_ComboBox, opt);
  // draw the icon and text
  painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}

// -------------------------------------------------------------------------
QSize ctkComboBox::minimumSizeHint() const
{
  Q_D(const ctkComboBox);
  return d->recomputeSizeHint(d->MinimumSizeHint);
}

// -------------------------------------------------------------------------
/*!
    \reimp

    This implementation caches the size hint to avoid resizing when
    the contents change dynamically. To invalidate the cached value
    change the \l sizeAdjustPolicy.
*/
QSize ctkComboBox::sizeHint() const
{
  Q_D(const ctkComboBox);
  return d->recomputeSizeHint(d->SizeHint);
}

// -------------------------------------------------------------------------
void ctkComboBox::changeEvent(QEvent *e)
{
  Q_D(const ctkComboBox);
  switch (e->type())
    {
    case QEvent::StyleChange:
    case QEvent::MacSizeChange:
    case QEvent::FontChange:
      d->SizeHint = QSize();
      d->MinimumSizeHint = QSize();
      break;
    default:
      break;
    }

  this->QComboBox::changeEvent(e);
}

// -------------------------------------------------------------------------
void ctkComboBox::wheelEvent(QWheelEvent* event)
{
  Q_D(ctkComboBox);
  bool scroll = false;
  switch (d->ScrollWheelEffect)
    {
    case AlwaysScroll:
      scroll = true;
      break;
    case ScrollWithFocus:
      scroll = this->hasFocus();
      break;
    case ScrollWithNoVScrollBar:
      scroll = true;
      for (QWidget* ancestor = this->parentWidget();
           ancestor; ancestor = ancestor->parentWidget())
        {
        if (QAbstractScrollArea* scrollArea =
            qobject_cast<QAbstractScrollArea*>(ancestor))
          {
          scroll = !scrollArea->verticalScrollBar()->isVisible();
          if (!scroll)
            {
            break;
            }
          }
        }
      break;
    default:
    case NeverScroll:
      break;
    }
  if (scroll)
    {
    this->QComboBox::wheelEvent(event);
    }
  else
    {
    event->ignore();
    }
}

// -------------------------------------------------------------------------
QString ctkComboBox::currentUserDataAsString()const
{
  return this->itemData(this->currentIndex()).toString();
}

// -------------------------------------------------------------------------
void ctkComboBox::setCurrentUserDataAsString(QString userData)
{
  for (int index=0; index<this->count(); ++index)
    {
    QString currentItemUserData = this->itemData(index).toString();
    if (!userData.compare(currentItemUserData))
      {
      this->setCurrentIndex(index);
      return;
      }
    }

  qWarning() << Q_FUNC_INFO << ": No item found with user data string " << userData;
}


text:
plumbery package
================

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

.. toctree::

    plumbery.actions
    plumbery.fittings
    plumbery.polishers

Submodules
----------

.. toctree::

   plumbery.action
   plumbery.bootstrap
   plumbery.engine
   plumbery.exception
   plumbery.facility
   plumbery.fitting
   plumbery.infrastructure
   plumbery.nodes
   plumbery.plogging
   plumbery.polisher
   plumbery.terraform
   plumbery.text
   plumbery.util

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

.. automodule:: plumbery
    :members:
    :undoc-members:
    :show-inheritance:


text:
//package declaration
package view.util;

//import java.awt components
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;

//import java.swing components
import javax.swing.border.Border;

//import rotatatble buttons and panels
import view.util.mega.MPanel;

//import utility class
import model.util.Util;
import view.util.mega.MLabel;

/**
 * Wrapper class which delivers a certain object to ActionListener.
 *
 * @author Julius Huelsmann
 * @version %U%, %I%
 */
@SuppressWarnings("serial")
public class VTabButton extends MPanel {

	/**
	 * ButtonWrapper of which the Tab - Button mainly consists.
	 */
	private VButtonWrapper vbw;

	/**
	 * MLabel for a stroke background.
	 */
	private MLabel jlbl_stroke;

	/**
	 * Constructor: Initializes the fundamental components of this tab
	 * button.
	 *
	 * @param _o_delivered the object passed to the button - wrapper owned
	 * by this instance of MPanel
	 */
	public VTabButton(final Object _o_delivered) {

		super.setLayout(null);
		super.setBorder(null);
		super.setOpaque(true);
		super.setFocusable(false);

		jlbl_stroke = new MLabel();
		jlbl_stroke.setOpaque(false);
		jlbl_stroke.setFocusable(false);
		super.add(jlbl_stroke);

		vbw = new VButtonWrapper(_o_delivered);

		vbw.setVisible(true);
		vbw.setBackground(Color.white);
		vbw.setBorder(null);
		vbw.setFocusable(false);
		vbw.setContentAreaFilled(false);
		vbw.setOpaque(true);
		super.add(vbw);
	}

	/*
	 * design methods
	 */

	/**
	 *
	 */
	public final void stroke() {
		jlbl_stroke.setVisible(true);
		Util.getStroke(jlbl_stroke);
	}

	/**
	 *
	 */
	public final void unstroke() {
		jlbl_stroke.setVisible(false);
	}

	/*
	 * overwritten methods or methods written for passing attributes directly
	 * to owned instance of VButtonWrapper
	 */

	/**
	 * set Border of VButtonWrapper.
	 * @param _b the Border
	 */
	public final void setBorder(final Border _b) {
		if (vbw != null) {
			vbw.setBorder(_b);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override public final void setSize(final int _width, final int _height) {
		super.setSize(_width, _height);
		vbw.setSize(_width, _height);
		jlbl_stroke.setSize(_width, _height);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override public final void setSize(final Dimension _d) {
		super.setSize(_d);
		vbw.setSize(_d);
		jlbl_stroke.setSize(_d);

	}

	/**
	 * set settings of owned VButtonWrapper.
	 * @param _control the ActionListener.
	 */
	public final void addActionListener(final ActionListener _control) {
        vbw.addActionListener(_control);
	}

	/**
	 * set settings of owned VButtonWrapper.
	 * @param _text the text
	 */
	public final void setText(final String _text) {
		vbw.setText(_text);
	}

	/**
	 * set settings of owned VButtonWrapper.
	 * @param _control the MouseListener.
	 */
	public final void addMouseListener(final MouseListener _control) {

        vbw.addMouseListener(_control);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override public final void setFocusable(final boolean _focusable) {
		vbw.setFocusable(_focusable);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override public final void setBackground(final Color _c) {
		if (vbw != null) {
			vbw.setBackground(_c);
		}
		super.setBackground(_c);
	}

	/**
	 * set settings of owned VButtonWrapper.
	 * @param _b whether content area is filled.
	 */
	public final void setContentAreaFilled(final boolean _b) {
		vbw.setContentAreaFilled(_b);
	}

	/**
	 * {@inheritDoc}
	 */
	public final void setOpaque(final boolean _opaque) {
		super.setOpaque(_opaque);
		if (vbw != null) {
			vbw.setOpaque(_opaque);

		}
	}

}


text:
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

<img width="600px" src="figs/figure1.png">

N-body gravity simulation with adaptive multilevel time stepping. Integrators implemented 'Euler', 'DKD', 'KDK' and 'RK4'.

Computational Astrophysics Course Project, ETH Zurich, 2012

mikael.mieskolainen@cern.ch