text:
//******************************************************************************************************
//  ScreenArea.cs - Gbtc
//
//  Copyright © 2012, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  10/01/2008 - J. Ritchie Carroll
//       Generated original version of source code.
//  08/10/2009 - Josh L. Patterson
//       Edited Comments.
//  09/14/2009 - Stephen C. Wills
//       Added new header and license agreement.
//  12/14/2012 - Starlynn Danyelle Gilliam
//       Modified Header.
//
//******************************************************************************************************

using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using GSF.Drawing;

namespace GSF.Windows.Forms
{
    /// <summary>Returns screen area statistics and capture functionality for all connected screens.</summary>
    public static class ScreenArea
    {
        /// <summary>
        /// Gets the least "x" coordinate of all screens on the system
        /// </summary>
        /// <returns>The smallest visible "x" screen coordinate</returns>
        public static int LeftMostBound
        {
            get
            {
                int leftBound = int.MaxValue;

                // Return the left-most "x" screen coordinate
                foreach (Screen display in Screen.AllScreens)
                {
                    if (leftBound > display.Bounds.X)
                        leftBound = display.Bounds.X;
                }

                return leftBound;
            }
        }

        /// <summary>
        /// Gets the greatest "x" coordinate of all screens on the system
        /// </summary>
        /// <returns>The largest visible "x" screen coordinate</returns>
        public static int RightMostBound
        {
            get
            {
                int rightBound = int.MinValue;

                // Return the right-most "x" screen coordinate
                foreach (Screen display in Screen.AllScreens)
                {
                    if (rightBound < display.Bounds.X + display.Bounds.Width)
                        rightBound = display.Bounds.X + display.Bounds.Width;
                }

                return rightBound;
            }
        }

        /// <summary>
        /// Gets the least "y" coordinate of all screens on the system
        /// </summary>
        /// <returns>The smallest visible "y" screen coordinate</returns>
        public static int TopMostBound
        {
            get
            {
                int topBound = int.MaxValue;

                // Return the top-most "y" screen coordinate
                foreach (Screen display in Screen.AllScreens)
                {
                    if (topBound > display.Bounds.Y)
                        topBound = display.Bounds.Y;
                }

                return topBound;
            }
        }

        /// <summary>
        /// Gets the greatest "y" coordinate of all screens on the system
        /// </summary>
        /// <returns>The largest visible "y" screen coordinate</returns>
        public static int BottomMostBound
        {
            get
            {
                int bottomBound = int.MinValue;

                // Return the bottom-most "y" screen coordinate
                foreach (Screen display in Screen.AllScreens)
                {
                    if (bottomBound < display.Bounds.Y + display.Bounds.Height)
                        bottomBound = display.Bounds.Y + display.Bounds.Height;
                }

                return bottomBound;
            }
        }

        /// <summary>
        /// Gets the width of the screen with the highest resolution.
        /// </summary>
        /// <returns>The width of the screen with the highest resolution.</returns>
        public static int MaximumWidth
        {
            get
            {
                int maxWidth = int.MinValue;

                // In this case we just get the largest screen height
                foreach (Screen display in Screen.AllScreens)
                {
                    if (maxWidth < display.Bounds.Width)
                        maxWidth = display.Bounds.Width;
                }

                return maxWidth;
            }
        }

        /// <summary>
        /// Gets the width of the screen with the lowest resolution.
        /// </summary>
        /// <returns>The width of the screen with the lowest resolution.</returns>
        public static int MinimumWidth
        {
            get
            {
                int minWidth = int.MaxValue;

                // In this case we just get the smallest screen height
                foreach (Screen display in Screen.AllScreens)
                {
                    if (minWidth > display.Bounds.Width)
                        minWidth = display.Bounds.Width;
                }

                return minWidth;
            }
        }

        /// <summary>
        /// Gets the height of the screen with the highest resolution.
        /// </summary>
        /// <returns>The height of the screen with the highest resolution.</returns>
        public static int MaximumHeight
        {
            get
            {
                int maxHeight = int.MinValue;

                // In this case we just get the largest screen height
                foreach (Screen display in Screen.AllScreens)
                {
                    if (maxHeight < display.Bounds.Height)
                        maxHeight = display.Bounds.Height;
                }

                return maxHeight;
            }
        }

        /// <summary>
        /// Gets the height of the screen with the lowest resolution.
        /// </summary>
        /// <returns>The height of the screen with the lowest resolution.</returns>
        public static int MinimumHeight
        {
            get
            {
                int minHeight = int.MaxValue;

                // In this case we just get the smallest screen height
                foreach (Screen display in Screen.AllScreens)
                {
                    if (minHeight > display.Bounds.Height)
                        minHeight = display.Bounds.Height;
                }

                return minHeight;
            }
        }

        /// <summary>
        /// Gets the total width of all the screens relative to their arrangement.
        /// </summary>
        /// <returns>The total width of all the screens relative to their arrangement.</returns>
        public static int TotalWidth
        {
            get
            {
                return RightMostBound - LeftMostBound;
            }
        }

        /// <summary>
        /// Gets the total height of all the screens relative to their arrangement.
        /// </summary>
        /// <returns>The total height of all the screens relative to their arrangement.</returns>
        public static int TotalHeight
        {
            get
            {
                return BottomMostBound - TopMostBound;
            }
        }

        /// <summary>
        /// Performs screen capture over all monitors.
        /// </summary>
        /// <returns>Captured screen image over all monitors.</returns>
        /// <remarks>
        /// Size captured will be for total width and height of all screens relative to their arrangement.
        /// An image square will be created large enough to cover all screens for the capture.
        /// </remarks>
        public static Bitmap Capture()
        {
            return Capture(new Rectangle(LeftMostBound, TopMostBound, TotalWidth, TotalHeight));
        }

        /// <summary>
        /// Performs screen capture over all monitors.
        /// </summary>
        /// <param name="imageFormat">Desired <see cref="ImageFormat"/> for captured <see cref="Bitmap"/>.</param>
        /// <returns>Captured screen image over all monitors.</returns>
        /// <remarks>
        /// Size captured will be for total width and height of all screens relative to their arrangement.
        /// An image square will be created large enough to cover all screens for the capture.
        /// </remarks>
        public static Bitmap Capture(ImageFormat imageFormat)
        {
            return Capture(new Rectangle(LeftMostBound, TopMostBound, TotalWidth, TotalHeight), imageFormat);
        }

        /// <summary>
        /// Performs screen capture for given <see cref="Screen"/>.
        /// </summary>
        /// <param name="captureScreen">A <see cref="Screen"/> object to capture.</param>
        /// <returns>Captured screen image for given <see cref="Screen"/>.</returns>
        public static Bitmap Capture(Screen captureScreen)
        {
            return Capture(captureScreen.Bounds);
        }

        /// <summary>
        /// Performs screen capture for given <see cref="Screen"/> and <see cref="ImageFormat"/>.
        /// </summary>
        /// <param name="captureScreen">Desired <see cref="Screen"/> to capture</param>
        /// <param name="imageFormat">Desired <see cref="ImageFormat"/> for captured <see cref="Bitmap"/>.</param>
        /// <returns>Captured screen image for given <see cref="Screen"/>.</returns>
        public static Bitmap Capture(Screen captureScreen, ImageFormat imageFormat)
        {
            return Capture(captureScreen.Bounds, imageFormat);
        }

        /// <summary>
        /// Performs a screen capture the given <see cref="Rectangle"/>.
        /// </summary>
        /// <param name="captureArea">Screen area <see cref="Rectangle"/> to capture.</param>
        /// <returns>Captured screen image for given area.</returns>
        public static Bitmap Capture(Rectangle captureArea)
        {
            return Capture(captureArea, ImageFormat.Bmp);
        }

        /// <summary>
        /// Performs a screen capture the given <see cref="Rectangle"/> and <see cref="ImageFormat"/>.
        /// </summary>
        /// <param name="captureArea">Screen area <see cref="Rectangle"/> to capture.</param>
        /// <param name="imageFormat">Desired <see cref="ImageFormat"/> for captured <see cref="Bitmap"/>.</param>
        /// <returns>Captured screen image for given area.</returns>
        public static Bitmap Capture(Rectangle captureArea, ImageFormat imageFormat)
        {
            // Create a blank image of the specified size.
            using (Bitmap screenCaptureImage = new Bitmap(captureArea.Width, captureArea.Height))
            {
                using (Graphics screenCaptureGraphics = Graphics.FromImage(screenCaptureImage))
                {
                    // Copy the area of the screen to the blank image.
                    screenCaptureGraphics.CopyFromScreen(captureArea.X, captureArea.Y, 0, 0, captureArea.Size);
                }

                // We'll return the captured screenshot in the specified image format.
                return screenCaptureImage.ConvertTo(imageFormat, true);
            }
        }
    }
}


text:
import os

from requests_oauthlib import OAuth1Session

def create_oauth_token(expiration=None, scope=None, key=None, secret=None, name=None):
    """
    Script to obtain an OAuth token from Trello.

    Must have TRELLO_API_KEY and TRELLO_API_SECRET set in your environment
    To set the token's expiration, set TRELLO_EXPIRATION as a string in your
    environment settings (eg. 'never'), otherwise it will default to 30 days.

    More info on token scope here:
        https://trello.com/docs/gettingstarted/#getting-a-token-from-a-user
    """
    request_token_url = 'https://trello.com/1/OAuthGetRequestToken'
    authorize_url = 'https://trello.com/1/OAuthAuthorizeToken'
    access_token_url = 'https://trello.com/1/OAuthGetAccessToken'

    expiration = expiration or os.environ.get('TRELLO_EXPIRATION', "30days")
    scope = scope or os.environ.get('TRELLO_SCOPE', 'read,write')
    trello_key = key or os.environ['TRELLO_API_KEY']
    trello_secret = secret or os.environ['TRELLO_API_SECRET']
    name = name or os.environ.get('TRELLO_NAME', 'py-trello')

    # Step 1: Get a request token. This is a temporary token that is used for
    # having the user authorize an access token and to sign the request to obtain
    # said access token.

    session = OAuth1Session(client_key=trello_key, client_secret=trello_secret)
    response = session.fetch_request_token(request_token_url)
    resource_owner_key, resource_owner_secret = response.get('oauth_token'), response.get('oauth_token_secret')

    print("Request Token:")
    print("    - oauth_token        = %s" % resource_owner_key)
    print("    - oauth_token_secret = %s" % resource_owner_secret)
    print("")

    # Step 2: Redirect to the provider. Since this is a CLI script we do not
    # redirect. In a web application you would redirect the user to the URL
    # below.

    print("Go to the following link in your browser:")
    print("{authorize_url}?oauth_token={oauth_token}&scope={scope}&expiration={expiration}&name={name}".format(
        authorize_url=authorize_url,
        oauth_token=resource_owner_key,
        expiration=expiration,
        scope=scope,
        name=name
    ))

    # After the user has granted access to you, the consumer, the provider will
    # redirect you to whatever URL you have told them to redirect to. You can
    # usually define this in the oauth_callback argument as well.

    # Python 3 compatibility (raw_input was renamed to input)
    try:
        inputFunc = raw_input
    except NameError:
        inputFunc = input

    accepted = 'n'
    while accepted.lower() == 'n':
        accepted = inputFunc('Have you authorized me? (y/n) ')
    oauth_verifier = inputFunc('What is the PIN? ')

    # Step 3: Once the consumer has redirected the user back to the oauth_callback
    # URL you can request the access token the user has approved. You use the
    # request token to sign this request. After this is done you throw away the
    # request token and use the access token returned. You should store this
    # access token somewhere safe, like a database, for future use.
    session = OAuth1Session(client_key=trello_key, client_secret=trello_secret,
                            resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret,
                            verifier=oauth_verifier)
    access_token = session.fetch_access_token(access_token_url)

    print("Access Token:")
    print("    - oauth_token        = %s" % access_token['oauth_token'])
    print("    - oauth_token_secret = %s" % access_token['oauth_token_secret'])
    print("")
    print("You may now access protected resources using the access tokens above.")
    print("")

