text:
package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path"
	"strings"
	"time"

	"github.com/voxelbrain/goptions"
)

var (
	options = struct {
		Server string        `goptions:"-s, --server, description='Pixelpixel server to push to'"`
		Help   goptions.Help `goptions:"-h, --help, description='Show this help'"`
		goptions.Verbs
		Upload struct{} `goptions:"upload"`
		Logs   struct{} `goptions:"logs"`
		Format struct{} `goptions:"format"`
	}{
		Server: "localhost:8080",
	}
)

const (
	keyFile = ".key"
)

func main() {
	fs := goptions.NewFlagSet("picli", &options)
	err := fs.Parse(os.Args[1:])
	if err == goptions.ErrHelpRequest {
		fs.PrintHelp(os.Stderr)
		return
	}

	options.Server = validateServer(options.Server)
	key := prepareKey()

	switch options.Verbs {
	case "upload":
		format()
		upload(key)
	case "logs":
		logs(key)
	case "format":
		format()
	default:
		if err != nil {
			fmt.Printf("Error: %s\n", err)
		}
		fs.PrintHelp(os.Stderr)
		return
	}
}

func makeApiCall(method, subpath string, body io.Reader) (int, string, error) {
	url := path.Join(options.Server, "pixels") + "/"
	url = slashify(url + subpath)
	req, _ := http.NewRequest(method, url, body)
	resp, err := http.DefaultClient.Do(req)
	buf := &bytes.Buffer{}

	code := -1
	if resp != nil {
		defer resp.Body.Close()
		code = resp.StatusCode
		io.Copy(buf, resp.Body)
	}

	// TODO: Sadly, this seems to be necassary. Can't seem to get it
	// working without it. I always get `malformed HTTP response ""`
	http.DefaultTransport.(*http.Transport).CloseIdleConnections()

	return code, buf.String(), err
}

func prepareKey() string {
	f, err := os.Open(keyFile)
	if err != nil {
		return ""
	}
	defer f.Close()
	key, err := ioutil.ReadAll(f)
	if err != nil {
		return ""
	}
	skey := strings.TrimSpace(string(key))
	code, _, err := makeApiCall("GET", "/"+skey, nil)
	if err == nil && code == http.StatusOK {
		return skey
	}
	return ""
}

func slashify(url string) string {
	url = path.Clean(url)
	if !strings.HasSuffix(url, "/") {
		url = url + "/"
	}
	return "http://" + strings.TrimPrefix(url, "/")
}

const (
	DEFAULT_REMOTE_SERVER = "pixelpixel.haxigon.com"
)

func validateServer(server string) string {
	t := time.AfterFunc(3*time.Second, func() {
		log.Fatalf("Attempt to connect to server timed out")
	})
	defer func() {
		t.Stop()
	}()

	resp, err := http.Get("http://" + path.Join(server, "handshake"))
	if err == nil && readAll(resp.Body) == "PIXELPIXEL OK" {
		return server
	}

	resp, err = http.Get("http://" + path.Join(DEFAULT_REMOTE_SERVER, "handshake"))
	if err == nil && readAll(resp.Body) == "PIXELPIXEL OK" {
		return DEFAULT_REMOTE_SERVER
	}
	log.Fatalf("Could not connect to server")
	return ""
}

func readAll(r io.Reader) string {
	data, _ := ioutil.ReadAll(r)
	return string(data)
}


text:
var link = require('../../lib/link');
var expect = require('chai').expect;
var clone = require('clone');

describe('lib/link for generating relative paths to the www directory', function () {

  var report = {
    'a': {
      'export': true,
      'dependencies': [],
      'commands': [{
        'behavior': 'copy',
        'files': ['/repo/fake/src/a.js'],
        'output': ['/www/fake/src/a.js']
      }]
    }
  };
  var reportWithNoExport = clone(report);
  reportWithNoExport.a.export = false;

  it('throws output out of www', function () {

    expect(function () {
      link(report, 'repo/www/');
    }).to.throw(/Output \[.+?\] out of www \[.*?\]!/);

    expect(link(report, '/www/')).to.eql({
      'a': ['fake/src/a.js']
    });

  });

  it('keeps the ending splash in paths', function () {
    expect(link(report, '/www')).to.eql({
      'a': ['/fake/src/a.js']
    });
  });

  it('can hide a package by set its export to be false', function () {
    expect(link(reportWithNoExport, '/www')).to.eql({});
  });

});

redpajama_set_name: RedPajamaGithub


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

import org.flowable.idm.api.PasswordSalt;
import org.flowable.idm.api.PasswordSaltProvider;

/**
 * @author faizal-manan
 */
public class PasswordSaltImpl implements PasswordSalt {

    private PasswordSaltProvider saltProvider;

    public PasswordSaltImpl(PasswordSaltProvider salt) {
        this.saltProvider = salt;
    }

    public PasswordSaltImpl(String salt) {
        this.saltProvider = new TextSaltProvider(salt);
    }

    @Override
    public PasswordSaltProvider getSource() {
        return saltProvider;
    }

    @Override
    public void setSource(PasswordSaltProvider source) {
        this.saltProvider = source;
    }
}


text:
import React, { cloneElement } from 'react';
import classSet from 'classnames';

import ValidComponentChildren from './utils/ValidComponentChildren';
import createChainedFunction from './utils/createChainedFunction';

const Pager = React.createClass({

  propTypes: {
    onSelect: React.PropTypes.func
  },

  render() {
    return (
      <ul
        {...this.props}
        className={classSet(this.props.className, 'pager')}>
        {ValidComponentChildren.map(this.props.children, this.renderPageItem)}
      </ul>
    );
  },

  renderPageItem(child, index) {
    return cloneElement(
      child,
      {
        onSelect: createChainedFunction(child.props.onSelect, this.props.onSelect),
        key: child.key ? child.key : index
      }
    );
  }
});

export default Pager;


text:
from __future__ import division, print_function, absolute_import

import pytest
from numpy.testing import assert_equal, assert_allclose, assert_almost_equal
from scipy._lib._numpy_compat import suppress_warnings

from scipy.misc import pade, logsumexp, face, ascent, electrocardiogram
from scipy.special import logsumexp as sc_logsumexp

def test_logsumexp():
    # make sure logsumexp can be imported from either scipy.misc or
    # scipy.special
    with suppress_warnings() as sup:
        sup.filter(DeprecationWarning, "`logsumexp` is deprecated")
        assert_allclose(logsumexp([0, 1]), sc_logsumexp([0, 1]), atol=1e-16)

def test_pade():
    # make sure scipy.misc.pade exists
    with suppress_warnings() as sup:
        sup.filter(DeprecationWarning, "`pade` is deprecated")
        pade([1, 2], 1)

def test_face():
    assert_equal(face().shape, (768, 1024, 3))

def test_ascent():
    assert_equal(ascent().shape, (512, 512))

def test_electrocardiogram():
    # Test shape, dtype and stats of signal
    ecg = electrocardiogram()
    assert ecg.dtype == float
    assert_equal(ecg.shape, (108000,))
    assert_almost_equal(ecg.mean(), -0.16510875)
    assert_almost_equal(ecg.std(), 0.5992473991177294)


text:
<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use App\Ecofy\Support\ObjectHelper;

use App\EcoLearnia\Modules\Assignment\Evaluation\DefaultEvaluator;
use App\EcoLearnia\Modules\Assignment\Evaluation\WhenHandler;

class DefaultEvaluatorTest extends TestCase
{

    protected function setUp()
    {
        //$this->markTestSkipped('The Skipping.');
    }

    /**
     * testCalculateAttemptsNoSubmissions
     */
    public function testCalculateAttemptsNoSubmissions()
    {
        $defaultEvaluator = new DefaultEvaluator();

        $activity = new stdClass();
        $activity->item_evalDetailsList = [];
        $activity->policy = ['maxAttempts' => 1];
        $result = $defaultEvaluator->calculateAttempts_($activity);

        $expected = new stdClass();
        $expected->numAttempted = 0;
        $expected->attemptsLeft = 1;

        $this->assertEquals($expected, $result, 'CalculateAttempts returned wrong values');
    }

    /**
     * testCalculateAttemptsOneSubmissionNoLeft
     */
    public function testCalculateAttemptsOneSubmissionNoLeft()
    {
        $defaultEvaluator = new DefaultEvaluator();

        $activity = new stdClass();
        $activity->item_evalDetailsList = [
            ['submission'=>'MyFakeSubmission', 'evalResult'=>'MyFakeEvalResult']
        ];
        $activity->policy = ['maxAttempts' => 1];
        $result = $defaultEvaluator->calculateAttempts_($activity);

        $expected = new stdClass();
        $expected->numAttempted = 1;
        $expected->attemptsLeft = 0;

        $this->assertEquals($expected, $result, 'CalculateAttempts returned wrong values');
    }

    /**
     * testCalculateAttemptsTwoSubmissionOneLeft
     */
    public function testCalculateAttemptsTwoSubmissionOneLeft()
    {
        $defaultEvaluator = new DefaultEvaluator();

        $activity = new stdClass();
        $activity->item_evalDetailsList = [
            ['submission'=>'MyFakeSubmission', 'evalResult'=>'MyFakeEvalResult'],
            ['submission'=>'MyFakeSubmission', 'evalResult'=>'MyFakeEvalResult']
        ];
        $activity->contentInstance = ['defaultPolicy' => 3];
        $result = $defaultEvaluator->calculateAttempts_($activity);

        $expected = new stdClass();
        $expected->numAttempted = 2;
        $expected->attemptsLeft = 1;

        $this->assertEquals($expected, $result, 'CalculateAttempts returned wrong values');
    }

    /**
     * testCombineSubmissionData
     */
    public function testCombineSubmissionData()
    {
        $defaultEvaluator = new DefaultEvaluator();
        $itemContent = $this->loadJson('numbergame.testitem.json');

        $variableDeclarations = $itemContent['variableDeclarations'];
        $submissionData = [
            'subm1' => 'MyData'
        ];

        $result = $defaultEvaluator->combineSubmissionData_($variableDeclarations, $submissionData);

        $expected = [
            'var_num1' => 2,
            'var_num2' => 4,
            'var_num3' => 8,
            'var_patternIndex' => 9,
            'subm1' => 'MyData'
        ];

        $this->assertEquals($expected, $result, 'combineSubmissionData returned wrong values');
    }

    /**
     * testCalculateAgregate
     */
    public function testCalculateAgregatePass()
    {
        $defaultEvaluator = new DefaultEvaluator();
        $itemContent = $this->loadJson('numbergame.testitem.json');

        $evalResult = new stdClass();
        $evalResult->fields = [
            'field1' => ['score' => 1],
            'field2' => ['score' => 1]
        ];
        $attemptNum = 1;

        $result = $defaultEvaluator->calculateAggregate_($evalResult, $attemptNum);

        $expected = new \stdClass();
        $expected->fields = [
            'field1' => ['score' => 1, 'pass' => true],
            'field2' => ['score' => 1, 'pass' => true]
        ];
        $expected->aggregate = new \stdClass();
        $expected->aggregate->score = 1;
        $expected->aggregate->pass = true;

        $this->assertEquals($expected, $result, 'combineSubmissionData returned wrong values');

    }