if __name__ == '__main__':
    create_oauth_token()

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from ..tokens import Doc
from ..attrs import ORTH, POS, HEAD, DEP
from ..compat import path2str

import pytest
import numpy
import tempfile
import shutil
import contextlib
import msgpack
from pathlib import Path

MODELS = {}

def load_test_model(model):
    """Load a model if it's installed as a package, otherwise skip."""
    if model not in MODELS:
        module = pytest.importorskip(model)
        MODELS[model] = module.load()
    return MODELS[model]

@contextlib.contextmanager
def make_tempfile(mode='r'):
    f = tempfile.TemporaryFile(mode=mode)
    yield f
    f.close()

@contextlib.contextmanager
def make_tempdir():
    d = Path(tempfile.mkdtemp())
    yield d
    shutil.rmtree(path2str(d))

def get_doc(vocab, words=[], pos=None, heads=None, deps=None, tags=None, ents=None):
    """Create Doc object from given vocab, words and annotations."""
    pos = pos or [''] * len(words)
    tags = tags or [''] * len(words)
    heads = heads or [0] * len(words)
    deps = deps or [''] * len(words)
    for value in (deps+tags+pos):
        vocab.strings.add(value)

    doc = Doc(vocab, words=words)
    attrs = doc.to_array([POS, HEAD, DEP])
    for i, (p, head, dep) in enumerate(zip(pos, heads, deps)):
        attrs[i, 0] = doc.vocab.strings[p]
        attrs[i, 1] = head
        attrs[i, 2] = doc.vocab.strings[dep]
    doc.from_array([POS, HEAD, DEP], attrs)
    if ents:
        doc.ents = [(ent_id, doc.vocab.strings[label], start, end) for ent_id, label, start, end in ents]
    if tags:
        for token in doc:
            token.tag_ = tags[token.i]
    return doc

def apply_transition_sequence(parser, doc, sequence):
    """Perform a series of pre-specified transitions, to put the parser in a
    desired state."""
    for action_name in sequence:
        if '-' in action_name:
            move, label = action_name.split('-')
            parser.add_label(label)
    with parser.step_through(doc) as stepwise:
        for transition in sequence:
            stepwise.transition(transition)

def add_vecs_to_vocab(vocab, vectors):
    """Add list of vector tuples to given vocab. All vectors need to have the
    same length. Format: [("text", [1, 2, 3])]"""
    length = len(vectors[0][1])
    vocab.reset_vectors(width=length)
    for word, vec in vectors:
        vocab.set_vector(word, vector=vec)
    return vocab

def get_cosine(vec1, vec2):
    """Get cosine for two given vectors"""
    return numpy.dot(vec1, vec2) / (numpy.linalg.norm(vec1) * numpy.linalg.norm(vec2))

def assert_docs_equal(doc1, doc2):
    """Compare two Doc objects and assert that they're equal. Tests for tokens,
    tags, dependencies and entities."""
    assert [ t.orth for t in doc1 ] == [ t.orth for t in doc2 ]

    assert [ t.pos for t in doc1 ] == [ t.pos for t in doc2 ]
    assert [ t.tag for t in doc1 ] == [ t.tag for t in doc2 ]

    assert [ t.head.i for t in doc1 ] == [ t.head.i for t in doc2 ]
    assert [ t.dep for t in doc1 ] == [ t.dep for t in doc2 ]
    if doc1.is_parsed and doc2.is_parsed:
        assert [ s for s in doc1.sents ] == [ s for s in doc2.sents ]

    assert [ t.ent_type for t in doc1 ] == [ t.ent_type for t in doc2 ]
    assert [ t.ent_iob for t in doc1 ] == [ t.ent_iob for t in doc2 ]
    assert [ ent for ent in doc1.ents ] == [ ent for ent in doc2.ents ]

def assert_packed_msg_equal(b1, b2):
    """Assert that two packed msgpack messages are equal."""
    msg1 = msgpack.loads(b1, encoding='utf8')
    msg2 = msgpack.loads(b2, encoding='utf8')
    assert sorted(msg1.keys()) == sorted(msg2.keys())
    for (k1, v1), (k2, v2) in zip(sorted(msg1.items()), sorted(msg2.items())):
        assert k1 == k2
        assert v1 == v2


text:
import string, random, sys

def genPass(numChars, usePunc):
	chars = string.ascii_letters + string.digits
	if usePunc:
		chars = chars + string.punctuation
	password = ''
	for i in range(numChars):
		password = password + random.choice(chars)
	return password

def isInteger(s):
	try:
		int(s)
		return True
	except ValueError:
		return False

def usage():
	print('Usage:\ngenerate_password.py [-noPunc] numchars')

def main(args):
	if len(args) > 2 or len(args) < 1:
		usage()
		return
	if ((len(args) == 2 and (args[0] != '-noPunc' or not isInteger(args[1]))) or
		(len(args) == 1 and not isInteger(args[0]))):
		usage()
		return
	numChars = int(args[-1])
	usePunc = args[0] != '-noPunc'
	print(genPass(numChars, usePunc))

main(sys.argv[1:])


text:
package at.ac.tuwien.infosys.jcloudscale.server.discovery;

import java.io.Closeable;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.logging.Logger;

import at.ac.tuwien.infosys.jcloudscale.configuration.JCloudScaleConfiguration;
import at.ac.tuwien.infosys.jcloudscale.server.PlatformSpecificUtil;

/**
 * @author rst
 * Allows to publish and discover resource using multicast protocol.
 */
public class MulticastDiscoverer
{
	private static final int MESSAGE_SIZE = 128;//size of the data message, in bytes.

	/**
	 * Publishes information specified by discoveryInformation on multicast address and port.
	 * @param multicastAddress The multicast address discoveryInformation should be available at.
	 * @param port The port discoveryInformation should be available at.
	 * @param discoveryInformation The information that needs to be discovered via multicast. Size should be limited to MESSAGE_SIZE.
	 * @return Closeable object that allows to control how long provided information will be available for discovery.
	 * @throws IOException In case specified address or port are incorrect (not correct values or not multicast address).
	 */
	public static Closeable publishResource(String multicastAddress, int port, byte[] discoveryInformation) throws IOException
	{
		return new MulticastResourceNotificator(multicastAddress, port, discoveryInformation);
	}

	/**
	 * Sends discovery message and waits for the answer until timeout occurs.
	 * @param mulitcastAddress The multicast address the resource is expected to be publish on.
	 * @param port The port that information should be available on.
	 * @param responseAwaitTimeout How long response should be awaited. (for normal networks there's no need in big values 1 sec is more than enough.)
	 * @return The discovery information or null if timeout occured.
	 * @throws IOException if failed to bind local socket or send discovery message.
	 */
	public static byte[] discoverResource(String mulitcastAddress, int port, long responseAwaitTimeout) throws IOException
	{
		try(DatagramSocket socket = new DatagramSocket(0))
		{
			socket.setSoTimeout((int)responseAwaitTimeout);
			//
			// Preparing and sending multicast packet.
			//
			InetAddress group = InetAddress.getByName(mulitcastAddress);
            String message = PlatformSpecificUtil.findBestIP()+":"+socket.getLocalPort();
            byte[] data = message.getBytes();
            DatagramPacket packet = new DatagramPacket(data, data.length, group, port);

            socket.send(packet);

            //
            // receiving answer
            //
            packet = new DatagramPacket(new byte[MESSAGE_SIZE], MESSAGE_SIZE);
            socket.receive(packet);

            return packet.getData();
		}
		catch(SocketTimeoutException ex)
		{
			//that's fine. Just that no answer within timeout
			return null;
		}
	}

	public static byte[] discoverResource(String mulitcastAddress, int port, long responseAwaitTimeout, long discoveryTimeout) throws IOException
	{
		long startTime = System.currentTimeMillis();
		byte[] serverReply = null;
		do
		{
			try
			{
				serverReply = MulticastDiscoverer.discoverResource(
					mulitcastAddress, port,	responseAwaitTimeout);
			}
			catch(Exception ex)
			{
				// this might happen because of some race conditions in socket implementations of Java or some windows bugs, at least from what I saw.
				// (like http://stackoverflow.com/questions/10088363/java-net-socketexception-no-buffer-space-available-maximum-connections-reached)
				JCloudScaleConfiguration.getLogger(MulticastDiscoverer.class).severe("Failed to send Multicast Discovery Request: "+ex);
			}
		}
		while(serverReply == null &&
				((System.currentTimeMillis() - startTime) < discoveryTimeout) &&
				!Thread.interrupted());

		return serverReply;
	}

	//-------------------------------------------------

	private static class MulticastResourceNotificator implements Closeable, Runnable
	{
		private static final String NAME = "MULTICAST RESOURCE NOTIFICATOR THREAD";

		private final Logger log = JCloudScaleConfiguration.getLogger(MulticastResourceNotificator.class);

		private volatile boolean isAborted = false;

		private MulticastSocket socket;
		InetAddress group;
		private byte[] data;

		public MulticastResourceNotificator(String multicastAddress, int port, byte[] discoveryInformation) throws IOException
		{
			this.data = discoveryInformation;

			//
			//configuring multicast socket.
			//
			socket = new MulticastSocket(port);
			group = InetAddress.getByName(multicastAddress);
			socket.joinGroup(group);
			Thread notificationThread = new Thread(this, NAME);
			notificationThread.start();
		}

		@Override
		public void run()
		{
			log.fine("Multicast resource notificator starts on thread "+NAME);

			while(!isAborted)
			{
				try
				{
					byte[] buffer = new byte[MESSAGE_SIZE];

					//
					// Waiting for message
					//
					DatagramPacket packet =  new DatagramPacket(buffer, buffer.length);
					socket.receive(packet);//here we are waiting for something to come.

					String discovererAddress = new String(packet.getData()).trim();

					log.info(String.format("%s:\tNew discovery request \"%s\"", new Date(System.currentTimeMillis()), discovererAddress));

					String hostname = discovererAddress.substring(0, discovererAddress.indexOf(':'));
					if(hostname == null || hostname.length() == 0)
					{
						log.severe("Message \""+discovererAddress+"\": format is incorrect. Skipping.");
						continue;
					}

					int port = Integer.parseInt(discovererAddress.substring(discovererAddress.indexOf(':')+1,discovererAddress.length()));

					//
					// Sending response.
					//
					packet = new DatagramPacket(data, data.length, InetAddress.getByName(hostname), port);
					socket.send(packet);
				}
				catch(SocketException ex)
				{
					log.fine("SocketException: Assuming that this is fine, just socket is closed: "+ex.toString());
				}
				catch(Exception ex)
				{
					log.severe(String.format("%s: Exception occured: %s", NAME, ex.toString()));
				}
			}

			log.fine(NAME+": Multicast resource notificator stops.");
		}

		@Override
		public void close()
		{
			isAborted = true;
			if(socket == null)
				return;

			try
			{
				socket.leaveGroup(group);
			}
			catch(IOException ex){}//who cares? we close anyways.

			socket.close();
			socket = null;
		}
	}
}


text:
//   Done by TheTutor

/*

  This is a "text-blitter" tutorial although what it really is demonstrating is how
  to "parse sections of a .bmp out" -- Meaning we're only loading one .bmp, but this .bmp
  is comprised of many (26 to be exact) smaller .bmps that we're going to want to be able
  to access as if they were separate .bmps -- Got it?

  Now before we go any further, I want to point out this is NOT a good text blitter -- No
  I'm not writing bad code, it's just (for example) our Alphabet.bmp doesn't have
  any punctuation OR even a "space character" -- So for blitting an English sentence it's
  simply not going to cut it -- But the fundamentals will be sound :)

*/

#include "win_main.h"

#define class_name "GameTutorials_TextBlitter"

// WinProc
LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);

// Frees up any memeory associated with an SText struct
void FreeText(SText &text);

// WinMain
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprev, PSTR cmdline, int ishow)
{
	SText textBlitter = {0}; // This is the object that holds the data for "text blitting"
	CWinObj win_obj; // Our window object that holds all the data about our window

	HWND hwnd;
    MSG msg;
    WNDCLASSEX wndclassex = {0};	// Zero out WNDCLASSEX

	// Fill in fields we care about -- If your unsure of what all these "fields" are
	// Check out an early tutorial or MSDN
	wndclassex.cbSize = sizeof(WNDCLASSEX);
    wndclassex.style = CS_HREDRAW | CS_VREDRAW;
    wndclassex.lpfnWndProc = WinProc;
    wndclassex.hInstance = hinstance;
	wndclassex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wndclassex.lpszClassName = class_name;
    wndclassex.hCursor = (HCURSOR)LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW), IMAGE_CURSOR,
											0, 0, LR_SHARED);

    RegisterClassEx(&wndclassex);

	// Creating our window --
    hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, /// Window will have a "sunken-edge"
						  class_name,
						  "www.GameTutorials.com -- A \"text-blitter\"",
						  WS_SYSMENU | WS_CAPTION, // Window with title bar that's not resizable
						  CW_USEDEFAULT,
						  CW_USEDEFAULT,
						  640,
						  480,
						  NULL,
						  NULL,
						  hinstance,
						  NULL);

		// Error Check
		if(!hwnd)
			return EXIT_FAILURE;

	// Init CWinObj
	if(win_obj.init(hwnd) == false)
		return EXIT_FAILURE; // Something bad happened

	// ** Fill the TEXT_BLITTER struct **

	// Load the bitmap
	textBlitter.hbitmap = (HBITMAP)LoadImage(hinstance,"Alphabet.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE);

		// Better error check...
		if(!(textBlitter.hbitmap))
			return EXIT_FAILURE;

	// Create a compatible HDC
	textBlitter.hdc = CreateCompatibleDC(win_obj.getHDC());

		// Better error check...
		if(!(textBlitter.hdc))
			return EXIT_FAILURE;

	// Select the hbitmap into the textBlitter
	textBlitter.old_bitmap = (HBITMAP)SelectObject(textBlitter.hdc,textBlitter.hbitmap);

	// ** Done filling TEXT_BLITTER struct **

	// Show and update window
    ShowWindow(hwnd, ishow);
    UpdateWindow(hwnd);

	PrintText(win_obj,textBlitter,"GameTutorials",0,50);
	PrintText(win_obj,textBlitter,"TheTutor",0,350);

	while(1)
	{
		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			if(msg.message == WM_QUIT)
				break;

			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			/* YOU WOULD DO COMPUTATIONALLY EXPENSIVE THINGS HERE
			   (updating player movement, checking for collision, etc) */

		}

	} // end of while(1)

	// Frees the memory associated with the WNDCLASSEX we registered
	UnregisterClass(class_name,hinstance);
		return msg.wParam;
}

// Does this WinProc look simple enough???  We're not doing anything special so we
// don't have to check for to many messages
LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
    PAINTSTRUCT ps;

	switch(message)
    {
		case WM_PAINT:

			BeginPaint(hwnd, &ps);
			EndPaint(hwnd, &ps);
				return 0;

		// This message gets sent when the window is terminated (closed, exited, you get the point)
		case WM_DESTROY:

			PostQuitMessage(0);
				return 0;

	} // end of switch(message)

    return DefWindowProc(hwnd, message, wparam, lparam);
}

// This will print "buff" to the screen starting at (x, y)
void PrintText(CWinObj &win_obj, SText &tb, char buff[MAX_LENGTH], int x, int y)
{
	// tempX and tempY will hold the upper left coord of where we're going to blit
	// to (ie win_obj.win_dc)
	int tempX = x;
	int tempY = y;

	// We'll keep looping until we've printed out the all of buff (either MAX_LENGTH characters
	// or until we hit a NULL character)
	for(int i = 0; (i < MAX_LENGTH) && (buff[i] != NULL); i++)
	{
		// Okay what we're doing here is taken the current letter in buff and making it
		// capital (this way we won't have to make two checks for 'a' and 'A')
		// The we're subtraction ALPHA_CONST which will give us an
		// integer (if buff[i] is a letter of the alphabet) between 0 and 25 --
		int index = toupper(buff[i]) - ALPHA_CONST;

		/* Here is how we have the letters laid out in our bitmap with 'A' starting at 0

		   0	1	2	3	4	5	6	7	8	9	10	11	12
		   13	14	15	16	17	18	19	20	21	22	23	24	25
		*/

		// Make sure our index is legal
		if((index >= 0) && (index <= 25))
		{
			int xOffset, yOffset;

			// Now look at the "diagram" of how our Alphabet.bmp is laid out (a few lines above)
			// Any "letter rect" on the top line is going to have an upper left y-ccord of 0
			// So for indexes 0 - 12 we know yOffset starts at 0 -- Each letter is exactly
			// LTR_WID (64 pixels) wide so the starting x-coord is going to be "index * LTR_WID"
			if(index < 13)
			{
				xOffset = index * LTR_WID;
				yOffset = 0;
			}
			else
			{
				/*
				   If the index is 13 or greater we've moved 64 pixels down (the height of the
				   bitmap) for our y-offset (upper left y-coord of rect for blitting)
				   Our x-coord is going to work the same way (index * LTR_WID) it's just we have
				   to subtract 13 to get the index in the same range (i.e. 0 - 12)
				*/
				xOffset = (index - 13) * LTR_WID;
				yOffset = LTR_HGT;
			}

			// Now remember when we're blitting we only blitting one letter at a time
			// our letters are (64x64) so by parameter:
			// win_obj.getHDC() -- Where we want to blit to
			// tempX -- The upper left x-coord of where we want to blit to
			// tempY -- The upper left y-coord of where we want to blit to
			// LTR_WID -- The width (in pixels) of the RECT we want to blit to
			// LTR_HGT -- The height (in pixels) of the RECT we want to blit to
			// tb.hdc -- The source we want to blit from (where we getting the image to blit)
			// xOffset -- The upper left x-coord in tb.hdc to begin blitting
			// yOffset -- The upper left y-ccord in tb.hdc to begin blitting
			// SRCCOPY -- "source copy" take everything from the source (tb.hdc) and copy it
			//			  verbatim to the dest (win_obj.win_dc)
			BitBlt(win_obj.getHDC(),tempX,tempY,LTR_WID,LTR_HGT,tb.hdc,xOffset,yOffset,SRCCOPY);

		} // end of if((index >= 0) && (index <= 25))

		// Every time we blit a letter we need to move to the right LTR_WID (64 pixels)
		// for the start of the next blit
		tempX += LTR_WID;

		// If our starting position is to close to the right of our window (if we can't FULLY
		// blit the next letter with out all of it or some of it going off the window) move down
		// to the next line
		if(tempX > (win_obj.getClientWid() - LTR_WID))
		{
			tempX = x; // Start back at "the left"
			tempY += LTR_HGT; // Effectively move to the next line
		}

	} // end of for(int i = 0; (i < MAX_LENGTH) && (buff[i] != NULL); i++)

}

// Free the memory in a SText struct
void FreeText(SText &text)
{
	// If old_bmp AND hdc has been assigned some memory
	if(text.old_bitmap && text.hdc)
	{
		SelectObject(text.hdc,text.old_bitmap); // Select back old bitmap

		DeleteObject(text.hbitmap); // Delete hbitmap
		DeleteDC(text.hdc); // Delete the HDC
	}

	// Zero out the variables
	text.hbitmap = text.old_bitmap = NULL;
	text.hdc = NULL;
}


text:
<?php

class Google_Service_Slides_CreateSheetsChartResponse extends Google_Model
{
  public $objectId;