    /**
     * testCalculateAgregateNoPass
     */
    public function testCalculateAgregateNoPass()
    {
        $defaultEvaluator = new DefaultEvaluator();
        $itemContent = $this->loadJson('numbergame.testitem.json');

        $evalResult = new \stdClass();
        $evalResult->fields = [
            'field1' => ['score' => 1.0],
            'field2' => ['score' => 0.8]
        ];
        $attemptNum = 1;

        $result = $defaultEvaluator->calculateAggregate_($evalResult, $attemptNum);

        $expected = new \stdClass();
        $expected->fields = [
            'field1' => ['score' => 1.0, 'pass' => true],
            'field2' => ['score' => 0.8, 'pass' => false]
        ];
        $expected->aggregate = new stdClass();
        $expected->aggregate->score = 0.90;
        $expected->aggregate->pass = false;

        $this->assertEquals($expected, $result, 'combineSubmissionData returned wrong values');

    }

    /**
     * testEvaluateFieldsCorrect
     */
    public function testEvaluateFieldsCorrect()
    {
        $defaultEvaluator = new DefaultEvaluator();
        $itemContent = $this->loadJson('addition.testitem.json');

        $rule = $itemContent['responseProcessing'];
        $submissionData = [
            'field1_value' => 20,
            'var_num1' => 5,
            'var_num2' => 15
        ];

        $result = $defaultEvaluator->evaluateFields_($rule, $submissionData);

        $expected = [
            'field1' => [
                'score' => 1,
                'feedback' => 'NUMBER Just right!!'
            ]
        ];

        $this->assertEquals($expected, $result, 'combineSubmissionData returned wrong values');
    }

    /**
     * testEvaluateFieldsCorrect
     */
    public function testEvaluateFieldsTooBig()
    {
        $defaultEvaluator = new DefaultEvaluator();
        $itemContent = $this->loadJson('addition.testitem.json');

        $rule = $itemContent['responseProcessing'];
        $submissionData = [
            'field1_value' => 20,
            'var_num1' => 3,
            'var_num2' => 4
        ];

        $result = $defaultEvaluator->evaluateFields_($rule, $submissionData);

        $expected = [
            'field1' => [
                'score' => 0,
                'feedback' => 'NUMBER TOO BIG'
            ]
        ];

        $this->assertEquals($expected, $result, 'combineSubmissionData returned wrong values');
    }

    /**
     * testEvaluateFieldsCorrect
     */
    public function testEvaluateFieldsTooSmall()
    {
        $defaultEvaluator = new DefaultEvaluator();
        $itemContent = $this->loadJson('addition.testitem.json');

        $rule = $itemContent['responseProcessing'];
        $submissionData = [
            'field1_value' => 3,
            'var_num1' => 3,
            'var_num2' => 4
        ];

        $result = $defaultEvaluator->evaluateFields_($rule, $submissionData);

        $expected = [
            'field1' => [
                'score' => 0,
                'feedback' => 'NUMBER TOO SMALL'
            ]
        ];

        $this->assertEquals($expected, $result, 'combineSubmissionData returned wrong values');
    }

    public function loadJson($filename)
    {
        $filedata = file_get_contents('tests/mock/' . $filename);
        $json = json_decode($filedata, true);
        return $json;
    }

}


text:
package fm.liu.timo;

import java.util.Map;
import java.util.Set;
import fm.liu.timo.config.model.User;
import fm.liu.timo.net.handler.FrontendPrivileges;

/**
 * @author xianmao.hexm
 */
public class TimoPrivileges implements FrontendPrivileges {

    @Override
    public boolean schemaExists(String db) {
        TimoConfig conf = TimoServer.getInstance().getConfig();
        return conf.getDatabases().containsKey(db.toUpperCase());
    }

    @Override
    public boolean userExists(String user, String host) {
        Map<String, User> users = TimoServer.getInstance().getConfig().getUsers();
        if (users.containsKey(user)) {
            Set<String> hosts = users.get(user).getHosts();
            if (!hosts.isEmpty() && !hosts.contains(host)) {
                return false;
            }
            return true;
        }
        return false;
    }

    @Override
    public String getPassword(String user) {
        TimoConfig conf = TimoServer.getInstance().getConfig();
        User uc = conf.getUsers().get(user);
        if (uc != null) {
            return uc.getPassword();
        } else {
            return null;
        }
    }

    @Override
    public Set<String> getUserSchemas(String user) {
        TimoConfig conf = TimoServer.getInstance().getConfig();
        User uc = conf.getUsers().get(user);
        if (uc != null) {
            return uc.getDatabases();
        } else {
            return null;
        }
    }

}


text:
package dl.dlutils.utils.base.number;

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;

/**
 * Some helper methods ...
 */
public class NumberUtil {

	public static final String ALLOWED_PHONE_NUMBER_CHARS = "+-/().";

	public static final int KILO_BYTES = 1024;

	public static final BigDecimal KB_BD = new BigDecimal(KILO_BYTES);

	public static final int MEGA_BYTES = KILO_BYTES * 1024;

	public static final BigDecimal MB_BD = new BigDecimal(MEGA_BYTES);

	public static final int GIGA_BYTES = MEGA_BYTES * 1024;

	public static final BigDecimal GB_BD = new BigDecimal(GIGA_BYTES);

	public static final BigDecimal TWENTY = new BigDecimal(20);

	public static final BigDecimal HUNDRED = new BigDecimal(100);

	public static final BigDecimal THOUSAND = new BigDecimal(1000);

	public static final BigDecimal THREE_THOUSAND_SIX_HUNDRED = new BigDecimal(3600);

	public static final BigDecimal MINUS_TWENTY = new BigDecimal(-20);

	public static final BigDecimal MINUS_HUNDRED = new BigDecimal(-100);

	public static final BigDecimal BILLION = new BigDecimal(1000000000);

	private static final Logger log = Logger.getLogger(NumberUtil.class);

	public static NumberFormat getCurrencyFormat(final Locale locale) {
		return getNumberFraction2Format(locale);
	}

	public static NumberFormat getNumberFraction2Format(final Locale locale) {
		final NumberFormat format = NumberFormat.getNumberInstance(locale);
		format.setMaximumFractionDigits(2);
		format.setMinimumFractionDigits(2);
		return format;
	}

	public static NumberFormat getNumberFractionFormat(final Locale locale, final int fractionDigits) {
		final NumberFormat format = NumberFormat.getNumberInstance(locale);
		format.setMaximumFractionDigits(fractionDigits);
		format.setMinimumFractionDigits(fractionDigits);
		return format;
	}

	/**
	 * Pretty output of bytes, "1023 bytes", "1.1 kb", "523 kb", "1.7 Mb", "143
	 * Gb" etc.
	 *
	 * @param bytes
	 * @return
	 */
	public static String formatBytes(final long bytes) {
		if (bytes < KILO_BYTES) {
			return String.valueOf(bytes) + " bytes";
		}
		if (bytes < MEGA_BYTES) {
			BigDecimal no = new BigDecimal(bytes).divide(KB_BD, 1, BigDecimal.ROUND_HALF_UP);
			if (no.longValue() >= 100) {
				no = no.setScale(0, BigDecimal.ROUND_HALF_UP);
			}
			return NumberFormat.getInstance(Locale.getDefault()).format(no) + " kb";
		}
		if (bytes < GIGA_BYTES) {
			BigDecimal no = new BigDecimal(bytes).divide(MB_BD, 1, BigDecimal.ROUND_HALF_UP);
			if (no.longValue() >= 100) {
				no = no.setScale(0, BigDecimal.ROUND_HALF_UP);
			}
			return NumberFormat.getInstance(Locale.getDefault()).format(no) + " Mb";
		}
		BigDecimal no = new BigDecimal(bytes).divide(GB_BD, 1, BigDecimal.ROUND_HALF_UP);
		if (no.longValue() >= 100) {
			no = no.setScale(0, BigDecimal.ROUND_HALF_UP);
		}
		return NumberFormat.getInstance(Locale.getDefault()).format(no) + " Gb";
	}

	/**
	 * @param value
	 * @return true, if value is not null and greater zero.
	 */
	public static boolean greaterZero(final Integer value) {
		return value != null && value.intValue() > 0;
	}

	/**
	 * @param value
	 * @return true, if value is not null and greater zero.
	 */
	public static boolean greaterZero(final Long value) {
		return value != null && value.intValue() > 0;
	}

	public static boolean isZeroOrNull(final Integer value) {
		return (value == null || value == 0);
	}

	public static boolean isGreaterZero(final BigDecimal value) {
		return (value != null && value.compareTo(BigDecimal.ZERO) > 0);
	}

	/**
	 * @param value
	 * @return true, if the given value is not null and not zero.
	 */
	public static boolean isNotZero(final Integer value) {
		return !isZeroOrNull(value);
	}

	/**
	 * Parses the given string as integer value.
	 *
	 * @param value The string representation of the integer value to parse.
	 * @return Integer value or null if an empty string was given or a syntax
	 *         error occurs.
	 */
	public static Integer parseInteger(String value) {
		if (value == null) {
			return null;
		}
		value = value.trim();
		if (value.length() == 0) {
			return null;
		}
		Integer result = null;
		try {
			result = new Integer(value);
		} catch (final NumberFormatException ex) {
			log.debug(ex.getMessage(), ex);
		}
		return result;
	}

	/**
	 * Parses the given string as short value.
	 *
	 * @param value The string representation of the short value to parse.
	 * @return Short value or null if an empty string was given or a syntax
	 *         error occurs.
	 */
	public static Short parseShort(String value) {
		if (value == null) {
			return null;
		}
		value = value.trim();
		if (value.length() == 0) {
			return null;
		}
		Short result = null;
		try {
			result = new Short(value);
		} catch (final NumberFormatException ex) {
			log.debug(ex.getMessage(), ex);
		}
		return result;
	}

	/**
	 * Catches any NumberFormatException and returns 0, otherwise the long value
	 * represented by the given value is returned.
	 */
	public static long parseLong(String value) {
		if (value == null) {
			return 0;
		}
		value = value.trim();
		if (value.length() == 0) {
			return 0;
		}
		Long result = null;
		try {
			result = new Long(value);
		} catch (final NumberFormatException ex) {
			log.debug(ex.getMessage(), ex);
		}
		return result;
	}

	/**
	 */
	public static BigDecimal parseBigDecimal(String value) {
		if (value == null) {
			return null;
		}
		value = value.trim();
		if (value.length() == 0) {
			return null;
		}
		BigDecimal result = null;
		try {
			if (value.indexOf(',') > 0) {
				// Replace the german decimal character by '.':
				value = value.replace(',', '.');
			}
			result = new BigDecimal(value);
		} catch (final NumberFormatException ex) {
			log.debug(ex.getMessage(), ex);
		}
		return result;
	}