  public function setObjectId($objectId)
  {
    $this->objectId = $objectId;
  }
  public function getObjectId()
  {
    return $this->objectId;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Patterns.ChainOfResponsibility.Employees
{
    /// <summary>
    /// Represents a team leader in Carebook company
    /// </summary>
    class TeamLeader : CarebookEmployee
    {
        /// <summary>
        /// Creates new TeamLeader object instance with specified full name
        /// </summary>
        /// <param name="fullName"></param>
        /// <param name="supervisor"></param>
        public TeamLeader(string fullName, CarebookEmployee supervisor)
            : base(fullName, supervisor)
        {
        }

        /// <summary>
        /// Team leader is responsible for non-global functionality changes
        /// </summary>
        /// <param name="changeDescription"></param>
        public override void HandlePageBehaviorChangeRequest(string changeDescription)
        {
            Console.WriteLine(
                String.Format("{0} (team leader) has accepted next request: {1}", FullName, changeDescription));
        }
    }
}


text:
namespace misere
{

class AbstractHandler : public HttpHandler
{
public:
   virtual bool init(const std::string& path,
                     const chaudiere::KeyValuePairs& kvpArguments);
   virtual void serviceRequest(const HttpRequest& request,
                               HttpResponse& response);
   virtual bool isAvailable() const;

};

}

#endif


text:
<toaster-container></toaster-container>

      <form class="form-signin floating-label">

Login

          Email address
          <input type="email" id="username" name="username" class="form-control" placeholder="Email address" required autofocus
                 [(ngModel)]="user.username">

          Password
          <input type="password" id="password" name="password" class="form-control" placeholder="Password" required
                 [(ngModel)]="user.password">

            <input type="checkbox" value="remember-me"> Remember me

        <button class="btn btn-lg btn-primary btn-block" type="submit" (click)="login()">Sign in</button>
      </form>


text:
import transformCss, { getStylesForProperty } from '..'

it('transforms numbers', () => {
  expect(transformCss([['z-index', '0']])).toEqual({ zIndex: 0 })
})

it('warns if missing units on unspecialized transform', () => {
  const consoleSpy = jest
    .spyOn(global.console, 'warn')
    .mockImplementation(() => {
      // Silence the warning from the test output
    })

  transformCss([['top', '1']])
  expect(consoleSpy).toHaveBeenCalledWith(
    'Expected style "top: 1" to contain units'
  )

  consoleSpy.mockRestore()
})

it('does not warn for unitless 0 length on unspecialized transform', () => {
  const consoleSpy = jest.spyOn(global.console, 'warn')

  transformCss([['top', '0']])
  expect(consoleSpy).not.toHaveBeenCalled()

  consoleSpy.mockRestore()
})

it('warns if adding etraneous units on unspecialized transform', () => {
  const consoleSpy = jest
    .spyOn(global.console, 'warn')
    .mockImplementation(() => {
      // Silence the warning from the test output
    })

  transformCss([['opacity', '1px']])
  expect(consoleSpy).toHaveBeenCalledWith(
    'Expected style "opacity: 1px" to be unitless'
  )

  consoleSpy.mockRestore()
})

it('does not warn for unitless 0 length on unitless transform', () => {
  const consoleSpy = jest.spyOn(global.console, 'warn')

  transformCss([['opacity', '0']])
  expect(consoleSpy).not.toHaveBeenCalled()

  consoleSpy.mockRestore()
})

it('allows pixels in unspecialized transform', () => {
  expect(transformCss([['top', '0px']])).toEqual({ top: 0 })
})

it('allows boolean values', () => {
  expect(
    transformCss([
      ['boolTrue1', 'true'],
      ['boolTrue2', 'TRUE'],
      ['boolFalse1', 'false'],
      ['boolFalse2', 'FALSE'],
    ])
  ).toEqual({
    boolTrue1: true,
    boolTrue2: true,
    boolFalse1: false,
    boolFalse2: false,
  })
})

it('allows null values', () => {
  expect(transformCss([['null1', 'null'], ['null2', 'NULL']])).toEqual({
    null1: null,
    null2: null,
  })
})

it('allows undefined values', () => {
  expect(
    transformCss([['undefined1', 'undefined'], ['undefined2', 'UNDEFINED']])
  ).toEqual({
    undefined1: undefined,
    undefined2: undefined,
  })
})

it('allows CSS custom properties to pass through', () => {
  expect(transformCss([['--my-prop', '0%']])).toEqual({ '--my-prop': '0%' })
})

it('allows percent in unspecialized transform', () => {
  expect(transformCss([['top', '0%']])).toEqual({ top: '0%' })
})

it('allows decimal values', () => {
  expect(getStylesForProperty('margin', '0.5px').marginTop).toBe(0.5)
  expect(getStylesForProperty('margin', '1.5px').marginTop).toBe(1.5)
  expect(getStylesForProperty('margin', '10.5px').marginTop).toBe(10.5)
  expect(getStylesForProperty('margin', '100.5px').marginTop).toBe(100.5)
  expect(getStylesForProperty('margin', '-0.5px').marginTop).toBe(-0.5)
  expect(getStylesForProperty('margin', '-1.5px').marginTop).toBe(-1.5)
  expect(getStylesForProperty('margin', '-10.5px').marginTop).toBe(-10.5)
  expect(getStylesForProperty('margin', '-100.5px').marginTop).toBe(-100.5)
  expect(getStylesForProperty('margin', '.5px').marginTop).toBe(0.5)
  expect(getStylesForProperty('margin', '-.5px').marginTop).toBe(-0.5)
})

it('allows decimal values in transformed values', () => {
  expect(transformCss([['border-radius', '1.5px']])).toEqual({
    borderTopLeftRadius: 1.5,
    borderTopRightRadius: 1.5,
    borderBottomRightRadius: 1.5,
    borderBottomLeftRadius: 1.5,
  })
})

it('allows negative values in transformed values', () => {
  expect(transformCss([['border-radius', '-1.5px']])).toEqual({
    borderTopLeftRadius: -1.5,
    borderTopRightRadius: -1.5,
    borderBottomRightRadius: -1.5,
    borderBottomLeftRadius: -1.5,
  })
})

it('allows uppercase units', () => {
  expect(transformCss([['top', '0PX']])).toEqual({ top: 0 })
  expect(transformCss([['transform', 'rotate(30DEG)']])).toEqual({
    transform: [{ rotate: '30deg' }],
  })
})

it('allows percent values in transformed values', () => {
  expect(transformCss([['margin', '10%']])).toEqual({
    marginTop: '10%',
    marginRight: '10%',
    marginBottom: '10%',
    marginLeft: '10%',
  })
})

it('allows color values in transformed border-color values', () => {
  expect(transformCss([['border-color', 'red']])).toEqual({
    borderTopColor: 'red',
    borderRightColor: 'red',
    borderBottomColor: 'red',
    borderLeftColor: 'red',
  })
})

it('allows omitting units for 0', () => {
  expect(transformCss([['margin', '10px 0']])).toEqual({
    marginTop: 10,
    marginRight: 0,
    marginBottom: 10,
    marginLeft: 0,
  })
})

it('transforms strings', () => {
  expect(transformCss([['color', 'red']])).toEqual({ color: 'red' })
})

it('converts to camel-case', () => {
  expect(transformCss([['background-color', 'red']])).toEqual({
    backgroundColor: 'red',
  })
})

it('transforms background to backgroundColor', () => {
  expect(transformCss([['background', '#f00']])).toEqual({
    backgroundColor: '#f00',
  })
})

it('transforms background to backgroundColor with rgb', () => {
  expect(transformCss([['background', 'rgb(255, 0, 0)']])).toEqual({
    backgroundColor: 'rgb(255, 0, 0)',
  })
})

it('transforms background to backgroundColor with named colour', () => {
  expect(transformCss([['background', 'red']])).toEqual({
    backgroundColor: 'red',
  })
})

it('allows blacklisting shorthands', () => {
  const actualStyles = transformCss(
    [['border-radius', '50px']],
    ['borderRadius']
  )
  expect(actualStyles).toEqual({ borderRadius: 50 })
})

it('throws useful errors', () => {
  expect(() => transformCss([['margin', '10']])).toThrow(
    'Failed to parse declaration "margin: 10"'
  )
})


text:
import React, {Component} from 'react';
import {connect} from 'react-redux'

import HitokotoPreview from '../pages/HitokotoPreview'

import {cleanPreview} from '../actions';

const mapStoreToProps = ({collections, layout}) => {
  return ({preview: collections.preview, layout})
};
const mapActionToProps = (dispacth) => {
  return ({
    cleanPreview: (ntype) => dispacth(cleanPreview(ntype))
  })
}
export default connect(mapStoreToProps, mapActionToProps)(HitokotoPreview)


text:
'use strict';

/**
 * Raptor.js - v2
 *
 * @Route("/api/development/troodon")
 * @Controller
 */
class ApiPanel {

	configure() {

	}

    /**
     * @Route("/import",method="post")
	 * @Development
	 * @Cors
	 * @Csrf
     */
	importAction(req, res, next, DynamicPrivilege, Options) {

		DynamicPrivilege.import(req.body.rol)
			.then(function () {
				res.show("Los privilegios fueron importados!!");
			})
			.catch(function(err){

				next(err)
			})

	}
}

module.exports = ApiPanel;


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

<title>LiveBeansViewMBean (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.springframework.context.support

Interface LiveBeansViewMBean

All Known Implementing Classes:

LiveBeansView, ServletContextLiveBeansView

public interface LiveBeansViewMBean

MBean operation interface for the LiveBeansView feature.

Since:

3.2

Author:

Juergen Hoeller

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

String
getSnapshotAsJson()

Generate a JSON snapshot of current beans and their dependencies.

Method Detail

getSnapshotAsJson

String getSnapshotAsJson()

Generate a JSON snapshot of current beans and their dependencies.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.

package org.usfirst.frc6413.SteamWorks.subsystems;

import java.math.BigDecimal;
import java.math.RoundingMode;

import org.usfirst.frc6413.SteamWorks.RobotMap;
import org.usfirst.frc6413.SteamWorks.commands.*;

import com.ctre.CANTalon;
import com.ctre.CANTalon.TalonControlMode;
import com.kauailabs.navx.frc.AHRS;

import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Spark;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.command.Subsystem;

/**
 *
 */
public class DriveBase extends Subsystem {

	// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS

	// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS

	// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
	private final CANTalon lFM = RobotMap.driveBaseLFM;
	private final CANTalon lRM = RobotMap.driveBaseLRM;
	private final CANTalon rFM = RobotMap.driveBaseRFM;
	private final CANTalon rRM = RobotMap.driveBaseRRM;
	private final RobotDrive robotDrive41 = RobotMap.driveBaseRobotDrive41;
	//private final AnalogInput rearUltrasonic = RobotMap.driveBaseRearUltrasonic;
	private final AnalogInput frontUltrasonic = RobotMap.driveBaseFrontUltrasonic;

	private int loops = 0;

	// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS

	private final AHRS ahrs = RobotMap.ahrs;

	// Put methods for controlling this subsystem
	// here. Call these from Commands.

	public void initDefaultCommand() {
		// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND

		setDefaultCommand(new MecanumDrive());

		// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND

		// Set the default command for a subsystem here.
		// setDefaultCommand(new MySpecialCommand());
	}

	public void mecanumDrive(XboxController controller) {
	  double x = deadZoneInput(controller.getX(GenericHID.Hand.kLeft), .3);
	  double y = deadZoneInput(controller.getY(GenericHID.Hand.kLeft), .1) * .5;
	  double rotation = deadZoneInput(controller.getX(GenericHID.Hand.kRight), .1) * .7;

	  if(controller.getTriggerAxis(GenericHID.Hand.kRight) != 0.0) {
			double trigger = controller.getTriggerAxis(GenericHID.Hand.kRight);
			y = y * (trigger + 1);
			rotation = rotation * (1-(trigger*.5));
	  }

		StringBuilder sb = new StringBuilder();

		if(controller.getBumper(GenericHID.Hand.kLeft)) {
			rFM.changeControlMode(TalonControlMode.PercentVbus);
			rRM.changeControlMode(TalonControlMode.PercentVbus);
			lFM.changeControlMode(TalonControlMode.PercentVbus);
			lRM.changeControlMode(TalonControlMode.PercentVbus);

			robotDrive41.mecanumDrive_Cartesian(x, y, rotation, 0);
		}
		else {
			y = y * -1;
			//sb.append("rawx:" + rotation + ", rawy:" + y);
			//double motorOutput = lFM.getOutputVoltage() / lFM.getBusVoltage();

			double z = Math.sqrt(rotation * rotation + y * y);
			double rad = Math.acos(Math.abs(rotation)/z);
			double angle = rad * 180.0 / Math.PI;

			double tcoeff = -1 + (angle/90.0)*2.0;
			double turn = tcoeff * Math.abs(Math.abs(y) - Math.abs(rotation));
			turn = Math.round(turn*100.0)/100.0;

			double move = Math.max(Math.abs(y), Math.abs(rotation));

			double left = 0;
			double right = 0;

			if ((rotation >= 0 && y >=0) || (rotation < 0 && y < 0))
			{
				left = move;
				right = turn;
			}
			else {
				right = move;
				left = turn;
			}

			if (y < 0)
			{
				left = 0 - left;
				right = 0 - right;
			}

			double rightTargetSpeed = right * 1200;
	    	rFM.changeControlMode(TalonControlMode.Speed);
	    	rFM.set(rightTargetSpeed);

	    	//rRM.changeControlMode(TalonControlMode.Follower);
	    	//rRM.set(0);

	    	rRM.changeControlMode(TalonControlMode.Speed);
	    	rRM.set(rightTargetSpeed);

	    	double leftTargetSpeed = left * 1200;
	    	lFM.changeControlMode(TalonControlMode.Speed);
	    	lFM.set(leftTargetSpeed);

	    	//lRM.changeControlMode(TalonControlMode.Follower);
	    	//lRM.set(1);

	    	lRM.changeControlMode(TalonControlMode.Speed);
	    	lRM.set(leftTargetSpeed);
		}
	}

	public void driveCount() {
		lFM.changeControlMode(TalonControlMode.Position);
		lFM.set(1000);
	}

	public void driveForward(double speed) {
		// need to reverse the right side, due to setup of mecanum drive
		lFM.changeControlMode(TalonControlMode.PercentVbus);
		lFM.set(speed);

		rFM.changeControlMode(TalonControlMode.PercentVbus);
		rFM.set(speed);

		lRM.changeControlMode(TalonControlMode.PercentVbus);
		lRM.set(speed);

		rRM.changeControlMode(TalonControlMode.PercentVbus);
		rRM.set(speed);
	}

	//public double getDistanceBehind() {
	//	return rearUltrasonic.getAverageVoltage();
	//}

	public double getDistanceAhead() {
		return frontUltrasonic.getAverageVoltage();
	}

	public void rotateToDegree(double degree) {

	}

	public static double round(double value, int places) {
		if (places < 0)
			throw new IllegalArgumentException();

		BigDecimal bd = new BigDecimal(value);
		bd = bd.setScale(places, RoundingMode.HALF_UP);
		return bd.doubleValue();
	}

	private double deadZoneInput(double input, double deadZone) {
		if (input <= deadZone && input >= -deadZone)
			return 0;
		else if (input >= deadZone)
			input = ((input - deadZone) / (1 - deadZone));
		else if (input <= deadZone)
			input = ((-input - deadZone) / (deadZone - 1));

		return round(input, 2);
	}
}


text:
using System;
using System.Collections.Generic;
using Cosmos.Extensions.Dependency;
using Cosmos.Extensions.Dependency.Core;
using Cosmos.Logging.Configurations;
using Cosmos.Logging.Core;
using Cosmos.Logging.Core.Enrichers;
using Cosmos.Logging.MessageTemplates;
using Cosmos.Optionals;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Cosmos.Logging.Extensions.DependencyInjection {
    /// <summary>
    /// Standard log service collection
    /// </summary>
    public class StandardLogServiceCollection : ILogServiceCollection, IDisposable {
        private LoggingConfigurationBuilder _configurationBuilder;
        private readonly bool _configurationBuilderLockedStatus;
        private readonly MicrosoftProxyRegister _services;

        // ReSharper disable once InconsistentNaming
        private LoggingConfiguration _loggingConfiguration { get; set; }

        // ReSharper disable once InconsistentNaming
        private ILoggingOptions _settings { get; set; }
        private readonly Dictionary<string, ILoggingSinkOptions> _sinkSettings;
        private object _sinkUpdateLock = new object();
        private Action<IConfigurationRoot> _originConfigAction;
        private readonly List<Func<ILogEventEnricher>> _additionalEnricherProviders;

        // ReSharper disable once UnusedMember.Local
        private StandardLogServiceCollection() { }

        internal StandardLogServiceCollection(IServiceCollection services) : this(services, null) { }

        internal StandardLogServiceCollection(IServiceCollection services, IConfigurationRoot root) {
            _configurationBuilder = root is null
                ? new LoggingConfigurationBuilder()
                : new DisabledConfigurationBuilder(root);
            _configurationBuilderLockedStatus = root != null;
            _services = new MicrosoftProxyRegister(services ?? throw new ArgumentNullException(nameof(services)));
            _settings = new LoggingOptions();
            _sinkSettings = new Dictionary<string, ILoggingSinkOptions>();
            _additionalEnricherProviders = new List<Func<ILogEventEnricher>>();

            BeGivenConfigurationBuilder = _configurationBuilder.InitializedByGivenBuilder;
            BeGivenConfigurationRoot = root != null;
        }

        /// <inheritdoc />
        public bool BeGivenConfigurationBuilder { get; }

        /// <inheritdoc />
        public bool BeGivenConfigurationRoot { get; }

        /// <inheritdoc />
        public ILoggingOptions ExposeLogSettings() => _settings;

        /// <inheritdoc />
        public LoggingConfiguration ExposeLoggingConfiguration() => _loggingConfiguration;

        /// <summary>
        /// Replace settings
        /// </summary>
        /// <param name="newSettings"></param>
        public void ReplaceSettings(ILoggingOptions newSettings) {
            if (newSettings != null) _settings = newSettings;
        }

        /// <inheritdoc />
        public ILogServiceCollection AddDependency(Action<DependencyProxyRegister> dependencyAction) {
            dependencyAction?.Invoke(_services);
            return this;
        }

        /// <inheritdoc />
        public ILogServiceCollection AddEnricher(Func<ILogEventEnricher> enricherProvider) {
            _additionalEnricherProviders.Add(enricherProvider);
            return this;
        }

        private Action<object> AddSinkSettingsAction { get; set; }

        /// <inheritdoc />
        public ILogServiceCollection AddSinkSettings<TSinkSettings, TSinkConfiguration>(TSinkSettings settings, Action<IConfiguration, TSinkConfiguration> configAct)
            where TSinkSettings : class, ILoggingSinkOptions, new() where TSinkConfiguration : SinkConfiguration, new() {
            if (settings != null && !_sinkSettings.ContainsKey(settings.Key)) {
                AddSinkSettingsAction += lockObj => {
                    lock (lockObj) {
                        if (!_sinkSettings.ContainsKey(settings.Key)) _sinkSettings.Add(settings.Key, settings);
                        _loggingConfiguration?.SetSinkConfiguration(settings.Key, settings, configAct);
                    }
                };
            }

            return this;
        }

        private Action<object> AddExtraSinkSettingsAction { get; set; }

        /// <inheritdoc />
        public ILogServiceCollection AddExtraSinkSettings<TExtraSinkSettings, TExtraSinkConfiguration>(
            TExtraSinkSettings settings,
            Action<IConfiguration, TExtraSinkConfiguration, LoggingConfiguration> configAct)
            where TExtraSinkSettings : class, ILoggingSinkOptions, new()
            where TExtraSinkConfiguration : SinkConfiguration, new() {
            if (settings != null && !_sinkSettings.ContainsKey(settings.Key)) {
                AddExtraSinkSettingsAction += lockObj => {
                    lock (lockObj) {
                        if (!_sinkSettings.ContainsKey(settings.Key)) _sinkSettings.Add(settings.Key, settings);
                        _loggingConfiguration?.SetExtraSinkConfiguration(settings.Key, settings, configAct);
                    }
                };
            }

            return this;
        }

        /// <inheritdoc />
        public ILogServiceCollection AddOriginalConfigAction(Action<IConfiguration> configAction) {
            if (configAction != null) {
                _originConfigAction += configAction;
            }

            return this;
        }

        /// <inheritdoc />
        public ILogServiceCollection ModifyConfigurationBuilder(Action<LoggingConfigurationBuilder> builderAct) {
            if (!_configurationBuilderLockedStatus) {
                builderAct?.Invoke(_configurationBuilder);
            }

            return this;
        }

        /// <inheritdoc />
        public ILogServiceCollection PreheatMessageTemplates(Action<MessageTemplateCachePreheater> preheatAct) {
            _configurationBuilder.PreheatMessageTemplates(preheatAct);
            return this;
        }

        internal void BuildConfiguration() {
            _loggingConfiguration = _configurationBuilder.Build(_settings);
        }

        internal void ActiveSinkSettings() {
            _settings.Sinks?.Clear();
            _settings.Sinks = _sinkSettings;
            AddSinkSettingsAction?.Invoke(_sinkUpdateLock);
            AddExtraSinkSettingsAction?.Invoke(_sinkSettings);
        }

        internal void ActiveOriginConfiguration() {
            _originConfigAction?.Invoke(_loggingConfiguration.Configuration);
        }

        internal void ActiveLogEventEnrichers() {
            foreach (var provider in _additionalEnricherProviders) {
                _loggingConfiguration.SetEnricher(provider.Invoke().ToMaybe());
            }
        }

        /// <summary>
        /// Gets original services
        /// </summary>
        public IServiceCollection OriginalServices => _services.RawServices;

        /// <inheritdoc />
        public void Dispose() => _services.Dispose();
    }
}


text:
var dl = require('wgap-datalist');

var checks = {
  weasel: { fn: require('weasel-words'), explanation: 'is a weasel word' },
  illusion: { fn: require('./lib/lexical-illusions'), explanation: 'is repeated' },
  so: { fn: require('./lib/starts-with-so'), explanation: 'adds no meaning' },
  thereIs: { fn: require('./lib/there-is'), explanation: 'is unnecessary verbiage' },
  passive: { fn: require('passive-voice'), explanation: 'may be passive voice' },
  adverb: { fn: require('adverb-where'), explanation: 'can weaken meaning' },
  wordy: { fn: require('too-wordy'), explanation: 'is wordy or unneeded' },
  cliche: { fn: require('no-cliches'), explanation: 'is a cliche' },
  readability: { fn: require('wgap-flesch-kincaid') },
  frankenword: { fn: require('frankenword'), explanation: 'is ghastly' },
  buzzword: { fn: dl(require('buzzwords')), explanation: 'is a buzzword' },
  filler: { fn: dl(require('fillers')), explanation: 'is filler' },
  hedge: { fn: dl(require('hedges')), explanation: 'is a hedge word' }
};

// Generate a reason for a suggestion, truncated appropriately.
function reasonable(text) {
  return suggestion => {
    var txt = text.substr(suggestion.index, suggestion.offset);
    var truncated = txt.length > 64 ? txt.substr(0, 64) + '...' : txt;
    var suggType = suggestion.type[0];
    var explanation = checks[suggType].explanation;
    suggestion.reason = `"${ truncated }" ${ (suggestion.reason || explanation) }`;
    return suggestion;
  };
}

// Concatenate reasons for passages with multiple errors.
function dedup (suggestions) {
  var dupsHash = {};
  return suggestions.reduce(function(memo, suggestion) {
    var key = suggestion.index + ":" + suggestion.offset;
    if (!dupsHash[key]) {
      dupsHash[key] = suggestion;
      memo.push(suggestion);
    } else {
      var substring = suggestion.reason.substring(suggestion.offset + 3);
      dupsHash[key].reason += " and " + substring;
      dupsHash[key].type.push(suggestion.type[0]);
    }
    return memo;
  }, []);
}

module.exports = function (text, opts) {

  return new Promise((resolve, reject) => {

    // Go ahead and resolve if we haven't been given any text.
    if (text === undefined || text === '') {
      resolve([]);
    } else {
      opts = opts || {};
      var suggestions = Object.keys(checks)
        .filter(check => {
          return opts[check] !== false;
        }).map(check => {
          return new Promise((resolve, reject) => {
            var res = checks[check].fn(text, opts[check]);
            Promise.resolve(res)
              .then(items => {
                var reasoned = items
                  .map(suggestion => {
                    suggestion.type = [ check ];
                    return suggestion;
                  })
                  .map(reasonable(text))
                resolve(reasoned);
              });
          });
        });
      Promise.all(suggestions)
        .then(suggestions => {
          var reduced = suggestions.reduce((prev, curr) => {
            return prev.concat(curr);
          });
          var out = dedup(reduced).sort((a, b) => {
            return a.index < b.index ? -1 : 1;
          });
          resolve(out);
        });
    }
  });
}

module.exports.reasonable = reasonable;
module.exports.dedup = dedup;


text:
from django.core.exceptions import ImproperlyConfigured

from urlmiddleware.urlresolvers import MiddlewareRegexURLResolver, MiddlewareRegexURLPattern

__all__ = ['mpatterns', 'middleware', ]

def mpatterns(prefix, *args):
    pattern_list = []
    for t in args:
        if isinstance(t, (list, tuple)):
            t = middleware(prefix=prefix, *t)
        elif isinstance(t, MiddlewareRegexURLPattern):
            t.add_prefix(prefix)
        pattern_list.append(t)
    return pattern_list

def middleware(regex, view, kwargs=None, name=None, prefix=''):
    if isinstance(view, (list, tuple)):
        # For include(...) processing.
        urlconf_module, app_name, namespace = view
        return MiddlewareRegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace)
    else:
        if isinstance(view, basestring):
            if not view:
                raise ImproperlyConfigured('Empty URL pattern view name not permitted (for pattern %r)' % regex)
            if prefix:
                view = prefix + '.' + view
        return MiddlewareRegexURLPattern(regex, view, kwargs, name)


text:
package org.kaazing.mina.core.session;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSessionConfig;

/**
 * Extended version of IoSessionConfig to add support for millisecond precision for idle timeouts.
 */
public interface IoSessionConfigEx extends IoSessionConfig {

    /**
     * New method added for millisecond precise idle times
     */
    void setIdleTimeInMillis(IdleStatus status, long idleTimeMillis);

    void setChangeListener(ChangeListener listener);

    interface ChangeListener {

        void idleTimeInMillisChanged(IdleStatus status, long idleTimeMillis);

    }
}


text:
var density = require('./density.js');
var extent = require('./extent.js');

exports.diameter = require('./diameter.js');
exports.modularity = require('./modularity.js');
exports.simpleSize = require('./simple-size.js');
exports.weightedSize = require('./weighted-size.js');

exports.abstractDensity = density.abstractDensity;
exports.density = density.density;
exports.directedDensity = density.directedDensity;
exports.undirectedDensity = density.undirectedDensity;
exports.mixedDensity = density.mixedDensity;
exports.multiDirectedDensity = density.multiDirectedDensity;
exports.multiUndirectedDensity = density.multiUndirectedDensity;
exports.multiMixedDensity = density.multiMixedDensity;

exports.nodeExtent = extent.nodeExtent;
exports.edgeExtent = extent.edgeExtent;


text:
class CBoxPlotOpen : public CDialog
{
	DECLARE_DYNAMIC(CBoxPlotOpen)

public:
	CBoxPlotOpen(CWnd* pParent = NULL);   // standard constructor
	CBoxPlotOpen(CString *Filename, CWnd* pParent = NULL);
	virtual ~CBoxPlotOpen();
	CString *filename;

// Dialog Data
	enum { IDD = IDD_BOXPLOTOPEN };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnBnClickedOpensave();
	afx_msg void OnBnClickedOk();
	CString pfsave;
};


text:
using AuthService.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.WindowsAzure.Storage;
using AuthService.Model;
using Microsoft.WindowsAzure;
using System.IO;
using AuthService.Logging;

namespace AuthService.Controller
{
    /// <summary>
    /// The storage client.
    /// </summary>
    public class StorageController : ApiController
    {
        private CloudStorageAccount _account;
        private CloudBlobContainer _userStorage;
        private CloudBlobClient _client;
        private List<DirectoryEntry> directory = new List<DirectoryEntry>();
        private string _userName;
        private string _containerName;
        private AzureBlobStorageManager _storageManager;
        private StorageExPorter _exporter;
        private Logger _logger;

        /// <summary>
        /// Initializes the storage.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        private async Task<string> InitStorage(string userName)
        {

            await Task.Run(()=> {

            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("Username cannot be null or empty.", "username");
            }

            _userName = userName.ToLowerInvariant();
            _containerName = _userName;
            _account = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("BlobStorage"));

            //2nd create the client
            _client = _account.CreateCloudBlobClient();
            //3rd create the container
            _userStorage = _client.GetContainerReference(_userName);
            _userStorage.CreateIfNotExists();
            //4th set the permissions on the container
            _userStorage.SetPermissions(new BlobContainerPermissions()
            {
                PublicAccess = BlobContainerPublicAccessType.Off

            });

            //Create instance of Azure BlobStorageManager
            _storageManager = new Storage.AzureBlobStorageManager();

            _exporter = new StorageExPorter(userName);
            });

            await LogMessage(String.Format("Storage init: {0}", userName));

            return _userName;

        }

        /// <summary>
        /// Logs the message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        private async Task LogMessage(string message)
        {
            var logName = CloudConfigurationManager.GetSetting("LogName");
            _logger = new Logger(logName);
            await _logger.StoreNewLogMessage(new Message(message, logName));
        }

        /// <summary>
        /// Uploads the file.
        /// </summary>
        /// <param name="fileStream">The file stream.</param>
        /// <param name="directory">The directory.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="filenName">Name of the filen.</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<HttpResponseMessage> UploadFile(MemoryStream fileStream,string directory,string contentType,string filenName, string userName)
        {

            await InitStorage(userName);

            var guard = new DirectoryQuota(this._userName, fileStream.Length);

            var enoughQuota = await guard.CheckUserQuota();

            if (enoughQuota != -1)
            {

                var uploadComplete = await _storageManager.UploadFile(this._userStorage, fileStream, directory, contentType, filenName);

                var logName = CloudConfigurationManager.GetSetting("LogName");
                await LogMessage(String.Format("File Upload: {0} FileName: {1}", userName,filenName));

                return Request.CreateResponse<bool>(uploadComplete);
            }
            else
            {
                throw new HttpResponseException(new HttpResponseMessage() { Content=new StringContent("Not enuough storage space left"),ReasonPhrase="quota exceeded"});
            }
        }

        /// <summary>
        /// Creates the directory.
        /// </summary>
        /// <param name="directoryName">Name of the directory.</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> CreateDirectory(string directoryName,string userName)
        {

            await InitStorage(userName);

            var created = await _storageManager.CreateDirectory(this._userStorage, directoryName);

            await LogMessage(String.Format("File Upload: {0} FileName: {1}", userName, directoryName));

            return Request.CreateResponse<bool>(created);
        }

        /// <summary>
        /// Copies the file.
        /// </summary>
        /// <param name="blobName">Name of the BLOB.</param>
        /// <param name="newFileName">New name of the file.</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> CopyFile(string blobName,string newFileName,string userName)
        {

           await InitStorage(userName);

           var blob = await _userStorage.GetBlobReferenceFromServerAsync(blobName);

           var ok = _storageManager.CopyFile(this._userStorage, (CloudBlockBlob) blob, newFileName);

           await LogMessage(String.Format("Copy File: {0} Orignial File: {1} New File {2}", userName, blobName,newFileName));

           return Request.CreateResponse<Task<bool>>(ok);
        }

        /// <summary>
        /// Renames the file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="newFileName">New name of the file.</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> RenameFile(string fileName, string newFileName, string userName)
        {

            await InitStorage(userName);

            var blob = await _userStorage.GetBlobReferenceFromServerAsync(fileName);
            var ok = await _storageManager.RenameFile(this._userStorage, (CloudBlockBlob)blob, newFileName);

            await LogMessage(String.Format("Rename File: {0} Orignial File: {1} New File {2}", userName, fileName, newFileName));

            return Request.CreateResponse<bool>(ok);
        }

        /// <summary>
        /// Renames the directory.
        /// </summary>
        /// <param name="directoryName">Name of the directory.</param>
        /// <param name="newName">The new name.</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> RenameDirectory(string directoryName, string newName,string userName)
        {
            await InitStorage(userName);

            var ok = await _storageManager.RenameDirectory(this._userStorage, directoryName, newName);

            await LogMessage(String.Format("Rename Directory: {0} Orignial Directory: {1} New Directory {2}", userName, directoryName, newName));

            return Request.CreateResponse<bool>(ok);
        }

        /// <summary>
        /// Moves the directory.
        /// </summary>
        /// <param name="directoryName">Name of the directory.</param>
        /// <param name="newDirectoryName">New name of the directory.</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> MoveDirectory(string directoryName, string newDirectoryName,string userName)
        {
            await InitStorage(userName);
            var ok = await _storageManager.MoveDirectory(this._userStorage, directoryName, newDirectoryName);

            await LogMessage(String.Format("Move Directory: {0} Orignial Directory: {1} New Directory {2}", userName, directoryName, newDirectoryName));

            return Request.CreateResponse<bool>(ok);
        }

        /// <summary>
        /// Downloads the file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> DownloadFile(string fileName,string userName)
        {
            await InitStorage(userName);
            var data = await _storageManager.DownloadFile(this._userStorage, fileName);
            await LogMessage(String.Format("Download File: {0} File Name: {1}", userName, fileName));
            return Request.CreateResponse<byte[]>(data);
        }

        /// <summary>
        /// Deletes the file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> DeleteFile(string fileName, string userName)
        {
            await InitStorage(userName);
            var blob = await _userStorage.GetBlobReferenceFromServerAsync(fileName);
            await _storageManager.DeleteFile((CloudBlockBlob)blob);
            await LogMessage(String.Format("Delete File: {0} Username:{1}",fileName,userName));
            return Request.CreateResponse<string>(fileName);
        }

        /// <summary>
        /// BLOBs the exists on cloud.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        private async Task<HttpResponseMessage> BlobExistsOnCloud(string key,string userName)
        {

            await InitStorage(userName);

          var value =  await Task.Run(() =>
            {
                var ok = _storageManager.BlobExistsOnCloud(this._userStorage, key);
                return ok;
            });

          return Request.CreateResponse<bool>(value);
        }

        /// <summary>
        /// Jsons the directory data.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> JsonDirectoryData(string userName)
        {

            await InitStorage(userName);

            await LogMessage(String.Format("Export JSON, username: {0} ",userName));

            var json = await _exporter.Storage2JSON();

            return Request.CreateResponse<string>(json);
        }
    }
}


text:
namespace UiMatic
{
    public interface IHavePreferredSelectorType
    {
        SelectorType PreferredSelectorType { get; }
    }
}


text:
using System;
using TQVaultAE.Domain.Entities;

namespace TQVaultAE.Domain.Results
{
	public class LoadVaultResult
	{
		public PlayerCollection Vault;
		public string Filename;
		public bool VaultLoaded;
		public ArgumentException ArgumentException;
	}
}


text:
package com.justjournal.services;

import com.justjournal.exception.ServiceException;
import com.justjournal.model.AvatarSource;
import com.justjournal.model.PrefBool;
import com.justjournal.model.UserPic;
import com.justjournal.model.UserPref;
import com.justjournal.repository.UserPicRepository;
import com.justjournal.repository.UserPrefRepository;
import io.minio.*;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.ServerException;
import io.minio.errors.XmlParserException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Optional;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/** @author Lucas Holt */
@Slf4j
@Service
public class ImageStorageService {

  @Setter
  @Value("${bucket.avatar:jjavatar}")
  private String avatarBucket;

  @Setter
  @Value("${bucket.image:jjimages}")
  private String imageBucket;

  @Autowired private MinioClient minioClient;

  @Autowired private UserImageService userImageService;

  @Autowired private UserPicRepository userPicRepository;