	/**
	 */
	public static BigDecimal parseCurrency(String value, final Locale locale) {
		if (value == null) {
			return null;
		}
		value = value.trim();
		if (value.length() == 0) {
			return null;
		}
		final NumberFormat format = getCurrencyFormat(locale);
		BigDecimal result = null;
		try {
			final Number number = format.parse(value);
			if (number != null) {
				result = new BigDecimal(number.toString());
				result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
			}
		} catch (final ParseException ex) {
			log.debug(ex.getMessage(), ex);
		}
		return result;
	}

	/**
	 * @param v1 null is supported.
	 * @param v2 null is supported.
	 * @return
	 */
	public static BigDecimal add(final BigDecimal v1, final BigDecimal v2) {
		if (v1 == null) {
			if (v2 == null) {
				return BigDecimal.ZERO;
			} else {
				return v2;
			}
		} else {
			if (v2 == null) {
				return v1;
			} else {
				return v1.add(v2);
			}
		}
	}

	/**
	 * Returns the given integer value as String representation.
	 *
	 * @param value The integer value to convert.
	 * @return The String representation or empty String, if value is null.
	 */
	public static String getAsString(final Number value) {
		if (value == null) {
			return "";
		} else {
			return String.valueOf(value);
		}
	}

	/**
	 * Returns the given number value as String representation.
	 *
	 * @param value The number value to convert.
	 * @param format The format to use.
	 * @return The String representation or empty String, if value is null.
	 */
	public static String getAsString(final Number value, final NumberFormat format) {
		if (value == null) {
			return "";
		} else {
			return format.format(value);
		}
	}

	public static String formatFraction2(final Number value) {
		final Locale locale = Locale.getDefault();
		final NumberFormat format = getNumberFraction2Format(locale);
		return format.format(value);
	}

	/**
	 * Extracts the phone number of the given string. All characters of the set
	 * "+-/()." and white spaces will be deleted and +## will be replaced by
	 * 00##. Example: +49 561 / 316793-0 -> 00495613167930
 Ignores any
	 * characters after the first occurence of ':' or any letter.
	 *
	 * @param str
	 * @param countryPrefix If country prefix is given, for all numbers
	 *            beginning with the country prefix the country prefix will be
	 *            replaced by 0. Example: ("+49 561 / 316793-0", "+49") ->
	 *            05613167930; ("+39 123456", "+49") -> 0039123456.
	 * @return
	 */
	public static String extractPhonenumber(String str, final String countryPrefix) {
		if (str == null) {
			return null;
		}
		str = str.trim();
		final StringBuffer buf = new StringBuffer();
		if (StringUtils.isNotEmpty(countryPrefix) == true && str.startsWith(countryPrefix) == true) {
			buf.append('0');
			str = str.substring(countryPrefix.length());
		} else if (str.length() > 3 && str.charAt(0) == '+' && Character.isDigit(str.charAt(1)) == true && Character.isDigit(str.charAt(2)) == true) {
			buf.append("00");
			buf.append(str.charAt(1));
			buf.append(str.charAt(2));
			str = str.substring(3);
		}
		for (int i = 0; i < str.length(); i++) {
			final char ch = str.charAt(i);
			if (Character.isDigit(str.charAt(i)) == true) {
				buf.append(ch);
			} else if (Character.isWhitespace(ch) == true) {
				// continue.
			} else if (ALLOWED_PHONE_NUMBER_CHARS.indexOf(ch) < 0) {
				break;
			}
		}
		return buf.toString();
	}

	/**
	 * Compares two given BigDecimals. They are equal if the value is equal
	 * independent of the scale (5.70 is equals to 5.7 and null is equals null,
	 * but null is not equals to 0).
	 *
	 * @param value1
	 * @param value2
	 * @return
	 * @see BigDecimal#compareTo(BigDecimal)
	 */
	public static boolean isEqual(final BigDecimal value1, final BigDecimal value2) {
		if (value1 == null) {
			return (value2 == null) ? true : false;
		}
		if (value2 == null) {
			return false;
		}
		return value1.compareTo(value2) == 0;
	}

	/**
	 * @param value
	 * @return true, if the given value is not null and not zero.
	 */
	public static boolean isNotZero(final BigDecimal value) {
		return !isZeroOrNull(value);
	}

	public static boolean isZeroOrNull(final BigDecimal value) {
		return (value == null || value.compareTo(BigDecimal.ZERO) == 0);
	}

	/**
	 * Compares two given Integers using compareTo method.
	 *
	 * @param value1
	 * @param value
	 * @return
	 * @see Integer#compareTo(Integer)
	 */
	public static boolean isEqual(final Integer value1, final Integer value) {
		if (value1 == null) {
			return (value == null) ? true : false;
		}
		if (value == null) {
			return false;
		}
		return value1.compareTo(value) == 0;
	}

	/**
	 * Splits string representation of the given number into digits. Examples:

	 * NumberHelper.splitToInts(11110511, 1, 3, 2, 2) = {1, 111, 5, 11}

	 * NumberHelper.splitToInts(10000511, 1, 3, 2, 2) = { 1, 0, 5, 11}

	 * NumberHelper.splitToInts(511, 1, 3, 2, 2) = { 0, 0, 5, 11}
	 *
	 * @param value
	 * @param split
	 * @return
	 */
	public static int[] splitToInts(final Number value, final int... split) {
		int numberOfDigits = 0;
		for (final int n : split) {
			numberOfDigits += n;
		}
		final String str = StringUtils.leftPad(String.valueOf(value.intValue()), numberOfDigits, '0');
		final int[] result = new int[split.length];
		int pos = 0;
		int i = 0;
		for (final int n : split) {
			result[i++] = parseInteger(str.substring(pos, pos + n));
			pos += n;
		}
		return result;
	}

	/**
	 * If given string is an number (NumberUtils.isNumber(String)) then it will
	 * be converted to a plain string via BigDecimal.toPlainString(). Any
	 * exponent such as 1E7 will be avoided.
	 *
	 * @param str
	 * @return Converted string if number, otherwise the origin string.
	 * @see NumberUtils#isNumber(String)
	 * @see NumberUtils#createBigDecimal(String)
	 * @see BigDecimal#toPlainString()
	 */
	public static String toPlainString(final String str) {
		if (NumberUtils.isNumber(str) == true) {
			final BigDecimal bd = NumberUtils.createBigDecimal(str);
			return bd.toPlainString();
		} else {
			return str;
		}
	}

	/**
	 * Sets scale 0 for numbers greater 100, 1 for numbers greater 20 and 2 as
	 * default.
	 *
	 * @param number
	 * @return
	 */
	public static BigDecimal setDefaultScale(final BigDecimal number) {
		if (number == null) {
			return null;
		}
		if (number.compareTo(NumberUtil.HUNDRED) >= 0 || number.compareTo(NumberUtil.MINUS_HUNDRED) <= 0) {
			return number.setScale(0, BigDecimal.ROUND_HALF_UP);
		} else if (number.compareTo(NumberUtil.TWENTY) >= 0 || number.compareTo(NumberUtil.MINUS_TWENTY) <= 0) {
			return number.setScale(1, BigDecimal.ROUND_HALF_UP);
		}
		return number.setScale(2, BigDecimal.ROUND_HALF_UP);
	}

	/**
	 * Generates secure random bytes of the given length and return base 64
	 * encoded bytes as url safe String. This is not the length of the resulting
	 * string!
	 *
	 * @param numberOfBytes
	 * @return
	 */
	public static String getSecureRandomUrlSaveString(final int numberOfBytes) {
		final SecureRandom random = new SecureRandom();
		final byte[] bytes = new byte[numberOfBytes];
		random.nextBytes(bytes);
		return Base64.encodeBase64URLSafeString(bytes);
	}

	public static boolean isIn(final int value, final int... numbers) {
		if (numbers == null) {
			return false;
		}
		for (final int number : numbers) {
			if (value == number) {
				return true;
			}
		}
		return false;
	}

}


text:
package mygalaxy.graphing;

import mygalaxy.domain.Node;

import com.google.common.collect.Multimap;

public interface DataProvider {

	public Multimap<Node, Node> getData(String userId);

}


text:
package fuzzer

import (
	"reflect"
	"strings"

	"github.com/google/gofuzz"

	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
	runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
)

// Funcs returns the fuzzer functions for the apiextensions apis.
func Funcs(codecs runtimeserializer.CodecFactory) []interface{} {
	return []interface{}{
		func(obj *apiextensions.CustomResourceDefinitionSpec, c fuzz.Continue) {
			c.FuzzNoCustom(obj)

			// match our defaulter
			if len(obj.Scope) == 0 {
				obj.Scope = apiextensions.NamespaceScoped
			}
			if len(obj.Names.Singular) == 0 {
				obj.Names.Singular = strings.ToLower(obj.Names.Kind)
			}
			if len(obj.Names.ListKind) == 0 && len(obj.Names.Kind) > 0 {
				obj.Names.ListKind = obj.Names.Kind + "List"
			}
			if len(obj.Versions) == 0 && len(obj.Version) != 0 {
				obj.Versions = []apiextensions.CustomResourceDefinitionVersion{
					{
						Name:    obj.Version,
						Served:  true,
						Storage: true,
					},
				}
			} else if len(obj.Versions) != 0 {
				obj.Version = obj.Versions[0].Name
			}
		},
		func(obj *apiextensions.CustomResourceDefinition, c fuzz.Continue) {
			c.FuzzNoCustom(obj)

			if len(obj.Status.StoredVersions) == 0 {
				for _, v := range obj.Spec.Versions {
					if v.Storage && !apiextensions.IsStoredVersion(obj, v.Name) {
						obj.Status.StoredVersions = append(obj.Status.StoredVersions, v.Name)
					}
				}
			}
		},
		func(obj *apiextensions.JSONSchemaProps, c fuzz.Continue) {
			// we cannot use c.FuzzNoCustom because of the interface{} fields. So let's loop with reflection.
			vobj := reflect.ValueOf(obj).Elem()
			tobj := reflect.TypeOf(obj).Elem()
			for i := 0; i < tobj.NumField(); i++ {
				field := tobj.Field(i)
				switch field.Name {
				case "Default", "Enum", "Example", "Ref":
					continue
				default:
					isValue := true
					switch field.Type.Kind() {
					case reflect.Interface, reflect.Map, reflect.Slice, reflect.Ptr:
						isValue = false
					}
					if isValue || c.Intn(10) == 0 {
						c.Fuzz(vobj.Field(i).Addr().Interface())
					}
				}
			}
			if c.RandBool() {
				validJSON := apiextensions.JSON(`{"some": {"json": "test"}, "string": 42}`)
				obj.Default = &validJSON
			}
			if c.RandBool() {
				obj.Enum = []apiextensions.JSON{c.Float64(), c.RandString(), c.RandBool()}
			}
			if c.RandBool() {
				validJSON := apiextensions.JSON(`"foobarbaz"`)
				obj.Example = &validJSON
			}
			if c.RandBool() {
				validRef := "validRef"
				obj.Ref = &validRef
			}
		},
		func(obj *apiextensions.JSONSchemaPropsOrBool, c fuzz.Continue) {
			if c.RandBool() {
				obj.Allows = true
				obj.Schema = &apiextensions.JSONSchemaProps{}
				c.Fuzz(obj.Schema)
			} else {
				obj.Allows = c.RandBool()
			}
		},
		func(obj *apiextensions.JSONSchemaPropsOrArray, c fuzz.Continue) {
			// disallow both Schema and JSONSchemas to be nil.
			if c.RandBool() {
				obj.Schema = &apiextensions.JSONSchemaProps{}
				c.Fuzz(obj.Schema)
			} else {
				obj.JSONSchemas = make([]apiextensions.JSONSchemaProps, c.Intn(3)+1)
				for i := range obj.JSONSchemas {
					c.Fuzz(&obj.JSONSchemas[i])
				}
			}
		},
		func(obj *apiextensions.JSONSchemaPropsOrStringArray, c fuzz.Continue) {
			if c.RandBool() {
				obj.Schema = &apiextensions.JSONSchemaProps{}
				c.Fuzz(obj.Schema)
			} else {
				c.Fuzz(&obj.Property)
			}
		},
	}
}