  @Autowired private UserPrefRepository userPrefRepository;

  private static final String USER_ID_ARGUMENT = "userId";

  public void deleteAvatar(final int userId) throws ServiceException {
    final Optional<UserPref> pref = userPrefRepository.findById(userId);
    if (pref.isEmpty()) {
      throw new IllegalArgumentException(USER_ID_ARGUMENT);
    }

    final Optional<UserPic> userPic = userPicRepository.findById(userId);
    if (userPic.isPresent()) {

      String filename = userPic.get().getFilename();
      if (filename == null) filename = getAvatarFileName(userId, userPic.get().getMimeType());

      try {
        deleteFile(avatarBucket, filename);
        userPicRepository.deleteById(userId);

        pref.get().setShowAvatar(PrefBool.N);
        userPrefRepository.save(pref.get());
      } catch (final Exception e) {
        log.error("Unable to delete avatar file {} for user {}", filename, userId, e);
        throw new ServiceException("Unable to delete avatar");
      }
    }
  }

  public void uploadAvatar(
      final int userId,
      @NonNull final String mimeType,
      @NonNull final AvatarSource source,
      @NonNull final InputStream is)
      throws ServiceException {

    if (userId < 1) throw new IllegalArgumentException(USER_ID_ARGUMENT);

    try {
      Optional<UserPic> userPic = userPicRepository.findById(userId);
      if (userPic.isEmpty()) {
        userPic = Optional.of(new UserPic());
      }

      final UserPic entity = userPic.get();
      entity.setId(userId);
      entity.setMimeType(mimeType);
      entity.setModified(Calendar.getInstance().getTime());
      entity.setSource(source);
      entity.setFilename(getAvatarFileName(userId, mimeType));

      userPicRepository.save(entity);

      uploadFile(avatarBucket, entity.getFilename(), mimeType, is);

      final Optional<UserPref> pref = userPrefRepository.findById(userId);
      if (pref.isEmpty()) {
        throw new IllegalArgumentException(USER_ID_ARGUMENT);
      }
      pref.get().setShowAvatar(PrefBool.N);
      userPrefRepository.save(pref.get());
    } catch (final Exception e) {
      log.error("Could not upload avatar", e);
      throw new ServiceException("Unable to save avatar");
    }
  }

  public InputStream downloadAvatar(final int userId) throws ServiceException {
    try {
      final Optional<UserPic> userPic = userPicRepository.findById(userId);
      if (userPic.isEmpty()) {
        throw new IllegalArgumentException(USER_ID_ARGUMENT);
      }
      return downloadFile(avatarBucket, userPic.get().getFilename());
    } catch (final Exception e) {
      log.error("Could not fetch avatar", e);
      throw new ServiceException("Unable to download avatar");
    }
  }

  protected String getAvatarFileName(final int id, @NonNull final String mimeType) {
    final String name = "avatar_" + id;

    if (mimeType.contains("jpeg") || mimeType.contains("jpg")) {
      return name + ".jpg";
    } else if (mimeType.contains("png") || mimeType.contains("ping")) {
      return name + ".png";
    } else if (mimeType.contains("gif")) {
      return name + ".gif";
    }

    return name;
  }

  /**
   * upload a file and will close inputstream upon completion.
   *
   * @param bucketName bucket to store images in
   * @param objectName image name or file name
   * @param mimeType image mime type
   * @param is input stream (preferably a ByteArrayInputStream)
   * @throws IOException
   * @throws InvalidKeyException
   * @throws NoSuchAlgorithmException
   * @throws InsufficientDataException
   * @throws ErrorResponseException
   * @throws InvalidResponseException
   */
  public void uploadFile(
      @NonNull final String bucketName,
      @NonNull final String objectName,
      @NonNull final String mimeType,
      @NonNull final InputStream is)
      throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException,
          ErrorResponseException, InvalidResponseException, InternalException, XmlParserException,
          ServerException {

    if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
      minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
    }