text:
class WidgetPlacement < ActiveRecord::Base
  belongs_to :widget
  belongs_to :template

end


text:
export * from './circle';
export * from './rainbowCircle';
export * from './pathAnimatedCircle';


text:
<?php

class RefSysJurusan extends \Phalcon\Mvc\Model
{

    /**
     *
     * @var integer
     * @Primary
     * @Identity
     * @Column(type="integer", length=11, nullable=false)
     */
    public $id_jurusan;

    /**
     *
     * @var string
     * @Column(type="string", length=64, nullable=false)
     */
    public $nama;

    /**
     *
     * @var string
     * @Column(type="string", length=64, nullable=true)
     */
    public $nama_en;

    /**
     *
     * @var string
     * @Column(type="string", nullable=false)
     */
    public $aktif;

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'ref_sys_jurusan';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return RefSysJurusan[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return RefSysJurusan
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

}


text:
#region License(Apache Version 2.0)

#endregion
#region ChangeLog
/******************************************
 * 2017-10-7 OutMan Create
 *
 * ***************************************/
#endregion
using System;

namespace WitsWay.Utilities.Daos
{
    /// <summary>
    /// 数据访问对象标记
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class DaoAttribute : Attribute { }
}


text:
package org.deidentifier.arx.criteria;

import org.deidentifier.arx.ARXConfiguration;
import org.deidentifier.arx.certificate.elements.ElementData;
import org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry;
import org.deidentifier.arx.framework.data.DataManager;
import org.deidentifier.arx.framework.lattice.Transformation;

/**
 * Delta-disclosure privacy as proposed in:

 *

 * Justin Brickell and Vitaly Shmatikov:

 * The Cost of Privacy: Destruction of Data-mining Utility in Anonymized Data Publishing

 * Proceedings of the 14th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining

 * 2008
 *
 * @author Fabian Prasser
 */
public class DDisclosurePrivacy extends ExplicitPrivacyCriterion {

    /** SVUID */
    private static final long   serialVersionUID = 1543994581019659183L;

    /** Log 2. */
    private static final double LOG2             = Math.log(2);

    /**
     * Computes log 2.
     *
     * @param num
     * @return
     */
    static final double log2(final double num) {
        return Math.log(num) / LOG2;
    }

    /** Parameter */
    private final double        d;

    /** The original distribution. */
    private double[]            distribution;

    /**
     * Creates a new instance
     *
     * @param attribute
     * @param delta
     */
    public DDisclosurePrivacy(String attribute, double delta) {
        super(attribute, false, false);
        this.d = delta;
    }

    @Override
    public DDisclosurePrivacy clone() {
        return new DDisclosurePrivacy(this.getAttribute(), this.getD());
    }

    /**
     * Returns the parameter delta.
     *
     * @return
     */
    public double getD(){
        return d;
    }

	@Override
    public int getRequirements(){
        // Requires a distribution
        return ARXConfiguration.REQUIREMENT_DISTRIBUTION;
    }

    @Override
    public void initialize(DataManager manager, ARXConfiguration config) {
        super.initialize(manager, config);
        distribution = manager.getDistribution(attribute);
    }

    @Override
    public boolean isAnonymous(Transformation node, HashGroupifyEntry entry) {

        // For table t
        // Foreach class c
        //     Foreach sensitive value s
        //         abs(log(freq(s, c)/freq(s, t)) < delta

        // Init
        int[] buckets = entry.distributions[index].getBuckets();
        double count = entry.count;

        // For each value in c
        for (int i = 0; i < buckets.length; i += 2) {
            if (buckets[i] != -1) { // bucket not empty
                double frequencyInT = distribution[buckets[i]];
                double frequencyInC = (double) buckets[i + 1] / count;
                double value = Math.abs(log2(frequencyInC / frequencyInT));
                if (value >= d) {
                    return false;
                }
            }
        }

        // check
        return true;
    }

    @Override
    public boolean isLocalRecodingSupported() {
        return true;
    }

    @Override
    public ElementData render() {
        ElementData result = new ElementData("Disclosure privacy");
        result.addProperty("Attribute", attribute);
        result.addProperty("Threshold (delta)", d);
        return result;
    }

    @Override
	public String toString() {
		return d+"-disclosure privacy for attribute '"+attribute+"'";
	}
}


text:
#ifndef CHS_HPP
#define CHS_HPP
// This class allows to convert LBA to CHS adressing used by MBR and vice versa
// Examples
/*
1:
    CHS chs(cyl,head,sect);
    chs.SetGeometry(sectors_per_track,tracks_per_cylinder);
    unsigned sector=chs.ToLBA();

2:
    CHS chs(1023); // secotr 1023
    chs.SetGeometry(sectors_per_track,tracks_per_cylinder);
    chs=2048;
    chs++; // now 2049
    MBR_CHS c=chs.ToMbrChs();

*/
#include <stdint.h>

#pragma pack(1)
// Cylinder-head-sector structure for MBR
struct MBR_CHS
{
  uint8_t head;             // head (<255)
  uint8_t sector:6;         // sector (<64)
  uint8_t cylinder_bits:2;  // 2 bits of cylinder value
  uint8_t cylinder   ;      // cylinder (<=1023)
};
#pragma pack()

//
// A class for CHS manipulation
//

class CHS
{
  long long cylinder,
            head,
            sector;
  unsigned int spt, // sectors per track
               tpc; // tracks per cylinder

  void calc(long long);

public:

  CHS(int c,int h, int s);
  CHS(long long lba);
  CHS();

  bool SetCylinder(long long);
  bool SetHead(unsigned int);
  bool SetSector(unsigned int);

  unsigned long GetCylinder();
  unsigned int GetHead();
  unsigned int GetSector();

  bool SetGeometry(int spt,int tpc);
  int GetSPT();
  int GetTPC();
  void SetSPT(int);
  void SetTPC(int);

  long long ToLBA();

  CHS &operator =(long long);
  bool operator ==(CHS &chs);
  CHS &operator ++();
  CHS &operator ++(int);

  MBR_CHS ToMbrChs();

};

#endif


text:
from setuptools import setup

setup(name='s3streamcat',
      version='0.1.6',
      description='Streaming based unix cat like functionality for file on S3. Supports gzip, bzip and xz compressed files as well',
      long_description=open('README.md').read(),
      url='https://github.com/samarthg/s3streamcat',
      download_url = 'https://github.com/samarthg/s3streamcat/archive/v0.1.6.tar.gz',
      author='Samarth Gahire',
      author_email='samarth.gahire@gmail.com',
      license='MIT',
      packages=['s3streamcat', 's3client'],
      install_requires=[
          'boto3==1.3.1',
          'bumpversion',
          'fabric3',
      ],
      zip_safe=False,
      entry_points={
          'console_scripts': [
              's3streamcat = s3streamcat.s3streamcat:stream_s3_file'
          ]
      },
      keywords = ['s3cat', 's3', 'print', 'aws', 'cat', 'stream', 'gzip', 'bzip', 'xz'],
      )


text:
from django.conf.urls import url

from oscar.core.application import Application
from oscar.core.loading import get_class
from oscar.apps.promotions.models import PagePromotion, KeywordPromotion

class PromotionsApplication(Application):
    name = 'promotions'

    home_view = get_class('promotions.views', 'HomeView')

    def get_urls(self):
        urls = [
            url(r'^$', self.home_view.as_view(), name='home'),
        ]
        return self.post_process_urls(urls)

application = PromotionsApplication()


text:
package com.streamreduce.core.model.messages.details.nodebelly;

import com.streamreduce.core.model.messages.details.AbstractMessageDetails;
import com.streamreduce.core.model.messages.details.MessageDetailsType;
import com.streamreduce.core.model.messages.details.SobaMessageDetails;

import java.util.Map;

/**
 * Aggregate message type
 */
public class NodebellySummaryMessageDetails extends AbstractMessageDetails implements SobaMessageDetails {

    protected Map<String, Object> structure;

    @Override
    public MessageDetailsType getMessageDetailsType() {
        return MessageDetailsType.NODEBELLY_SUMMARY;
    }

    public static class Builder {
        NodebellySummaryMessageDetails theObject;

        public Builder() {
            theObject = new NodebellySummaryMessageDetails();
        }

        public Builder title(String title) {
            theObject.title = title.trim();
            return this;
        }

        public Builder structure(Map<String, Object> structure) {
            theObject.structure = structure;
            return this;
        }

        public NodebellySummaryMessageDetails build() {
            return theObject;
        }
    }

    public Map<String, Object> getStructure() {
        return structure;
    }

    public String toPlainText() {
        StringBuilder text = new StringBuilder();
        for (Map.Entry<String, Object> entry : structure.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            text.append(key).append(":").append(value).append(" ");
        }
        return text.toString();
    }

}


text: Very Good Statistics


text:
import express from 'express';
import User from '../models/User';

const router = express.Router();

router.route('/')
    .get(function (req, res, next){
        const searchTerm = req.query.q;
        const re = new RegExp(searchTerm, 'i');
        User.find().or([
          {'firstName':{$regex:re}}, {'lastName':{$regex:re}}, {'userName':{$regex:re}}
        ]).exec((err, foundUsers) => {
          res.json(foundUsers);
        })
});

export default router;


text:
<!DOCTYPE html>

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

            <meta name="description" content="HydroPi Pool Management and Power Control">
            <meta name="author" content="">
            <link rel="icon"
                  type="image/png"
                  href="favicon.png">

            <title>HydroPi - Pool Monitor</title>

            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

            <link rel="stylesheet" type="text/css" href="css/hydropi_theme.css">

<?php
    //Create the top menu
    include "php/top_menu.php"
?>

Raspberry Pi Tools

                                <button type="button" class="btn btn-md btn-info btn-block mb-2" onclick="Shutdown()">Shutdown</button>

                                <button type="button" class="btn btn-md btn-primary btn-block mb-2" onclick="Restart()">Restart</button>

MySQL Delete Readings

                                <button type="button" class="btn btn-md btn-info btn-block mb-2" onclick="Delete_MySQL(0)">Delete All</button>

                                <button type="button" class="btn btn-md btn-primary btn-block mb-2" onclick="Delete_MySQL(90)">Over 3 Months</button>

                                <button type="button" class="btn btn-md btn-info btn-block mb-2" onclick="Delete_MySQL(180)">Over 6 Months</button>

                                <button type="button" class="btn btn-md btn-primary btn-block mb-2" onclick="Delete_MySQL(365)">Over 12 Months</button>

Misc Settings

                        <form class="form" method="POST" action="/php/update_settings.php">
                            <fieldset>
                                <?php
                                // Get the names of all the settings in the database and add an input for each to the form
                                include "php/settings_col_names.php";
                                $count = 0;
                                foreach ($colnames as $title) {
                                    $count += 1;
                                    if ($count % 2 == 0) {
                                        $mycolor = "btn-info";
                                    }
                                    else {
                                        $mycolor = "btn-primary";
                                    }
echo "
\n";
echo "
\n";
echo "                                      \n";
echo "
\n";
echo "
\n";
echo "                                      <input name=\"" .$title. "\" class=\"form-control input-md d-flex justify-content-center " .$mycolor. "\" id=\"" .$title. "\" autocomplete=\"off\">\n";
echo "
\n";
echo "
\n";
                                }
                                ?>

                                    <button name="singlebutton" class="btn btn-success my-2" id="singlebutton">Update Settings</button>

                            </fieldset>
                        </form>


text:
"""
    setup.py

    Copyright (c) 2015 Chad Oakley Hughes
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:
    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
    3. Neither the name of copyright holders nor the names of its
       contributors may be used to endorse or promote products derived
       from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
    BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

"""

from distutils.core import setup

setup(
    name = 'python-interactive',
    version = '0.0.2',
    description = 'python embedded interactive porcelain',
    long_description = """
        *python-interactive* is a wrapper around code and cmd to provide porcelain facades for
        embedding real-time python interpreters into your python code.
    """,
    author = 'Chad Oakely Hughes',
    author_email = 'tc50cal@gmail.com',
    license = '3-clause BSD License',
    classifiers = [
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: DFSG approved",
        "License :: OSI Approved :: BSD License",
        "Natural Language :: English",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 2",
        "Topic :: Communications",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Software Development :: Object Brokering",
    ],
    files = ['interactive']
)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f4f4f4"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/vs_ly"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ebf5fe">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:layout_weight="2">

            <TextView
                android:id="@+id/house_mavb_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="83312548340"
                android:textColor="#3c3c3b"
                android:textSize="12sp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/show_ly"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:layout_weight="1.5">

            <TextView
                android:id="@+id/house_fdate_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="2017-08-31 10:33"
                android:textColor="#3c3c3b"
                android:textSize="12sp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:layout_weight="1.5">

            <TextView
                android:id="@+id/house_fno_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:text="CA2563"
                android:textColor="#3c3c3b"
                android:textSize="12sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:layout_weight="1.5">

            <TextView
                android:id="@+id/house_opdate_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:text="2017-09-20 13:20"
                android:textColor="#3c3c3b"
                android:textSize="12sp" />
        </LinearLayout>

    </LinearLayout>

</LinearLayout>


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Radium from 'radium'

// Only old-style imports for react-icons seem to work with gulp
import FaExpand from 'react-icons/lib/fa/expand'

const steps = 100 // Slider steps

function makeStyles (primary) {
  return {
    controls: {
      position: 'absolute',
      bottom: '40px',
      left: '15px',
      zIndex: 100
    },
    sliderWrapper: {
      backgroundColor: 'white',
      color: primary,
      border: `solid 1px lightgray`,
      padding: '6.5px',
      marginRight: '15px',
      MozUserSelect: 'none',
      WebkitUserSelect: 'none',
      msUserSelect: 'none'
    },
    slider: {
      position: 'relative',
      top: 3,
      marginLeft: 5,
      marginRight: 5
    },
    button: {
      backgroundColor: 'white',
      color: primary,
      border: `solid 1px lightgray`,
      outline: 'none',
      position: 'absolute',
      width: 31,
      height: 31,
      top: -3
    }
  }
}

class GraphControls extends Component {
  static propTypes = {
    primary: PropTypes.string,
    minZoom: PropTypes.number,
    maxZoom: PropTypes.number,
    zoomLevel: PropTypes.number.isRequired,
    zoomToFit: PropTypes.func.isRequired,
    modifyZoom: PropTypes.func.isRequired
  }

  static defaultProps = {
    primary: 'dodgerblue',
    minZoom: 0.15,
    maxZoom: 1.5
  }

  constructor (props) {
    super(props)
    this.state = {
      styles: makeStyles(props.primary)
    }
    this.zoom = this.zoom.bind(this)
  }

  // Convert slider val (0-steps) to original zoom value range
  sliderToZoom (val) {
    return ((val) * (this.props.maxZoom - this.props.minZoom) / steps) + this.props.minZoom
  }

  // Convert zoom val (minZoom-maxZoom) to slider range
  zoomToSlider (val) {
    return (val - this.props.minZoom) * steps / (this.props.maxZoom - this.props.minZoom)
  }

  // Center graph-view on contents of svg > view
  zoomToFit () {
    this.props.zoomToFit()
  }

  // Modify current zoom of graph-view
  zoom (e) {
    const sliderVal = e.target.value
    const zoomLevelNext = this.sliderToZoom(sliderVal)
    const delta = zoomLevelNext - this.props.zoomLevel
    if (zoomLevelNext <= this.props.maxZoom && zoomLevelNext >= this.props.minZoom) {
      this.props.modifyZoom(delta)
    }
  }

  render () {
    const styles = this.state.styles
    return (

          -
          <input
            id='typeinp'
            type='range'
            style={styles.slider}
            min={this.zoomToSlider(this.props.minZoom)}
            max={this.zoomToSlider(this.props.maxZoom)}
            value={this.zoomToSlider(this.props.zoomLevel)}
            onChange={this.zoom}
            step='1'
          />
          +

        <button style={styles.button} onMouseDown={this.props.zoomToFit}>
          <FaExpand />
        </button>

    )
  }
}

export default Radium(GraphControls)


text:
package io.opentracing.noop;

import io.opentracing.Span;
import io.opentracing.SpanContext;

import java.util.Map;

public interface NoopSpan extends Span {
    static final NoopSpan INSTANCE = new NoopSpanImpl();
}

final class NoopSpanImpl implements NoopSpan {

    @Override
    public SpanContext context() { return NoopSpanContextImpl.INSTANCE; }

    @Override
    public void finish() {}

    @Override
    public void finish(long finishMicros) {}

    @Override
    public NoopSpan setTag(String key, String value) { return this; }

    @Override
    public NoopSpan setTag(String key, boolean value) { return this; }

    @Override
    public NoopSpan setTag(String key, Number value) { return this; }

    @Override
    public NoopSpan log(Map<String, ?> fields) { return this; }

    @Override
    public NoopSpan log(long timestampMicroseconds, Map<String, ?> fields) { return this; }

    @Override
    public NoopSpan log(String event) { return this; }

    @Override
    public NoopSpan log(long timestampMicroseconds, String event) { return this; }

    @Override
    public NoopSpan setBaggageItem(String key, String value) { return this; }

    @Override
    public String getBaggageItem(String key) { return null; }

    @Override
    public NoopSpan setOperationName(String operationName) { return this; }

    @Override
    public String toString() { return NoopSpan.class.getSimpleName(); }
}


text:
/*
 * ARTIK Cloud API
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: 2.0.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package cloud.artik.model;

import java.util.Objects;
import cloud.artik.model.TaskList;
import cloud.artik.model.TasksStatusCounts;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 *
 */
@ApiModel(description = "")

public class TaskListEnvelope {
  @SerializedName("total")
  private Integer total = null;

  @SerializedName("data")
  private TaskList data = null;

  @SerializedName("statusCounts")
  private TasksStatusCounts statusCounts = null;

  @SerializedName("offset")
  private Integer offset = null;

  @SerializedName("count")
  private Integer count = null;

  public TaskListEnvelope total(Integer total) {
    this.total = total;
    return this;
  }

   /**
   * Total
   * @return total
  **/
  @ApiModelProperty(example = "null", value = "Total")
  public Integer getTotal() {
    return total;
  }

  public void setTotal(Integer total) {
    this.total = total;
  }

  public TaskListEnvelope data(TaskList data) {
    this.data = data;
    return this;
  }

   /**
   * Envelope for task list
   * @return data
  **/
  @ApiModelProperty(example = "null", value = "Envelope for task list")
  public TaskList getData() {
    return data;
  }

  public void setData(TaskList data) {
    this.data = data;
  }

  public TaskListEnvelope statusCounts(TasksStatusCounts statusCounts) {
    this.statusCounts = statusCounts;
    return this;
  }

   /**
   * Status counts
   * @return statusCounts
  **/
  @ApiModelProperty(example = "null", value = "Status counts")
  public TasksStatusCounts getStatusCounts() {
    return statusCounts;
  }

  public void setStatusCounts(TasksStatusCounts statusCounts) {
    this.statusCounts = statusCounts;
  }

  public TaskListEnvelope offset(Integer offset) {
    this.offset = offset;
    return this;
  }

   /**
   * Offset
   * @return offset
  **/
  @ApiModelProperty(example = "null", value = "Offset")
  public Integer getOffset() {
    return offset;
  }

  public void setOffset(Integer offset) {
    this.offset = offset;
  }

  public TaskListEnvelope count(Integer count) {
    this.count = count;
    return this;
  }

   /**
   * Count
   * @return count
  **/
  @ApiModelProperty(example = "null", value = "Count")
  public Integer getCount() {
    return count;
  }

  public void setCount(Integer count) {
    this.count = count;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    TaskListEnvelope taskListEnvelope = (TaskListEnvelope) o;
    return Objects.equals(this.total, taskListEnvelope.total) &&
        Objects.equals(this.data, taskListEnvelope.data) &&
        Objects.equals(this.statusCounts, taskListEnvelope.statusCounts) &&
        Objects.equals(this.offset, taskListEnvelope.offset) &&
        Objects.equals(this.count, taskListEnvelope.count);
  }