    if (is instanceof ByteArrayInputStream)
      minioClient.putObject(
          PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                  is, is.available(), -1)
              .contentType(mimeType)
              .build());
    else
      minioClient.putObject(
          PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(is, -1, 10485760)
              .contentType(mimeType)
              .build());
    is.close();
  }

  public InputStream downloadFile(
      @NonNull final String bucketName, @NonNull final String objectName)
      throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException,
          ErrorResponseException, InvalidResponseException, InternalException, XmlParserException,
          ServerException {

    return minioClient.getObject(
        GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
  }

  public void deleteFile(@NonNull final String bucketName, @NonNull final String objectName)
      throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException,
          InvalidResponseException, ErrorResponseException, InternalException, XmlParserException,
          ServerException {
    minioClient.removeObject(
        RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
  }
}


text:
+++
Title = "Tom McLaughlin"
Twitter = "tmclaughbos"
Website = "https://www.serverlessops.io/"
Linkedin = "https://www.linkedin.com/in/tmclaugh/"
Pronouns = "he/him"
Github = "tmclaugh"
image = "tom-mclaughlin.png"
type = "speaker"
linktitle = "tom-mclaughlin"

+++

Tom is the founder of [ServerlessOps](https://www.serverlessops.io) and
an experienced operations engineer. He started ServerlessOps after he
asked the question, what would he do if servers went away? At a loss for
an answer and interested in the future of his profession, he decided to
pursue the answer. Tom is actively engaged in promoting serverless
infrastructure and engaging with the community to learn more about their
thoughts, wants, and concerns are around the topic.

Previously, Tom has worked in Engineering and Developer Relations. As an
engineer he enjoyed building automation tools and platform automation
infrastructure. His goal was to ensure that he was never a roadblock for
someone else getting their work done. While in Developer Relations he
enjoyed showing other engineers how to do the same.

When not at work he is a proud cat dad to two calicoes and enjoys
spending his time drag racing and sailing. He is also an amateur
thinkfluencer on Twitter.


text:
import sys
import os
import unittest

sys.path.append(os.path.join(os.path.dirname(__file__), '../lib'))

from testlib import get_fixture, function, random_string
from testlib import EapiConfigUnitTest

import pyeapi.api.routemaps

class TestApiRoutemaps(EapiConfigUnitTest):

    def __init__(self, *args, **kwargs):
        super(TestApiRoutemaps, self).__init__(*args, **kwargs)
        self.instance = pyeapi.api.routemaps.Routemaps(None)
        self.config = open(get_fixture('running_config.routemaps')).read()

    def test_instance(self):
        result = pyeapi.api.routemaps.instance(None)
        self.assertIsInstance(result, pyeapi.api.routemaps.Routemaps)

    def test_get(self):
        result = self.instance.get('TEST')
        keys = ['deny', 'permit']
        self.assertEqual(sorted(keys), sorted(result.keys()))

    def test_get_not_configured(self):
        self.assertIsNone(self.instance.get('blah'))

    def test_getall(self):
        result = self.instance.getall()
        self.assertIsInstance(result, dict)

    def test_routemaps_functions(self):
        for name in ['create', 'delete', 'default']:
            if name == 'create':
                cmds = 'route-map new permit 100'
            elif name == 'delete':
                cmds = 'no route-map new permit 100'
            elif name == 'default':
                cmds = 'default route-map new permit 100'
            func = function(name, 'new', 'permit', 100)
            self.eapi_positive_config_test(func, cmds)

    def test_set_set_statement_clean(self):
        cmds = ['route-map new permit 100', 'set weight 100']
        func = function('set_set_statements', 'new', 'permit', 100,
                        ['weight 100'])
        self.eapi_positive_config_test(func, cmds)

    def test_set_set_statement_remove_extraneous(self):
        # Review fixtures/running_config.routemaps to see the default
        # running-config that is the basis for this test
        cmds = ['route-map TEST permit 10', 'no set tag 50',
                'route-map TEST permit 10', 'set weight 100']
        func = function('set_set_statements', 'TEST', 'permit', 10,
                        ['weight 100'])
        self.eapi_positive_config_test(func, cmds)

    def test_set_match_statement_clean(self):
        cmds = ['route-map new permit 200', 'match as 100']
        func = function('set_match_statements', 'new', 'permit', 200,
                        ['as 100'])
        self.eapi_positive_config_test(func, cmds)

    def test_set_match_statement_remove_extraneous(self):
        # Review fixtures/running_config.routemaps to see the default
        # running-config that is the basis for this test
        cmds = ['route-map TEST permit 10', 'no match interface Ethernet1',
                'route-map TEST permit 10', 'match as 1000']
        func = function('set_match_statements', 'TEST', 'permit', 10,
                        ['as 1000'])
        self.eapi_positive_config_test(func, cmds)

    def test_set_continue(self):
        cmds = ['route-map TEST permit 10', 'continue 100']
        func = function('set_continue', 'TEST', 'permit', 10, 100)
        self.eapi_positive_config_test(func, cmds)

    def test_set_continue_with_invalid_integer(self):
        with self.assertRaises(ValueError):
            self.instance.set_continue('TEST', 'permit', 10, -1)

    def test_set_continue_with_invalid_string(self):
        with self.assertRaises(ValueError):
            self.instance.set_continue('TEST', 'permit', 10, 'invalid')

    def test_set_continue_to_default(self):
        cmds = ['route-map TEST permit 10', 'default continue']
        func = function('set_continue', 'TEST', 'permit', 10, default=True)
        self.eapi_positive_config_test(func, cmds)

    def test_negate_continue(self):
        cmds = ['route-map TEST permit 10', 'no continue']
        func = function('set_continue', 'TEST', 'permit', 10, disable=True)
        self.eapi_positive_config_test(func, cmds)

    def test_set_description_with_value(self):
        value = random_string()
        cmds = ['route-map TEST permit 10', 'no description',
                'description %s' % value]
        func = function('set_description', 'TEST', 'permit', 10, value)
        self.eapi_positive_config_test(func, cmds)

    def test_negate_description(self):
        cmds = ['route-map TEST permit 10', 'no description']
        func = function('set_description', 'TEST', 'permit', 10, disable=True)
        self.eapi_positive_config_test(func, cmds)

    def test_set_description_with_default(self):
        cmds = ['route-map TEST permit 10', 'default description']
        func = function('set_description', 'TEST', 'permit', 10, default=True)
        self.eapi_positive_config_test(func, cmds)

    def test_set_description_with_invalid_value(self):
        # with self.assertRaises(ValueError):
        #     self.instance.set_description('TEST', 'permit', 10, value=None)
        # If command_builder fails because value is None, uncomment
        # above lines and remove below lines.
        cmds = ['route-map TEST permit 10', 'no description']
        func = function('set_description', 'TEST', 'permit', 10, value=None)
        self.eapi_positive_config_test(func, cmds)

if __name__ == '__main__':
    unittest.main()


text:
package org.ldp4j.application.sdk;

import java.util.List;
import java.util.Objects;

import org.ldp4j.application.engine.context.HttpRequest.Header;

import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;

public final class ImmutableHeader implements Header {

	private static final long serialVersionUID = 7192427783850618802L;

	private final String name;
	private final String rawValue;
	private final ImmutableList<Element> elements;

	ImmutableHeader(String name, String rawValue, List<ImmutableElement> elements) {
		this.name=name;
		this.rawValue=rawValue;
		this.elements=ImmutableList.<Element>copyOf(elements);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String name() {
		return this.name;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String rawValue() {
		return this.rawValue;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ImmutableList<Element> elements() {
		return this.elements;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int hashCode() {
		return
			Objects.
				hash(this.name,this.rawValue,this.elements);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean equals(Object obj) {
		boolean result = false;
		if(obj instanceof Header) {
			Header that=(Header)obj;
			result=
				Objects.equals(this.name,that.name()) &&
				Objects.equals(this.rawValue,that.rawValue()) &&
				Objects.equals(this.elements,that.elements());
		}
		return result;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toString() {
		return
			MoreObjects.
				toStringHelper(Header.class).
					add("name",this.name).
					add("rawValue",this.rawValue).
					add("elements",this.elements).
					toString();
	}

}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content_shell_apk;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import org.chromium.base.ChromiumActivity;
import org.chromium.content.app.LibraryLoader;
import org.chromium.content.browser.ActivityContentVideoViewDelegate;
import org.chromium.content.browser.ContentVideoView;
import org.chromium.content.browser.ContentView;
import org.chromium.content.browser.DeviceUtils;
import org.chromium.content.browser.TracingIntentHandler;
import org.chromium.content.common.CommandLine;
import org.chromium.content.common.ProcessInitException;
import org.chromium.content_shell.Shell;
import org.chromium.content_shell.ShellManager;
import org.chromium.ui.gfx.ActivityNativeWindow;

/**
 * Activity for managing the Content Shell.
 */
public class ContentShellActivity extends ChromiumActivity {

    public static final String COMMAND_LINE_FILE = "/data/local/tmp/content-shell-command-line";
    private static final String TAG = ContentShellActivity.class.getName();

    private static final String ACTIVE_SHELL_URL_KEY = "activeUrl";
    private static final String ACTION_START_TRACE =
            "org.chromium.content_shell.action.PROFILE_START";
    private static final String ACTION_STOP_TRACE =
            "org.chromium.content_shell.action.PROFILE_STOP";
    public static final String COMMAND_LINE_ARGS_KEY = "commandLineArgs";

    private ShellManager mShellManager;
    private ActivityNativeWindow mActivityNativeWindow;
    private BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initializing the command line must occur before loading the library.
        if (!CommandLine.isInitialized()) {
            CommandLine.initFromFile(COMMAND_LINE_FILE);
            String[] commandLineParams = getCommandLineParamsFromIntent(getIntent());
            if (commandLineParams != null) {
                CommandLine.getInstance().appendSwitchesAndArguments(commandLineParams);
            }
        }
        waitForDebuggerIfNeeded();

        DeviceUtils.addDeviceSpecificUserAgentSwitch(this);
        try {
            LibraryLoader.ensureInitialized();

            setContentView(R.layout.content_shell_activity);
            mShellManager = (ShellManager) findViewById(R.id.shell_container);
            mActivityNativeWindow = new ActivityNativeWindow(this);
            mActivityNativeWindow.restoreInstanceState(savedInstanceState);
            mShellManager.setWindow(mActivityNativeWindow);
            ContentVideoView.registerContentVideoViewContextDelegate(
                    new ActivityContentVideoViewDelegate(this));

            String startupUrl = getUrlFromIntent(getIntent());
            if (!TextUtils.isEmpty(startupUrl)) {
                mShellManager.setStartupUrl(Shell.sanitizeUrl(startupUrl));
            }
            if (!ContentView.enableMultiProcess(this, ContentView.MAX_RENDERERS_AUTOMATIC)) {
                String shellUrl = ShellManager.DEFAULT_SHELL_URL;
                if (savedInstanceState != null
                    && savedInstanceState.containsKey(ACTIVE_SHELL_URL_KEY)) {
                    shellUrl = savedInstanceState.getString(ACTIVE_SHELL_URL_KEY);
                }
                mShellManager.launchShell(shellUrl);
            }
        } catch (ProcessInitException e) {
            Log.e(TAG, "ContentView initialization failed.", e);
            finish();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Shell activeShell = getActiveShell();
        if (activeShell != null) {
            outState.putString(ACTIVE_SHELL_URL_KEY, activeShell.getContentView().getUrl());
        }

        mActivityNativeWindow.saveInstanceState(outState);
    }

    private void waitForDebuggerIfNeeded() {
        if (CommandLine.getInstance().hasSwitch(CommandLine.WAIT_FOR_JAVA_DEBUGGER)) {
            Log.e(TAG, "Waiting for Java debugger to connect...");
            android.os.Debug.waitForDebugger();
            Log.e(TAG, "Java debugger connected. Resuming execution.");
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode != KeyEvent.KEYCODE_BACK) return super.onKeyUp(keyCode, event);

        Shell activeView = getActiveShell();
        if (activeView != null && activeView.getContentView().canGoBack()) {
            activeView.getContentView().goBack();
            return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (getCommandLineParamsFromIntent(intent) != null) {
            Log.i(TAG, "Ignoring command line params: can only be set when creating the activity.");
        }

        String url = getUrlFromIntent(intent);
        if (!TextUtils.isEmpty(url)) {
            Shell activeView = getActiveShell();
            if (activeView != null) {
                activeView.loadUrl(url);
            }
        }
    }

    @Override
    protected void onPause() {
        ContentView view = getActiveContentView();
        if (view != null) view.onActivityPause();

        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();

        ContentView view = getActiveContentView();
        if (view != null) view.onActivityResume();
        IntentFilter intentFilter = new IntentFilter(ACTION_START_TRACE);
        intentFilter.addAction(ACTION_STOP_TRACE);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                String extra = intent.getStringExtra("file");
                if (ACTION_START_TRACE.equals(action)) {
                    if (extra.isEmpty()) {
                        Log.e(TAG, "Can not start tracing without specifing saving location");
                    } else {
                        TracingIntentHandler.beginTracing(extra);
                        Log.i(TAG, "start tracing");
                    }
                } else if (ACTION_STOP_TRACE.equals(action)) {
                    Log.i(TAG, "stop tracing");
                    TracingIntentHandler.endTracing();
                }
            }
        };
        registerReceiver(mReceiver, intentFilter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mActivityNativeWindow.onActivityResult(requestCode, resultCode, data);
    }

    private static String getUrlFromIntent(Intent intent) {
        return intent != null ? intent.getDataString() : null;
    }

    private static String[] getCommandLineParamsFromIntent(Intent intent) {
        return intent != null ? intent.getStringArrayExtra(COMMAND_LINE_ARGS_KEY) : null;
    }

    /**
     * @return The {@link ShellManager} configured for the activity or null if it has not been
     *         created yet.
     */
    public ShellManager getShellManager() {
        return mShellManager;
    }

    /**
     * @return The currently visible {@link Shell} or null if one is not showing.
     */
    public Shell getActiveShell() {
        return mShellManager != null ? mShellManager.getActiveShell() : null;
    }

    /**
     * @return The {@link ContentView} owned by the currently visible {@link Shell} or null if one
     *         is not showing.
     */
    public ContentView getActiveContentView() {
        Shell shell = getActiveShell();
        return shell != null ? shell.getContentView() : null;
    }
}


text:
package io.ddf.spark.content

import io.ddf.content.{Representation, ConvertFunction}
import io.ddf.DDF
import org.apache.spark.sql.catalyst.expressions.Row
import io.ddf.content.Schema.Column
import org.apache.spark.rdd.RDD

/**
  */
class RDDRow2ArrayDouble(@transient ddf: DDF) extends ConvertFunction(ddf) with RowToArray {

  override def apply(representation: Representation): Representation = {
    val columns = ddf.getSchemaHandler.getColumns
    representation.getValue match {
      case rdd: RDD[Row] =>
        val rddArrDouble = rdd.map {
          row => rowToArrayDouble(row, columns.toArray(new Array[Column](columns.size())))
        }.filter(row => row != null)
        new Representation(rddArrDouble, RepresentationHandler.RDD_ARR_DOUBLE.getTypeSpecsString)
    }
  }
}