  @Override
  public int hashCode() {
    return Objects.hash(total, data, statusCounts, offset, count);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class TaskListEnvelope {\n");

    sb.append("    total: ").append(toIndentedString(total)).append("\n");
    sb.append("    data: ").append(toIndentedString(data)).append("\n");
    sb.append("    statusCounts: ").append(toIndentedString(statusCounts)).append("\n");
    sb.append("    offset: ").append(toIndentedString(offset)).append("\n");
    sb.append("    count: ").append(toIndentedString(count)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


text:
layout: page
title: Mejia Ranger International Seminar
date: 2016-05-24
author: Joseph Ramirez
tags: weekly links, java
status: published
summary: Interdum et malesuada fames ac ante ipsum primis.
banner: images/banner/wedding.jpg
booking:
  startDate: 07/02/2017
  endDate: 07/04/2017
  ctyhocn: TYSDDHX
  groupCode: MRIS
published: true
---
Duis lorem nunc, egestas ac efficitur quis, posuere sed quam. Morbi fringilla ligula neque, in suscipit est egestas id. Sed eu sagittis velit. Suspendisse potenti. Proin ac nisl est. Proin tempor faucibus elementum. Sed ipsum enim, ornare eu facilisis a, sollicitudin non lorem. Nunc vel tellus porta, sodales urna nec, consequat diam.

* Phasellus pharetra dolor facilisis, pulvinar lorem id, maximus orci
* In tempus sem sit amet massa dictum dapibus
* Donec nec mauris non orci elementum ornare
* Morbi vel velit mollis, finibus nulla sit amet, accumsan diam
* Duis non est lobortis, fermentum quam non, fermentum mauris.

Curabitur in justo sem. Curabitur tortor mi, pharetra ut eros et, rhoncus tincidunt orci. Mauris turpis arcu, blandit a condimentum et, dapibus et justo. Fusce vel massa mattis, dignissim quam vel, elementum mi. In ut nisi mollis, viverra sem vel, pretium tellus. Nulla vitae ligula eget erat finibus ornare. Aliquam egestas posuere odio eget feugiat. Duis at venenatis turpis.


text:
class ChallengesController < ApplicationController

	def index
		@challenges = Challenge.all
		@new_challenge = Challenge.new
		current_user
		# p "GOTCHA" * 10
		p @current_user

	end

	def create
		current_user
		newchallenge = Challenge.create(	title: params["challenge"]["title"],
												  	description: params["challenge"]["description"],
												  	proposer_id: @current_user.id )
		redirect_to :root
	end

end


text:
#ifndef _TWITCURL_H_
#define _TWITCURL_H_

#include <cstdint>
#include <string>
#include <sstream>
#include <cstring>
#include <vector>
#include "oauthlib.h"
#include "curl/curl.h"

/* Few common types used by twitCurl */
namespace twitCurlTypes
{
    typedef enum _eTwitCurlApiFormatType
    {
        eTwitCurlApiFormatJson = 0,
        eTwitCurlApiFormatXml,
        eTwitCurlApiFormatMax
    } eTwitCurlApiFormatType;

    typedef enum _eTwitCurlProtocolType
    {
        eTwitCurlProtocolHttps = 0,
        eTwitCurlProtocolHttp,
        eTwitCurlProtocolMax
    } eTwitCurlProtocolType;
};

/* twitCurl class */
class twitCurl
{
public:
    twitCurl();
    ~twitCurl();

    /* Twitter OAuth authorization methods */
    oAuth& getOAuth();
    bool oAuthRequestToken( std::string& authorizeUrl /* out */ );
    bool oAuthAccessToken();
    bool oAuthHandlePIN( const std::string& authorizeUrl /* in */ );

    /* Twitter login APIs, set once and forget */
    std::string& getTwitterUsername();
    std::string& getTwitterPassword();
    void setTwitterUsername( std::string& userName /* in */ );
    void setTwitterPassword( std::string& passWord /* in */ );

    /* Twitter search APIs */
    bool search( std::string& searchQuery /* in */, std::string resultCount = "" /* in */ );

    /* Twitter status APIs */
    bool statusUpdate( std::string& newStatus /* in */, std::string inReplyToStatusId = "" /* in */ );
    bool statusShowById( std::string& statusId /* in */ );
    bool statusDestroyById( std::string& statusId /* in */ );
    bool retweetById( std::string& statusId /* in */ );

    /* Twitter timeline APIs */
    bool timelineHomeGet( std::string sinceId = ""  /* in */ );
    bool timelinePublicGet();
    bool timelineFriendsGet();
    bool timelineUserGet( bool trimUser /* in */, bool includeRetweets /* in */,
                          unsigned int tweetCount /* in */,
                          std::string userInfo = "" /* in */,
                          bool isUserId = false /* in */ );
    bool featuredUsersGet();
    bool mentionsGet( std::string sinceId = "" /* in */ );

    /* Twitter user APIs */
    bool userLookup( std::vector<std::string> &userInfo /* in */,  bool isUserId = false /* in */ );
    bool userGet( std::string& userInfo /* in */, bool isUserId = false /* in */ );
    bool friendsGet( std::string userInfo = "" /* in */, bool isUserId = false /* in */ );
    bool followersGet( std::string userInfo = "" /* in */, bool isUserId = false /* in */ );

    /* Twitter direct message APIs */
    bool directMessageGet( std::string sinceId = "" /* in */ );
    bool directMessageSend( std::string& userInfo /* in */, std::string& dMsg /* in */, bool isUserId = false /* in */ );
    bool directMessageGetSent();
    bool directMessageDestroyById( std::string& dMsgId /* in */ );

    /* Twitter friendships APIs */
    bool friendshipCreate( std::string& userInfo /* in */, bool isUserId = false /* in */ );
    bool friendshipDestroy( std::string& userInfo /* in */, bool isUserId = false /* in */ );
    bool friendshipShow( std::string& userInfo /* in */, bool isUserId = false /* in */ );

    /* Twitter social graphs APIs */
    bool friendsIdsGet( std::string& nextCursor /* in */,
                        std::string& userInfo /* in */, bool isUserId = false /* in */ );
    bool followersIdsGet( std::string& nextCursor /* in */,
                          std::string& userInfo /* in */, bool isUserId = false /* in */ );

    /* Twitter account APIs */
    bool accountRateLimitGet();
    bool accountVerifyCredGet();

    /* Twitter favorites APIs */
    bool favoriteGet();
    bool favoriteCreate( std::string& statusId /* in */ );
    bool favoriteDestroy( std::string& statusId /* in */ );

    /* Twitter block APIs */
    bool blockCreate( std::string& userInfo /* in */ );
    bool blockDestroy( std::string& userInfo /* in */ );
    bool blockListGet( std::string& nextCursor /* in */,
                        bool includeEntities /* in */, bool skipStatus /* in */ );
    bool blockIdsGet( std::string& nextCursor /* in */, bool stringifyIds /* in */ );

    /* Twitter search APIs */
    bool savedSearchGet();
    bool savedSearchCreate( std::string& query /* in */ );
    bool savedSearchShow( std::string& searchId /* in */ );
    bool savedSearchDestroy( std::string& searchId /* in */ );

    /* Twitter trends APIs (JSON) */
    bool trendsGet(uint32_t id, std::string exclude = "");
    bool trendsAvailableGet();
    bool trendsClosestGet(double latitude, double longitude);

    /* cURL APIs */
    bool isCurlInit();
    void getLastWebResponse( std::string& outWebResp /* out */ );
    void getLastCurlError( std::string& outErrResp /* out */);

    /* Internal cURL related methods */
    int saveLastWebResponse( char*& data, size_t size );

    /* cURL proxy APIs */
    std::string& getProxyServerIp();
    std::string& getProxyServerPort();
    std::string& getProxyUserName();
    std::string& getProxyPassword();
    void setProxyServerIp( std::string& proxyServerIp /* in */ );
    void setProxyServerPort( std::string& proxyServerPort /* in */ );
    void setProxyUserName( std::string& proxyUserName /* in */ );
    void setProxyPassword( std::string& proxyPassword /* in */ );

    /* Clones this object */
    twitCurl* clone();

protected:
    /* cURL data */
    CURL* m_curlHandle;
    char* m_errorBuffer;
    std::string m_callbackData;

    /* cURL flags */
    bool m_curlProxyParamsSet;
    bool m_curlLoginParamsSet;
    bool m_curlCallbackParamsSet;

    /* cURL proxy data */
    std::string m_proxyServerIp;
    std::string m_proxyServerPort;
    std::string m_proxyUserName;
    std::string m_proxyPassword;

    /* Twitter data */
    std::string m_twitterUsername;
    std::string m_twitterPassword;

    /* Twitter API type */
    twitCurlTypes::eTwitCurlApiFormatType m_eApiFormatType;
    twitCurlTypes::eTwitCurlProtocolType m_eProtocolType;

    /* OAuth data */
    oAuth m_oAuth;

    /* Private methods */
    void clearCurlCallbackBuffers();
    void prepareCurlProxy();
    void prepareCurlCallback();
    void prepareCurlUserPass();
    void prepareStandardParams();
    bool performGet( const std::string& getUrl );
    bool performGetInternal( const std::string& getUrl,
                             const std::string& oAuthHttpHeader );
    bool performDelete( const std::string& deleteUrl );
    bool performPost( const std::string& postUrl, std::string dataStr = "" );

    /* Internal cURL related methods */
    static int curlCallback( char* data, size_t size, size_t nmemb, twitCurl* pTwitCurlObj );
};

/* Private functions */
void utilMakeCurlParams( std::string& outStr, std::string& inParam1, std::string& inParam2 );
void utilMakeUrlForUser( std::string& outUrl, const std::string& baseUrl, std::string& userInfo, bool isUserId );

#endif // _TWITCURL_H_


text:
angular
  .module('linuxDash')
  .run(['$rootScope', '$location', function ($rootScope, $location) {

    var key = 'hiddenPlugins'

    var getHiddenPlugins = function () {
      var hiddenPluginsCSV = localStorage.getItem(key) || ''
      return hiddenPluginsCSV.split(',')
    }

    var updateHiddenPlugins = function (hiddenPlugins) {
      localStorage.setItem(key, hiddenPlugins.join(','))
    }

    $rootScope.$on('hide-plugin', function (e, m) {
      var hiddenPlugins = getHiddenPlugins()

      if(hiddenPlugins.indexOf(m) < 0)
        hiddenPlugins.push(m)

      updateHiddenPlugins(hiddenPlugins)
    })

    $rootScope.$on('show-plugin', function (e, m) {
      var hiddenPlugins = getHiddenPlugins()
      var indexOfPlugin = hiddenPlugins.indexOf(m)

      if(indexOfPlugin > -1)
        hiddenPlugins.splice(indexOfPlugin, 1)

      updateHiddenPlugins(hiddenPlugins)
    })

    $rootScope.hiddenPlugins = getHiddenPlugins()

  }])


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.google.caliper</groupId>
  <artifactId>caliper-examples</artifactId>
  <packaging>jar</packaging>
  <version>0.5-rc1</version>
  <inceptionYear>2009</inceptionYear>
  <name>Caliper Examples</name>
  <parent>
    <groupId>org.sonatype.oss</groupId>
    <artifactId>oss-parent</artifactId>
    <version>5</version>
  </parent>
  <url>http://code.google.com/p/caliper/</url>
  <description>Caliper Examples</description>
  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>
  <scm>
    <connection>scm:git:http://code.google.com/p/caliper/examples</connection>
    <developerConnection>scm:git:git:http://code.google.com/p/caliper/examples</developerConnection>
    <url>http://caliper.codegoogle.com/svn/trunk/examples</url>
  </scm>
  <issueManagement>
    <system>Google Code Issue Tracking</system>
    <url>http://code.google.com/p/caliper/issues/list</url>
  </issueManagement>
  <organization>
    <name>Google, Inc.</name>
    <url>http://www.google.com</url>
  </organization>
  <dependencies>
    <dependency>
      <groupId>com.google.caliper</groupId>
      <artifactId>caliper</artifactId>
      <version>0.5-rc1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <defaultGoal>package</defaultGoal>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.8</version>
        <configuration>
          <downloadSources>true</downloadSources>
          <downloadJavadocs>true</downloadJavadocs>
          <workspace>../eclipse-ws/</workspace>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <arguments>-DenableCiProfile=true</arguments>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <developers>
    <developer>
      <name>Jesse Wilson</name>
      <organization>Google Inc.</organization>
    </developer>
  </developers>
</project>


text:
"ColumnRemove filter"

from .abstract import AbstractFilter

class ColumnRemove(AbstractFilter):
    "Remove a specific column from a flux"
    name = 'Retrait de colonne'
    description = "Retire une colonne d'un flux"

    node_in = ['origine']
    node_out = ['reste']

    parameters = [
        {
            'name': 'Colonne',
            'key': 'column',
            'type': 'string'
        }
    ]

    def run(self):
        "Execute the filter"
        origin = self._flux_in['contenu']
        column = self._param('column')
        column_id = origin['headers'].index(column)
        self._flux_out['reste'] = {
            'headers': origin['headers'][:column_id] + origin['headers'][column_id + 1:],
            'rows': [
                [
                    cell for ind, cell in enumerate(row) if ind != column_id
                ] for row in origin['rows']
            ]
        }


text:
<?php

namespace AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class TestingControllerTest extends WebTestCase
{
    public function testGetValueAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/testing/get_value');

        $this->assertGreaterThan(
            999,
            $client->getResponse()->getContent()
        );
    }

    public function testGetHtml()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/testing/get_html');

        $this->assertCount(3, $crawler->filter('div'));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
 Copyright 2011 Robert Theis

 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.
 -->
<resources>
    <string-array name="copy_part">
        <item>Ligne de code</item>
        <item>Numéro de référence</item>
    </string-array>
</resources>


text:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/**
 *
 * @author romis_000, Johan
 */
public class ConvexPolygon {

    private ArrayList<PointDouble> points = new ArrayList<PointDouble>();

    public ConvexPolygon(ArrayList<PointDouble> points) {
        this.points = points;
    }

    public ArrayList<PointDouble> getPointDoubles() {
        return points;
    }

    public double[] GetXPointDoubles() {
        double xpoints[] = new double[this.points.size()];
        int c = 0;
        for (PointDouble p : this.points) {
            xpoints[c] = p.x;
            ++c;
        }
        return xpoints;
    }

    public double[] GetYPointDoubles() {
        double ypoints[] = new double[this.points.size()];
        int c = 0;
        for (PointDouble p : this.points) {
            ypoints[c] = p.y;
            ++c;
        }
        return ypoints;
    }

    public double[][] getVertices() {
        double[][] vertices = new double[points.size()][2];
        for (int i = 0; i < points.size(); ++i) {
            vertices[i][0] = points.get(i).x;
            vertices[i][1] = points.get(i).y;
        }
        return vertices;
    }

    /**
     * Returns the axis corresponding to the edges of the polygon, used to check
     * for detection collision
     */
    public PointDouble[] Getaxes() {
        PointDouble[] axes = new PointDouble[this.points.size()];
        for (int i = 0; i < this.points.size(); i++) {
            // get the current vertex
            PointDouble v1 = new PointDouble(this.points.get(i).getX(), this.points.get(i).getY());
            // get the next vertex
            PointDouble v2 = new PointDouble(this.points.get(i + 1 == this.points.size() ? 0 : i + 1).getX(), this.points.get(i + 1 == this.points.size() ? 0 : i + 1).getY());
            // subtract the two to get the edge vector
            PointDouble edge = new PointDouble((v1.x + (-v2.x)), (v1.y + (-v2.y)));
            // get either perpendicular vector
            PointDouble normal = new PointDouble((-edge.y), edge.x);
            // the perp method is just (x, y) => (-y, x) or (y, -x)
            axes[i] = normal;
        }
        return axes;
    }

    /**
     * Checks if the polygon is convex
     */
    public boolean isConvex() {
        PointDouble prev = points.get(points.size() - 2);
        PointDouble curr = points.get(points.size() - 1);
        PointDouble next = points.get(0);
        // Are the first two selected edges making a turnleft ?
        boolean isCCW = turnLeft(prev, curr, next);
        // Verify if all the edges are making the same type of angle as the first two
        for (int i = 1; i < points.size(); i++) {
            prev = curr;
            curr = next;
            next = points.get(i);
            if (turnLeft(prev, curr, next) != isCCW) {
                return false;
            }
        }
        return true;
    }

    /**
     * Checks if a given point is within the polygon
     */
    public boolean contain(PointDouble p) {
        PointDouble prev = points.get(points.size() - 1);
        PointDouble curr = p;
        PointDouble next = points.get(0);
        // Is the point left or right of the selected edge ?
        boolean isCCW = turnLeft(prev, curr, next);
        // Is the point the same side of every other edges of the polygon ?
        for (int i = 1; i < points.size(); i++) {
            prev = next;
            next = points.get(i);
            if (turnLeft(prev, curr, next) != isCCW) {
                return false;
            }
        }
        return true;
    }

    /**
     * Check the sign of the angle between vectors [p1, p2] and [p2, p3]
     * with the cross product
     */
    public boolean turnLeft(PointDouble p1, PointDouble p2, PointDouble p3) {
        return ((p2.getX() - p1.getX()) * (p3.getY()
                - p2.getY()) - (p3.getX() - p2.getX()) * (p2.getY() - p1.getY())) > 0;
    }

    /**
     * Checks if the vertices of the polygon are in counter-clock wise order
     * The vertices of the polygon need to be sorted for this test
     */
    public boolean isCCW() {
        double min = points.get(0).getY();
        int minIndex = 0;
        for (int i = 1; i < points.size() - 1; i++) {
            if (points.get(i).getY() < min) {
                min = points.get(i).getY();
                minIndex = i;
            }
        }
        PointDouble prev = points.get((minIndex - 1 + points.size()) % points.size());
        PointDouble next = points.get((minIndex + 1) % points.size());
        return turnLeft(prev, points.get(minIndex), next);
    }

    /**
     * Calculates the convex hull of list of points
     * Using the monotone chain algorithm
     */
    public ConvexPolygon convexHull(ArrayList<PointDouble> points) {
        Collections.sort(points, new PointXCompare());
        int n = points.size();

        ArrayList<PointDouble> pl1 = new ArrayList<PointDouble>();
        ArrayList<PointDouble> pl2 = new ArrayList<PointDouble>();
        for (int i = 0; i < n; i++) {
            while (pl2.size() >= 2 && !(turnLeft(pl2.get(pl2.size() - 2), pl2.get(pl2.size() - 1), points.get(i)))) {
                pl2.remove(pl2.get(pl2.size() - 1));
            }
            pl2.add(points.get(i));
        }
        for (int i = n - 1; i >= 0; i--) {
            while (pl1.size() >= 2 && !(turnLeft(pl1.get(pl1.size() - 2), pl1.get(pl1.size() - 1), points.get(i)))) {
                pl1.remove(pl1.get(pl1.size() - 1));
            }
            pl1.add(points.get(i));
        }
        pl1.remove(pl1.size() - 1);
        pl2.remove(pl2.size() - 1);
        pl2.addAll(pl1);
        return new ConvexPolygon(pl2);
    }

    /**
     * Translates the polygon from the given numbers
     */
    public void translate(double x, double y) {
        for (PointDouble p : this.points) {
            p.x += x;
            p.y += y;
        }
    }

    /**
     * Checks for an intersection between the polygon and the second given
     * polygon
     */
    public Boolean intersects(ConvexPolygon pol2) {
        PointDouble[] axes1 = this.Getaxes();
        PointDouble[] axes2 = pol2.Getaxes();
        for (int i = 0; i < axes1.length; i++) {
            PointDouble axis = axes1[i];
            // project both shapes onto the axis
            Projection p1 = this.project(axis);
            Projection p2 = pol2.project(axis);
            // do the projections overlap?
            if (!p1.overlap(p2)) {
                // then we can guarantee that the shapes do not overlap
                return false;
            }
        }
        for (int i = 0; i < axes2.length; i++) {
            PointDouble axis = axes2[i];
            Projection p1 = this.project(axis);
            Projection p2 = pol2.project(axis);
            if (!p1.overlap(p2)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Generates a projection of an edge of the polygon on a given axis
     */
    public Projection project(PointDouble axis) {
        double min = ((axis.x * this.points.get(0).x) + (axis.y * this.points.get(0).y));
        double max = min;
        for (int i = 1; i < this.points.size(); i++) {
            double p = ((axis.x * this.points.get(i).x) + (axis.y * this.points.get(i).y));
            if (p < min) {
                min = p;
            } else if (p > max) {
                max = p;
            }
        }
        Projection proj = new Projection(min, max);
        return proj;
    }

    public Boolean hasVertex(PointDouble pt) {
        for (int i = 0; i < this.points.size(); i++) {
            //for (int i = 0; i < this.points.size() - 1; i++) {
            if (this.points.get(i).equals(pt)) {
                return true;
            }
        }
        return false;
    }

    public Boolean deleteVertex(PointDouble pt) {
        if (this.points.size() > 3) {
            for (int i = 0; i < this.points.size(); i++) {
                if (this.points.get(i).equals(pt)) {
                    this.points.remove(i);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Sorts the vertices of the polygon in an order specified by the sorter
     * used
     */
    public void sortVertices(PolygonSorter sorter) {
        PointDouble[] arrPointDoubles = points.toArray(new PointDouble[points.size()]);
        Arrays.sort(arrPointDoubles, sorter);
        this.points.clear();
        points.addAll(Arrays.asList(arrPointDoubles));
    }

    /*
    * Add a vertex to the polygon
    * Return true if the vertex is added to the polygon
    * Return false otherwise, which means that the addition
    * of the vertex would have made it concave.
    */
    public Boolean addVertex(PointDouble pt) {
        // Make a temporary list to check some properties of the new polygon
        ArrayList<PointDouble> tempList = new ArrayList<>(Arrays.asList(this.points.toArray(new PointDouble[this.points.size()])));
        tempList.add(pt);
        // Create a temporary polygon
        ConvexPolygon tempPolygon = new ConvexPolygon(tempList);
        // Sort it
        tempPolygon.sortVertices(new AntiClockSort(tempPolygon.getVertices()));
        // We need the new polygon to be convex, or we can't accept to add the new vertex.
        if (tempPolygon.isConvex()) {
            this.points = tempPolygon.points;
            return true;
        } else {
            return false;
        }
    }
}


text:
@interface MWKSearchResult ()

@property (nonatomic, assign, readwrite) NSInteger articleID;

@property (nonatomic, copy, readwrite) NSString* displayTitle;

@property (nonatomic, copy, readwrite) NSString* wikidataDescription;

@property (nonatomic, copy, readwrite) NSString* extract;

@property (nonatomic, copy, readwrite) NSURL* thumbnailURL;

@property (nonatomic, copy, readwrite) NSNumber* index;

@property (nonatomic, copy, readwrite) NSNumber* titleNamespace;

@property (nonatomic, assign, readwrite) BOOL isDisambiguation;

@property (nonatomic, assign, readwrite) BOOL isList;

@end

@implementation MWKSearchResult

- (instancetype)initWithArticleID:(NSInteger)articleID
                     displayTitle:(NSString*)displayTitle
              wikidataDescription:(NSString*)wikidataDescription
                          extract:(NSString*)extract
                     thumbnailURL:(NSURL*)thumbnailURL
                            index:(NSNumber*)index
                 isDisambiguation:(BOOL)isDisambiguation
                           isList:(BOOL)isList
                   titleNamespace:(NSNumber*)titleNamespace {
    self = [super init];
    if (self) {
        self.articleID           = articleID;
        self.displayTitle        = displayTitle;
        self.wikidataDescription = wikidataDescription;
        self.extract             = extract;
        self.thumbnailURL        = thumbnailURL;
        self.index               = index;
        self.isDisambiguation    = isDisambiguation;
        self.isList              = isList;
        self.titleNamespace      = titleNamespace;
    }
    return self;
}

#pragma mark - MTLJSONSerializing

+ (NSValueTransformer*)thumbnailURLJSONTransformer {
    return [MTLValueTransformer
            transformerUsingForwardBlock:^NSURL* (NSString* urlString,
                                                  BOOL* success,
                                                  NSError* __autoreleasing* error) {
        return [NSURL wmf_optionalURLWithString:urlString];
    }
                            reverseBlock:^NSString* (NSURL* thumbnailURL,
                                                     BOOL* success,
                                                     NSError* __autoreleasing* error) {
        return [thumbnailURL absoluteString];
    }];
}

+ (NSValueTransformer*)wikidataDescriptionJSONTransformer {
    return [MTLValueTransformer transformerUsingForwardBlock:^id (NSArray* value, BOOL* success, NSError* __autoreleasing* error) {
        NSString* description = [value firstObject];
        return [description wmf_stringByCapitalizingFirstCharacter];
    }];
}

+ (MTLValueTransformer*)extractJSONTransformer {
    return [MTLValueTransformer transformerUsingForwardBlock:^id (NSString* extract, BOOL* success, NSError* __autoreleasing* error) {
        // HAX: sometimes the api gives us "..." for the extract, which is not useful and messes up how random
        // weights relative quality of the random titles it retrieves.
        if ([extract isEqualToString:@"..."]) {
            extract = nil;
        }

        return [extract wmf_summaryFromText];
    }];
}

+ (NSValueTransformer*)isDisambiguationJSONTransformer {
    return [MTLValueTransformer
            transformerUsingForwardBlock:^(NSDictionary* value, BOOL* success, NSError** error) {
        NSString* disambiguation = value[@"pageprops.disambiguation"];
        if (disambiguation) {
            return @YES;
        }
        // HAX: occasionally the search api doesn't report back "disambiguation" page term ( T121288 ),
        // so double-check wiki data description for "disambiguation page" string.
        NSArray* descriptions = value[@"terms.description"];
        return @(descriptions.count && [descriptions.firstObject containsString:@"disambiguation page"]);
    }];
}

+ (NSValueTransformer*)isListJSONTransformer {
    return [MTLValueTransformer
            transformerUsingForwardBlock:^(NSArray* value, BOOL* success, NSError** error) {
        // HAX: check wiki data description for "Wikimedia list article" string. Not perfect
        // and enwiki specific, but confirmed with max that without doing separate wikidata query, there's no way to tell if it's a list at the moment.
        return @(value.count && [value.firstObject containsString:@"Wikimedia list article"]);
    }];
}

+ (NSDictionary*)JSONKeyPathsByPropertyKey {
    return @{WMF_SAFE_KEYPATH(MWKSearchResult.new, displayTitle): @"title",
             WMF_SAFE_KEYPATH(MWKSearchResult.new, articleID): @"pageid",
             WMF_SAFE_KEYPATH(MWKSearchResult.new, thumbnailURL): @"thumbnail.source",
             WMF_SAFE_KEYPATH(MWKSearchResult.new, wikidataDescription): @"terms.description",
             WMF_SAFE_KEYPATH(MWKSearchResult.new, extract): @"extract",
             WMF_SAFE_KEYPATH(MWKSearchResult.new, index): @"index",
             WMF_SAFE_KEYPATH(MWKSearchResult.new, isDisambiguation): @[@"pageprops.disambiguation", @"terms.description"],
             WMF_SAFE_KEYPATH(MWKSearchResult.new, isList): @"terms.description",
             WMF_SAFE_KEYPATH(MWKSearchResult.new, titleNamespace): @"ns"};
}

@end


text:
#import "EC2Response.h"
#import "../AmazonServiceExceptionUnmarshaller.h"

/**
 * Get Password Data Response
 *
 * \ingroup EC2
 */

@interface EC2GetPasswordDataResponse:EC2Response

{
    NSString *instanceId;
    NSDate   *timestamp;
    NSString *passwordData;
}

-(void)setException:(AmazonServiceException *)theException;

/**
 * Default constructor for a new  object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * The ID of the instance whose Windows administrator password was
 * requested.
 */
@property (nonatomic, retain) NSString *instanceId;

/**
 * The time the data was last updated.
 */
@property (nonatomic, retain) NSDate *timestamp;

/**
 * The Windows administrator password of the specified instance.
 */
@property (nonatomic, retain) NSString *passwordData;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
{% extends 'base.html' %}

{%  block todo_active %}green lighten-5{% endblock %}

{% block todo_inner %}

목록

달력

{% endblock %}


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

namespace Melanchall.DryWetMidi.Multimedia
{
    internal sealed class VirtualDeviceApi64 : VirtualDeviceApi
    {
        #region Constants

        private const string LibraryName = LibraryName64;

        #endregion

        #region Extern functions

        [DllImport(LibraryName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
        private static extern VIRTUAL_OPENRESULT OpenVirtualDevice_Mac(IntPtr name, IntPtr sessionHandle, Callback_Mac callback, out IntPtr info);

        [DllImport(LibraryName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
        private static extern VIRTUAL_CLOSERESULT CloseVirtualDevice(IntPtr info);

        [DllImport(LibraryName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
        private static extern VIRTUAL_SENDBACKRESULT SendDataBackFromVirtualDevice(IntPtr pktlist, IntPtr readProcRefCon);

        [DllImport(LibraryName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
        private static extern IntPtr GetInputDeviceInfoFromVirtualDevice(IntPtr info);

        [DllImport(LibraryName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
        private static extern IntPtr GetOutputDeviceInfoFromVirtualDevice(IntPtr info);

        #endregion

        #region Methods

        public override VIRTUAL_OPENRESULT Api_OpenDevice_Mac(string name, IntPtr sessionHandle, Callback_Mac callback, out IntPtr info)
        {
            var namePointer = Marshal.StringToHGlobalAnsi(name);
            return OpenVirtualDevice_Mac(namePointer, sessionHandle, callback, out info);
        }

        public override VIRTUAL_CLOSERESULT Api_CloseDevice(IntPtr info)
        {
            return CloseVirtualDevice(info);
        }

        public override VIRTUAL_SENDBACKRESULT Api_SendDataBack(IntPtr pktlist, IntPtr readProcRefCon)
        {
            return SendDataBackFromVirtualDevice(pktlist, readProcRefCon);
        }

        public override IntPtr Api_GetInputDeviceInfo(IntPtr info)
        {
            return GetInputDeviceInfoFromVirtualDevice(info);
        }

        public override IntPtr Api_GetOutputDeviceInfo(IntPtr info)
        {
            return GetOutputDeviceInfoFromVirtualDevice(info);
        }

        #endregion
    }
}


text:
#import <BaiduBCEBasic/BCECredentials.h>

/**
 *  @brief Provides access to the BCE credentials used for accessing BCE services: BCE access key ID,
 *         secret access key and session token.
 *         These credentials are used to securely sign requests to BCE services.
 */
@interface BCESTSCredentials : BCECredentials

/**
 *  @brief The session token for this credentials object.
 */
@property(nonatomic, copy) NSString* sessionToken;

/**
 *  @brief The expiration time for this credentials object.
 */
@property(nonatomic, copy) NSString* expiration;

/**
 *  @brief The user ID for this credentials object.
 */
@property(nonatomic, copy) NSString* userId;

@end


text:
{#Example Framework Footer#}
{% load static %}
{%  include 'limbo/framework.html' %}
{%  if SETTINGS.DEBUG  or SETTINGS.NON_COMPILED_JS or request.user.is_superuser %}
    {%  for js in SETTINGS.JAVASCRIPTS %}
        <script type="text/javascript" charset="utf-8" src="{% get_static_prefix %}js/{{ js }}" ></script>
    {%  endfor %}
    <script type="text/javascript" charset="utf-8" src="{% get_static_prefix %}js/sugar.js" ></script>
    <script type="text/javascript" charset="utf-8" src="{% get_static_prefix %}js/limbo.datatables.js" ></script>
    <script type="text/javascript" charset="utf-8" src="{% get_static_prefix %}js/limbo.dialog-box.js" ></script>
    <script type="text/javascript" charset="utf-8" src="{% get_static_prefix %}js/ui.limbo.js" ></script>
    <script type="text/javascript" charset="utf-8" src="{% get_static_prefix %}js/limbo.js" ></script>
{%  else %}
    <script type="text/javascript" charset="utf-8" src="{% get_static_prefix %}js/limbo.min.js"></script>
{%  endif %}