text:
package jcrush;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jcrush.io.ConnectionType;
import jcrush.io.Requester;
import jcrush.model.FileStatus;
import jcrush.model.FileType;
import jcrush.model.MediaCrushFile;
import jcrush.system.Validator;
import jcrush.system.exceptions.FileUploadFailedException;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static jcrush.system.Constants.*;
import static jcrush.system.Utils.*;

/**
 * Static methods that expose the MediaCrush API
 */
public class JCrush {

    private static final Gson GSON;

    private static final String DEFAULT_SERVER_API_URL = MEDIA_CRUSH_URL + API_DIRECTORY;
    private static String serverApiUrl = DEFAULT_SERVER_API_URL;

    static {
        GSON = new Gson();
        _setSystemProperties();
    }

    /**
     * Change the server URL where the API resides. By default,
     * it uses https://www.mediacru.sh/api
     * @param serverApiUrl The URL where the API waits for connections.
     */
    public static void changeApiURL(String serverApiUrl) {
    	JCrush.serverApiUrl = serverApiUrl;
    }

    /**
     * Get the server URL where the API resides. By default, it uses https://www.mediacru.sh/api
     * @return
     *        The URL where the API waits for connections.
     */
    public static String getApiURL() {
        return serverApiUrl;
    }

    private static void _setSystemProperties() {
        System.setProperty("http.agent", DEFAULT_USER_AGENT);
    }

    /**
     * Returns information about the file whose hash is hash
     * @param hash
     *            NOT NULLABLE
     *

     *            - The hash of the file to retrieve.
     * @return
     *        The file represented as a {@link MediaCrushFile} object
     * @throws IOException
     *                    An {@link IOException} can be thrown for the following reasons:

     *                    * There was an error invoking {@link jcrush.io.Requester#connect()}

     *                    * The json returned contained a 404 error
     * @see jcrush.io.Requester#connect()
     */
    public static MediaCrushFile getFileInfo(String hash) throws IOException {
        Validator.validateNotNull(hash, "hash");

        URL uri = new URL(serverApiUrl + hash);
        Requester requester = new Requester(ConnectionType.GET, uri);
        requester.setRecieve(true);
        requester.connect();

        String json = requester.getResponse();
        requester.disconnect();
        Validator.validateNot404(json);

        MediaCrushFile toreturn = GSON.fromJson(json, MediaCrushFile.class);

        try {
            setHash(toreturn, hash);
        } catch (NoSuchFieldException e) {
            throw new IOException("Hash could not be set for MediaCrushFile!", e);
        } catch (IllegalAccessException e) {
            throw new IOException("Hash could not be set for MediaCrushFile!", e);
        }

        return toreturn;
    }

    /**
     * Returns an array of {@link MediaCrushFile} containing information about the file whose hash is hash
     * @param hash
     *           NOT NULLABLE
     *

     *           - An array of hash's to lookup
     * @return
     *        An array of files represented as a {@link MediaCrushFile} object
     * @throws IOException
     *                    An {@link IOException} can be thrown for the following reasons:

     *                    * There was an error invoking {@link jcrush.io.Requester#connect()}

     *                    * The json returned contained a 404 error
     * @see jcrush.io.Requester#connect()
     */
    public static MediaCrushFile[] getFileInfos(String... hash) throws IOException {
        Validator.validateNotNull(hash, "hash");

        String list = "";
        for (int i = 0; i < hash.length; i++) {
            if (i == 0)
                list = hash[i];
            else
                list += "," + hash[i];
        }

        URL uri = new URL(serverApiUrl + "info?list=" + list);
        Requester requester = new Requester(ConnectionType.GET, uri);
        requester.setRecieve(true);
        requester.connect();

        String json = requester.getResponse();
        requester.disconnect();
        Validator.validateNot404(json);

        Type mapType = new TypeToken<HashMap<String, MediaCrushFile>>(){}.getType();
        HashMap<String, MediaCrushFile> map = GSON.fromJson(json, mapType);

        MediaCrushFile[] array = new MediaCrushFile[map.size()];
        int i = 0;
        for (String key : map.keySet()) {
            try {
                setHash(map.get(key), key);
            } catch (NoSuchFieldException e) {
                throw new IOException("Hash could not be set for MediaCrushFile \"" + key + "\"", e);
            } catch (IllegalAccessException e) {
                throw new IOException("Hash could not be set for MediaCrushFile \"" + key + "\"", e);
            }
            array[i] = map.get(key);
            i++;
        }

        return array;
    }

    /**
     * A convenience method. Returns a {@link MediaCrushFile} object with all info attached and does not throw an exception
     * when the file does not exist. When the hash specified does not exist, this method simply returns null.
     * @param hash
     *            The hash to retrieve
     * @return
     *        The file represented as a {@link MediaCrushFile} object.
     * @throws IOException
     *                    This exception can be thrown if {@link JCrush#getFileInfo(String)} or {@link JCrush#getFileStatus(String)} throws an exception
     * @see JCrush#getFileInfo(String)
     * @see JCrush#getFileStatus(String)
     */
    public static MediaCrushFile getFile(String hash) throws IOException {
        if (!doesExists(hash))
            return null;

        MediaCrushFile file = getFileInfo(hash);
        FileStatus status = getFileStatus(hash).getStatus();

        try {
            setStatus(file, status);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return file;
    }

    /**
     * A convenience method. Returns a {@link MediaCrushFile} object with all info attached and does not throw an exception
     * when the file does not exist. When the hash specified does not exist, this method simply returns null.

     * If any file throws an {@link IOException}, then the exception is ignored and the file in the array is set to null.
     * @param hash
     *            The hash(s) to retrieve
     * @return
     *        The file(s) represented as an array of {@link MediaCrushFile} object(s).
     */
    public static MediaCrushFile[] getFiles(String... hash) {
        MediaCrushFile[] files = new MediaCrushFile[hash.length];
        for (int i = 0; i < files.length; i++) {
            try {
                files[i] = getFile(hash[i]);
            } catch (IOException e) {
                files[i] = null;
            }
        }

        return files;
    }

    /**
     * Returns whether a hash exists or not.
     * @param hash
     *            The hash to lookup
     * @return
     *        true if the has exists or false if it does not
     * @throws IOException
     *                    An {@link IOException} will be thrown if {@link jcrush.io.Requester#connect()} raises an exception
     * @see jcrush.io.Requester#connect()
     */
    public static boolean doesExists(String hash) throws IOException {
        Validator.validateNotNull(hash, "hash");

        URL uri = new URL(serverApiUrl + hash + "/exists");
        Requester requester = new Requester(ConnectionType.HEAD, uri);
        requester.setRecieve(true);
        try {
            requester.connect();
        } catch (FileNotFoundException ignored) {
            requester.disconnect();
            return false;
        }
        requester.disconnect();
        return true;
    }

    /**
     * Upload a file to mediacru.sh

     * This method creates a new instance of a {@link File} and then invoke {@link JCrush#uploadFile(java.io.File)}
     * @param filePath
     *                The full file path to the file that will be uploaded to mediacru.sh
     * @throws IOException
     *                    An IOException can be thrown for the following reasons:

     *                    * The file path specified is not a file, but a directory

     *                    * The file path specified does not exist

     *                    * {@link JCrush#uploadFile(java.io.File)} raises an Exception

     * @see JCrush#uploadFile(java.io.File)
     */
    public static void uploadFile(String filePath) throws IOException {
        Validator.validateNotNull(filePath, "filePath");
        File file = new File(filePath);
        if (!file.exists())
            throw new FileNotFoundException("The file could not be found!");
        else if (file.isDirectory())
            throw new IOException("The filePath specified is a directory!");
        else
            uploadFile(file);
    }

    /**
     * Upload the file specified in the parameter to mediacru.sh

     * Only the following file types are allowed:

     * * .png

     * * .jpg

     * * .jpeg

     * * .gif

     * * .mp4

     * * .ogv

     * * .mp3

     * * .ogg

     * An unknown file type will raise an {@link IOException}

     *
     * @param file
     *            The file to upload represented as a {@link File} object
     * @return
     *        The hash of the currently uploading file on mediacru.sh
     * @throws FileUploadFailedException
     *                                  A FileUploadFiledException can be thrown for the following reasons:

     *                                  * The file was already uploaded.

     *                                  * The rate limit was exceeded.

     *                                  * The file extension is not acceptable. However, for this to be thrown is highly unlikely. An {@link IOException} will be thrown first
     *                                  before the upload with the reason "Unknown file type!"
     * @throws IOException
     *                    An IOException can be thrown for the following reasons:

     *                    * An unknown file type was specified

     *                    * The file specified does not exist

     *                    * The file specified is not a file, but a directory

     *                    * An unknown error code was returned from the server

     */
    public static String uploadFile(File file) throws IOException {
        Validator.validateNotNull(file, "file");

        if (!file.exists())
            throw new FileNotFoundException();
        if (file.isDirectory())
            throw new IOException("This file is a directory!");

        //Get content type of file
        FileType contentType = FileType.toFileType(toContentType(file));
        if (contentType == null)
            throw new IOException("Unknown file type!");

        return uploadFile(new FileInputStream(file), contentType, file.getName());
    }

    /**
     * Upload an image/sound/video to mediacru.sh using the data provided in the InputStream provided

     * This method requires a file name with an extension at the end. This can be provided manually or you can use the
     * helper method {@link jcrush.model.FileType#getFileExtension()}

     * Only the following file types are allowed:

     * * .png

     * * .jpg

     * * .jpeg

     * * .gif

     * * .mp4

     * * .ogv

     * * .mp3

     * * .ogg

     * An unknown file type will raise an {@link IOException}

     *
     * @param imageData
     *                 The {@link InputStream} with the image data to upload
     * @param type
     *            The {@link FileType} of the data being uploaded
     * @param fileName
     *                 The file name for this data INCLUDING the file extension.
     * @return
     *        The hash of the currently uploading file on mediacru.sh
     * @throws FileUploadFailedException
     *                                  A FileUploadFiledException can be thrown for the following reasons:

     *                                  * The file was already uploaded.

     *                                  * The rate limit was exceeded.

     *                                  * The file extension is not acceptable. However, for this to be thrown is highly unlikely. An {@link IOException} will be thrown first
     *                                  before the upload with the reason "Unknown file type!"
     * @throws IOException
     *                    An IOException can be thrown for the following reasons:

     *                    * An unknown file type was specified

     *                    * The file specified does not exist

     *                    * The file specified is not a file, but a directory

     *                    * An unknown error code was returned from the server

     */
    public static String uploadFile(InputStream imageData, FileType type, String fileName) throws IOException {

        //Read file into byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copy(imageData, baos, 1024);
        byte[] bytes = baos.toByteArray();

        //Prepare form data to send
        String header = "\r\n--" + CONTENT_DIVIDER + "\r\n" +
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + "\r\n" +
                "Content-Type: " + type.toString() + "\r\n" +
                "Content-Transfer-Encoding: binary\r\n" +
                "\r\n";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.write(header.getBytes("ASCII"));
        bos.write(bytes);
        String footer = "\r\n--" + CONTENT_DIVIDER + "--";
        bos.write(footer.getBytes("ASCII"));
        byte[] tosend = bos.toByteArray();

        //Prepare the requester with form data
        URL uri = new URL(serverApiUrl + "upload/file");
        Requester requester = new Requester(ConnectionType.POST, uri);
        requester.setPostData(tosend);
        requester.addHeader("Content-Length", "" + tosend.length);
        requester.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        requester.addHeader("Accept-Encoding", "gzip, deflate");
        requester.addHeader("X-Requested-With", "XMLHttpRequest");
        requester.addHeader("Content-Type", "multipart/form-data; boundary=" + CONTENT_DIVIDER);
        requester.setRecieve(true);
        try {
            requester.connect(); //Connect
        } catch (IOException e) {
            BufferedReader read = new BufferedReader(new InputStreamReader(
                    requester.getErrorStream()));
            StringBuilder builder = new StringBuilder(100);
            String line;
            while ((line = read.readLine()) != null)
                builder.append(line);
            read.close();
            String reason = builder.toString();

            int code = requester.getResponseCode();
            switch (code) {
                case 409:
                    throw new FileUploadFailedException("This file was already uploaded!", e);
                case 420:
                    throw new FileUploadFailedException("The rate limit was exceeded. Enhance your calm.", e);
                case 415:
                    throw new FileUploadFailedException("The file extension is not acceptable.", e);
                default:
                    throw new IOException("The server responded with an unknown error code! (" + code + ")", e);
            }
        }

        //Parse results
        int code = requester.getResponseCode();
        String json = requester.getResponse();
        requester.disconnect(); //Disconnect
        Map map = GSON.fromJson(json, Map.class);
        if (code == 200 && !map.containsKey("error")) {
            return (String)map.get("hash");
        } else {
            if (code == 200) {
                try {
                    code = Integer.parseInt((String)map.get("error"));
                } catch (Throwable t) {
                    throw new IOException("The server responded with an unknown error (" + (map.get("error") == null ? "null" : map.get("error")) + ")", t);
                }
            }
            switch (code) {
                case 409:
                    throw new FileUploadFailedException("This file was already uploaded!");
                case 420:
                    throw new FileUploadFailedException("The rate limit was exceeded. Enhance your calm.");
                case 415:
                    throw new FileUploadFailedException("The file extension is not acceptable.");
                default:
                    throw new IOException("The server responded with an unknown error code! (" + code + ")");
            }
        }
    }

    /**
     * Delete a file from mediacru.sh.

     * Only same IP as the uploader may delete the file specified. An {@link IOException} will be thrown if the IP's do
     * not match
     * @param hash
     *            The hash of the file to delete
     * @throws IOException
     *                    An IOException can be thrown for the following reasons:

     *                    * The hash specified does not exist

     *                    * The IP does not match the stored hash

     *                    * The server responded with an unknown error code.

     */
    public static void delete(String hash) throws IOException {
        Validator.validateNotNull(hash, "hash");

        URL uri = new URL(serverApiUrl + hash + "/delete");
        Requester requester = new Requester(ConnectionType.GET, uri);
        requester.setRecieve(true);
        try {
            requester.connect();
        } catch (FileNotFoundException e) {
            requester.disconnect();
            throw new IOException("There is no file with that hash!");
        }

        int code = requester.getResponseCode();
        requester.disconnect();

        if (code != 200) {
            if (code == 404)
                throw new IOException("There is no file with that hash!");
            else if (code == 401)
                throw new IOException("The IP does not match the stored hash!");
            else
                throw new IOException("The server responded with an unknown code! (" + code + ")");
        }
    }

    /**
     * Delete the {@link MediaCrushFile} object from mediacru.sh

     * Only same IP as the uploader may delete the file specified. An {@link IOException} will be thrown if the IP's do
     * not match
     * @param file
     *            The {@link MediaCrushFile} object that represents the file to delete
     * @throws IOException
     *                    An IOException will only be thrown if {@link JCrush#delete(String)} throws an exception
     * @see JCrush#delete(String)
     */
    public static void delete(MediaCrushFile file) throws IOException {
        Validator.validateNotNull(file, "file");
        delete(file.getHash());
    }

    /**
     * Get the current upload status for the file specified by the hash
     * @param hash
     *            The hash of the file
     * @return
     *        A {@link MediaCrushFile} object that represents the file.

     *        You can use {@link jcrush.model.MediaCrushFile#getStatus()} to get the status of the file
     * @throws IOException
     *                   An IOException can be thrown for the following reasons:

     *                   * {@link jcrush.io.Requester#connect()} throws an IOException
     *                   * There was an error constructing the {@link MediaCrushFile} file.
     * @see jcrush.io.Requester#connect()
     */
    public static MediaCrushFile getFileStatus(String hash) throws IOException {
        Validator.validateNotNull(hash, "hash");

        URL uri = new URL(serverApiUrl + hash + "/status");
        Requester requester = new Requester(ConnectionType.GET, uri);
        requester.setRecieve(true);
        requester.connect();

        String json = requester.getResponse();
        requester.disconnect();
        Validator.validateNot404(json);

        Map map = GSON.fromJson(json, Map.class);

        String statusString = (String) map.get("status");

        try {
            MediaCrushFile file = convertMapToFile((Map) map.get(hash));
            setHash(file, hash);
            setStatus(file, FileStatus.toFileStatus(statusString));

            return file;
        } catch (NoSuchFieldException e) {
            throw new IOException("Error creating MediaCrushFile", e);
        } catch (IllegalAccessException e) {
            throw new IOException("Error creating MediaCrushFile", e);
        } catch (InstantiationException e) {
            throw new IOException("Error creating MediaCrushFile", e);
        } catch (NoSuchMethodException e) {
            throw new IOException("Error creating MediaCrushFile", e);
        } catch (InvocationTargetException e) {
            throw new IOException("Error creating MediaCrushFile", e);
        }
    }
    /**
     * Upload the file at a URL to mediacru.sh

     * {@link JCrush#uploadFileViaURL(String)} is invoked with {@link java.net.URL#toString()} passed as the URL parameter
     * @param url
     *          The URL from where to fetch the file to upload, represented as a {@link URL} object
     * @return
     *        The hash of the currently uploading file on mediacru.sh
     * @throws IOException
     *                    An IOException will only be thrown if {@link JCrush#uploadFileViaURL(String)} throws an exception
     * @see JCrush#uploadFileViaURL(String)
     */
    public static String uploadFileViaURL(URL url) throws IOException {
        Validator.validateNotNull(url, "url");
        return uploadFileViaURL(url.toString());
    }

    /**
     * Upload the file at a URL to mediacru.sh

     * {@link JCrush#uploadFileViaURL(String)} is invoked with {@link java.net.URI#toString()} passed as the URL parameter
     * @param uri
     *          The URL from where to fetch the file to upload, represented as a {@link URI} object
     * @return
     *        The hash of the currently uploading file on mediacru.sh
     * @throws IOException
     *                    An IOException will only be thrown if {@link JCrush#uploadFileViaURL(String)} throws an exception
     * @see JCrush#uploadFileViaURL(String)
     */
    public static String uploadFileViaURL(URI uri) throws IOException {
        Validator.validateNotNull(uri, "uri");
        return uploadFileViaURL(uri.toString());
    }

    /**
     * Upload the file at a URL to mediacru.sh

     * @param url
     *            The URL from where to fetch the file to upload
     * @return
     *        The hash of the currently uploading file on mediacru.sh
     * @throws FileUploadFailedException
     *                                  A FileUploadFiledException can be thrown for the following reasons:

     *                                  * The file was already uploaded.

     *                                  * The rate limit was exceeded.

     *                                  * The file extension is not acceptable.

     *                                  * The URL was invalid

     *                                  * The file requested does not exist

     * @throws IOException
     *                    An IOException can be thrown for the following reasons:

     *                    * An unknown error code was returned from the server

     */
    public static String uploadFileViaURL(String url) throws IOException {
        Validator.validateNotNull(url, "url");

        String post = "url=" + url;
        URL uri = new URL(serverApiUrl + "upload/url");
        Requester requester = new Requester(ConnectionType.POST, uri);
        requester.setPostData(post);
        requester.addHeader("Content-Length", "" + post.length());
        requester.setRecieve(true);
        try {
            requester.connect(); //Connect
        } catch (IOException e) {
            BufferedReader read = new BufferedReader(new InputStreamReader(
                    requester.getErrorStream()));
            StringBuilder builder = new StringBuilder(100);
            String line;
            while ((line = read.readLine()) != null)
                builder.append(line);
            read.close();
            String reason = builder.toString();

            int code = requester.getResponseCode();
            switch (code) {
                case 400:
                    throw new FileUploadFailedException("The URL is invalid.", e);
                case 404:
                    throw new FileUploadFailedException("The file requested does not exist", e);
                case 409:
                    throw new FileUploadFailedException("This file was already uploaded!", e);
                case 420:
                    throw new FileUploadFailedException("The rate limit was exceeded. Enhance your calm.", e);
                case 415:
                    throw new FileUploadFailedException("The file extension is not acceptable.", e);
                default:
                    throw new IOException("The server responded with an unknown error code! (" + code + ")", e);
            }
        }

        //Parse results
        int code = requester.getResponseCode();
        String json = requester.getResponse();
        requester.disconnect(); //Disconnect
        Map map = GSON.fromJson(json, Map.class);
        if (code == 200 && !map.containsKey("error")) {
            return (String)map.get("hash");
        } else {
            if (code == 200) {
                try {
                    code = Integer.parseInt((String)map.get("error"));
                } catch (Throwable t) {
                    throw new IOException("The server responded with an unknown error (" + (map.get("error") == null ? "null" : map.get("error")) + ")", t);
                }
            }
            switch (code) {
                case 400:
                    throw new FileUploadFailedException("The URL is invalid.");
                case 404:
                    throw new FileUploadFailedException("The file requested does not exist");
                case 409:
                    throw new FileUploadFailedException("This file was already uploaded!");
                case 420:
                    throw new FileUploadFailedException("The rate limit was exceeded. Enhance your calm.");
                case 415:
                    throw new FileUploadFailedException("The file extension is not acceptable.");
                default:
                    throw new IOException("The server responded with an unknown error code! (" + code + ")");
            }
        }
    }
}


text:
void testDriverTestTestSuite(void);

void test_testDriverGetValue(void);

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.heliosapm.utils.ssh.terminal;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;

import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/**
	 *
Title: CommandTerminalImpl

	 *
Description: A wrapper of a session to provide a simplified command terminal

	 *
Company: Helios Development Group LLC

	 * @author Whitehead (nwhitehead AT heliosdev DOT org)
	 *
com.heliosapm.utils.ssh.terminal.WrappedSession.CommandTerminalImpl

	 */
	public class CommandTerminalImpl implements CommandTerminal {
		/** The underlying session */
		protected Session session;
		/** The underlying wrapped session */
		protected final WrappedSession wrappedSession;
		/** The input stream to read terminal output from */
		protected PushbackInputStream pbis;
		/** The output stream to write to the terminal */
		protected OutputStream terminalOut;
		/** The captured terminal tty */
		protected String tty = null;
		/** The command exit codes */
		protected Integer[] exitCodes = null;

		/**
		 * Creates a new CommandTerminalImpl
		 * @param wrappedSession The wrapped session
		 */
		public CommandTerminalImpl(final WrappedSession wrappedSession) {
			this.wrappedSession = wrappedSession;
			this.session = wrappedSession.session;

			try {
				terminalOut = session.getStdin();
				this.session.requestDumbPTY();
				this.session.startShell();
				pbis = new PushbackInputStream(new StreamGobbler(session.getStdout()));
				writeCommand("PS1=" + WrappedSession.PROMPT);
				readUntilPrompt(null);
				try {
					tty = exec("tty").toString().trim();
				}  catch (Exception x) {
					tty = null;
				}
				this.wrappedSession.connected.set(true);
			} catch (Exception e) {
				throw new RuntimeException("Failed to initialize session shell", e);
			}
		}

		public boolean isConnected() {
			return this.wrappedSession.isOpen();
		}

		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.utils.ssh.terminal.CommandTerminal#getResponseStream()
		 */
		public InputStream getResponseStream() {
			return pbis;
		}

		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.opentsdb.CommandTerminal#close()
		 */
		public void close() {
			try { session.close(); } catch (Exception x) {/* No Op */}
			session = null;
		}

		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.opentsdb.CommandTerminal#exec(java.lang.String[])
		 */
		@Override
		public StringBuilder exec(final String...commands) {
			return execWithDelim(null, commands);
		}

		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.opentsdb.CommandTerminal#execSplit(java.lang.String[])
		 */
		@Override
		public StringBuilder[] execSplit(String...commands) {
			try {
				final StringBuilder[] results = new StringBuilder[commands.length];
				exitCodes = new Integer[commands.length];
				int index = 0;
				for(String command: commands) {
					results[index] = new StringBuilder();
					writeCommand(command);
					readUntilPrompt(results[index]);
					exitCodes[index] = session.getExitStatus();
				    index++;
				}
				return results;
			} catch (Exception ex) {
				throw new RuntimeException("Command execution failed", ex);
			}
		}

		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.opentsdb.CommandTerminal#execWithDelim(java.lang.String, java.lang.String[])
		 */
		@Override
		public StringBuilder execWithDelim(final String outputDelim, final String... commands) {
			final StringBuilder b = new StringBuilder();
			final StringBuilder[] results = execSplit(commands);
			for(StringBuilder r: results) {
				b.append(r);
				if(outputDelim!=null) {
					b.append(outputDelim);
				}
			}
			return b;
		}

		/**
		 * Reads the input stream until the end of the submitted command
		 * @throws IOException thrown on any IO error
		 */
		void skipTillEndOfCommand() throws IOException {
		    boolean eol = false;
		    while (true) {
		      final char ch = (char) pbis.read();
		      switch (ch) {
		      case WrappedSession.CR:
		      case WrappedSession.LF:
		        eol = true;
		        break;
		      default:
		        if (eol) {
		          pbis.unread(ch);
		          return;
		        }
		      }
		    }
		  }

		/**
		 * Reads the input stream until the end of the expected prompt
		 * @param buff The buffer to append into. Content is discarded if null.
		 * @throws IOException thrown on any IO errors
		 */
		void readUntilPrompt(final StringBuilder buff) throws IOException {
			final StringBuilder cl = new StringBuilder();
			boolean eol = true;
			int match = 0;
			while (true) {
				final char ch = (char) pbis.read();
//				if(65535==(int)ch) return;
				switch (ch) {
				case WrappedSession.CR:
				case WrappedSession.LF:
					if (!eol) {
						if (buff != null) {
							buff.append(cl.toString()).append(WrappedSession.LF);
						}
						cl.setLength(0);
					}
					eol = true;
					break;
				default:
					if (eol) {
						eol = false;
					}
					cl.append(ch);
					break;
				}

				if (cl.length() > 0
						&& match < WrappedSession.PROMPT.length()
						&& cl.charAt(match) == WrappedSession.PROMPT.charAt(match)) {
					match++;
					if (match == WrappedSession.PROMPT.length()) {
						return;
					}
				} else {
					match = 0;
				}
			}
		}

		/**
		 * Writes a command to the terminal
		 * @param cmd The command to write
		 * @throws IOException thrown on any IO error
		 */
		void writeCommand(final String cmd) throws IOException {
			terminalOut.write(cmd.getBytes());
			terminalOut.write(WrappedSession.LF);
			skipTillEndOfCommand();
		}

		/**
		 * Returns the tty of this terminal
		 * @return the tty of this terminal
		 */
		public final String getTty() {
			return tty;
		}

		@Override
		public Integer[] getExitStatuses() {
			return exitCodes;
		}

	  }


text:
This project was a startup to sell food online after we failed to receive financial support I developed it independently

building an eCommerce web application with Django (djangoproject.com) & Bootstrap (getbootstrap.com). I used many technologies including Python, HTML, CSS, JQuery, AJAX, and more.

This is an eCommerce web app using Django for backend, Bootstrap for front-end, Heroku for hosting, and Stripe for payment proccessing (to be implemented).

# Product

The original product was called Como En Casa which offers quality homemade food cooked by selected people living in your own community. Our services make easier to hold a balanced diet based in homemade food and in addition promote employment creation (mainly among housewives) in order to support local economy and increase families' income.

# Initial Setup

You need to have Django and pip installed then you can run the following commands to run the apllication

```bash
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver

```

Then you can open the website in browser at http://localhost:8000/ or the admin site http://localhost:8000/admin if you need to add new products, new categories, etc.


text:
package org.apache.drill.exec.rpc.security;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.protobuf.ByteString;
import com.google.protobuf.Internal.EnumLite;
import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import org.apache.drill.exec.proto.UserBitShared.SaslMessage;
import org.apache.drill.exec.proto.UserBitShared.SaslStatus;
import org.apache.drill.exec.rpc.BasicClient;
import org.apache.drill.exec.rpc.ClientConnection;
import org.apache.drill.exec.rpc.RpcException;
import org.apache.drill.exec.rpc.RpcOutcomeListener;
import org.apache.hadoop.security.UserGroupInformation;

import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.PrivilegedExceptionAction;
import java.util.EnumMap;
import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Handles SASL exchange, on the client-side.
 *
 * @param <T> handshake rpc type
 * @param <C> Client connection type
 * @param <HS> Handshake send type
 * @param <HR> Handshake receive type
 */
public class AuthenticationOutcomeListener<T extends EnumLite, C extends ClientConnection,
    HS extends MessageLite, HR extends MessageLite>
    implements RpcOutcomeListener<SaslMessage> {
  private static final org.slf4j.Logger logger =
      org.slf4j.LoggerFactory.getLogger(AuthenticationOutcomeListener.class);

  private static final ImmutableMap<SaslStatus, SaslChallengeProcessor>
      CHALLENGE_PROCESSORS;
  static {
    final Map<SaslStatus, SaslChallengeProcessor> map = new EnumMap<>(SaslStatus.class);
    map.put(SaslStatus.SASL_IN_PROGRESS, new SaslInProgressProcessor());
    map.put(SaslStatus.SASL_SUCCESS, new SaslSuccessProcessor());
    map.put(SaslStatus.SASL_FAILED, new SaslFailedProcessor());
    CHALLENGE_PROCESSORS = Maps.immutableEnumMap(map);
  }

  private final BasicClient<T, C, HS, HR> client;
  private final C connection;
  private final T saslRpcType;
  private final UserGroupInformation ugi;
  private final RpcOutcomeListener<?> completionListener;

  public AuthenticationOutcomeListener(BasicClient<T, C, HS, HR> client,
                                       C connection, T saslRpcType, UserGroupInformation ugi,
                                       RpcOutcomeListener<?> completionListener) {
    this.client = client;
    this.connection = connection;
    this.saslRpcType = saslRpcType;
    this.ugi = ugi;
    this.completionListener = completionListener;
  }

  public void initiate(final String mechanismName) {
    logger.trace("Initiating SASL exchange.");
    try {
      final ByteString responseData;
      final SaslClient saslClient = connection.getSaslClient();
      if (saslClient.hasInitialResponse()) {
        responseData = ByteString.copyFrom(evaluateChallenge(ugi, saslClient, new byte[0]));
      } else {
        responseData = ByteString.EMPTY;
      }
      client.send(new AuthenticationOutcomeListener<>(client, connection, saslRpcType, ugi, completionListener),
          connection,
          saslRpcType,
          SaslMessage.newBuilder()
              .setMechanism(mechanismName)
              .setStatus(SaslStatus.SASL_START)
              .setData(responseData)
              .build(),
          SaslMessage.class,
          true /* the connection will not be backed up at this point */);
      logger.trace("Initiated SASL exchange.");
    } catch (final Exception e) {
      completionListener.failed(RpcException.mapException(e));
    }
  }

  @Override
  public void failed(RpcException ex) {
    completionListener.failed(RpcException.mapException(ex));
  }

  @Override
  public void success(SaslMessage value, ByteBuf buffer) {
    logger.trace("Server responded with message of type: {}", value.getStatus());
    final SaslChallengeProcessor processor = CHALLENGE_PROCESSORS.get(value.getStatus());
    if (processor == null) {
      completionListener.failed(RpcException.mapException(
          new SaslException("Server sent a corrupt message.")));
    } else {
      // SaslSuccessProcessor.process disposes saslClient so get mechanism here to use later in logging
      final String mechanism = connection.getSaslClient().getMechanismName();
      try {
        final SaslChallengeContext<C> context = new SaslChallengeContext<>(value, ugi, connection);
        final SaslMessage saslResponse = processor.process(context);

        if (saslResponse != null) {
          client.send(new AuthenticationOutcomeListener<>(client, connection, saslRpcType, ugi, completionListener),
              connection, saslRpcType, saslResponse, SaslMessage.class,
              true /* the connection will not be backed up at this point */);
        } else {
          // success
          completionListener.success(null, null);
          if (logger.isTraceEnabled()) {
            logger.trace("Successfully authenticated to server using {} mechanism and encryption context: {}",
                mechanism, connection.getEncryptionCtxtString());
          }
        }
      } catch (final Exception e) {
        logger.error("Authentication with encryption context: {} using mechanism {} failed with {}",
            connection.getEncryptionCtxtString(), mechanism, e.getMessage());
        completionListener.failed(RpcException.mapException(e));
      }
    }
  }

  @Override
  public void interrupted(InterruptedException e) {
    completionListener.interrupted(e);
  }

  private static class SaslChallengeContext<C extends ClientConnection> {

    final SaslMessage challenge;
    final UserGroupInformation ugi;
    final C connection;

    SaslChallengeContext(SaslMessage challenge, UserGroupInformation ugi, C connection) {
      this.challenge = checkNotNull(challenge);
      this.ugi = checkNotNull(ugi);
      this.connection = checkNotNull(connection);
    }
  }

  private interface SaslChallengeProcessor {

    /**
     * Process challenge from server, and return a response.
     *
     * Returns null iff SASL exchange is complete and successful.
     *
     * @param context challenge context
     * @return response
     * @throws Exception in case of any failure
     */
    <CC extends ClientConnection>
    SaslMessage process(SaslChallengeContext<CC> context) throws Exception;

  }

  private static class SaslInProgressProcessor implements SaslChallengeProcessor {

    @Override
    public <CC extends ClientConnection> SaslMessage process(SaslChallengeContext<CC> context) throws Exception {
      final SaslMessage.Builder response = SaslMessage.newBuilder();
      final SaslClient saslClient = context.connection.getSaslClient();

      final byte[] responseBytes = evaluateChallenge(context.ugi, saslClient,
          context.challenge.getData().toByteArray());

      final boolean isComplete = saslClient.isComplete();
      logger.trace("Evaluated challenge. Completed? {}.", isComplete);
      response.setData(responseBytes != null ? ByteString.copyFrom(responseBytes) : ByteString.EMPTY);
      // if isComplete, the client will get one more response from server
      response.setStatus(isComplete ? SaslStatus.SASL_SUCCESS : SaslStatus.SASL_IN_PROGRESS);
      return response.build();
    }
  }

  private static class SaslSuccessProcessor implements SaslChallengeProcessor {

    @Override
    public <CC extends ClientConnection> SaslMessage process(SaslChallengeContext<CC> context) throws Exception {
      final SaslClient saslClient = context.connection.getSaslClient();

      if (saslClient.isComplete()) {
        handleSuccess(context);
        return null;
      } else {
        // server completed before client; so try once, fail otherwise
        evaluateChallenge(context.ugi, saslClient, context.challenge.getData().toByteArray()); // discard response

        if (saslClient.isComplete()) {
          handleSuccess(context);
          return null;
        } else {
          throw new SaslException("Server allegedly succeeded authentication, but client did not. Suspicious?");
        }
      }
    }
  }

  private static class SaslFailedProcessor implements SaslChallengeProcessor {

    @Override
    public <CC extends ClientConnection> SaslMessage process(SaslChallengeContext<CC> context) throws Exception {
      throw new SaslException(String.format("Authentication failed. Incorrect credentials? [Details: %s]",
          context.connection.getEncryptionCtxtString()));
    }
  }

  private static byte[] evaluateChallenge(final UserGroupInformation ugi, final SaslClient saslClient,
                                          final byte[] challengeBytes) throws SaslException {
    try {
      return ugi.doAs(new PrivilegedExceptionAction<byte[]>() {
        @Override
        public byte[] run() throws Exception {
          return saslClient.evaluateChallenge(challengeBytes);
        }
      });
    } catch (final UndeclaredThrowableException e) {
      throw new SaslException(
          String.format("Unexpected failure (%s)", saslClient.getMechanismName()), e.getCause());
    } catch (final IOException | InterruptedException e) {
      if (e instanceof SaslException) {
        throw (SaslException) e;
      } else {
        throw new SaslException(
            String.format("Unexpected failure (%s)", saslClient.getMechanismName()), e);
      }
    }
  }

  private static <CC extends ClientConnection> void handleSuccess(SaslChallengeContext<CC> context) throws
      SaslException {
    final CC connection = context.connection;
    final SaslClient saslClient = connection.getSaslClient();

    try {
      // Check if connection was marked for being secure then verify for negotiated QOP value for
      // correctness.
      final String negotiatedQOP = saslClient.getNegotiatedProperty(Sasl.QOP).toString();
      final String expectedQOP = connection.isEncryptionEnabled()
          ? SaslProperties.QualityOfProtection.PRIVACY.getSaslQop()
          : SaslProperties.QualityOfProtection.AUTHENTICATION.getSaslQop();

      if (!(negotiatedQOP.equals(expectedQOP))) {
        throw new SaslException(String.format("Mismatch in negotiated QOP value: %s and Expected QOP value: %s",
            negotiatedQOP, expectedQOP));
      }

      // Update the rawWrapChunkSize with the negotiated buffer size since we cannot call encode with more than
      // negotiated size of buffer.
      if (connection.isEncryptionEnabled()) {
        final int negotiatedRawSendSize = Integer.parseInt(
            saslClient.getNegotiatedProperty(Sasl.RAW_SEND_SIZE).toString());
        if (negotiatedRawSendSize <= 0) {
          throw new SaslException(String.format("Negotiated rawSendSize: %d is invalid. Please check the configured " +
              "value of encryption.sasl.max_wrapped_size. It might be configured to a very small value.",
              negotiatedRawSendSize));
        }
        connection.setWrapSizeLimit(negotiatedRawSendSize);
      }
    } catch (Exception e) {
      throw new SaslException(String.format("Unexpected failure while retrieving negotiated property values (%s)",
          e.getMessage()), e);
    }

    if (connection.isEncryptionEnabled()) {
      connection.addSecurityHandlers();
    } else {
      // Encryption is not required hence we don't need to hold on to saslClient object.
      connection.disposeSaslClient();
    }
  }
}


text:
package org.apache.nifi.csv;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Supplier;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.serialization.MalformedRecordException;
import org.apache.nifi.serialization.RecordReader;
import org.apache.nifi.serialization.record.DataType;
import org.apache.nifi.serialization.record.MapRecord;
import org.apache.nifi.serialization.record.Record;
import org.apache.nifi.serialization.record.RecordField;
import org.apache.nifi.serialization.record.RecordFieldType;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.util.DataTypeUtils;

public class CSVRecordReader implements RecordReader {
    private final CSVParser csvParser;
    private final RecordSchema schema;

    private final Supplier<DateFormat> LAZY_DATE_FORMAT;
    private final Supplier<DateFormat> LAZY_TIME_FORMAT;
    private final Supplier<DateFormat> LAZY_TIMESTAMP_FORMAT;

    private List<RecordField> recordFields;

    public CSVRecordReader(final InputStream in, final ComponentLog logger, final RecordSchema schema, final CSVFormat csvFormat, final boolean hasHeader, final boolean ignoreHeader,
        final String dateFormat, final String timeFormat, final String timestampFormat, final String encoding) throws IOException {

        this.schema = schema;
        final DateFormat df = dateFormat == null ? null : DataTypeUtils.getDateFormat(dateFormat);
        final DateFormat tf = timeFormat == null ? null : DataTypeUtils.getDateFormat(timeFormat);
        final DateFormat tsf = timestampFormat == null ? null : DataTypeUtils.getDateFormat(timestampFormat);

        LAZY_DATE_FORMAT = () -> df;
        LAZY_TIME_FORMAT = () -> tf;
        LAZY_TIMESTAMP_FORMAT = () -> tsf;

        final Reader reader = new InputStreamReader(new BOMInputStream(in), encoding);

        CSVFormat withHeader;
        if (hasHeader) {
            withHeader = csvFormat.withSkipHeaderRecord();

            if (ignoreHeader) {
                withHeader = withHeader.withHeader(schema.getFieldNames().toArray(new String[0]));
            }
        } else {
            withHeader = csvFormat.withHeader(schema.getFieldNames().toArray(new String[0]));
        }

        csvParser = new CSVParser(reader, withHeader);
    }

    @Override
    public Record nextRecord(final boolean coerceTypes, final boolean dropUnknownFields) throws IOException, MalformedRecordException {
        final RecordSchema schema = getSchema();

        final List<RecordField> recordFields = getRecordFields();
        final int numFieldNames = recordFields.size();

        for (final CSVRecord csvRecord : csvParser) {
            final Map<String, Object> values = new HashMap<>(recordFields.size() * 2);
            for (int i = 0; i < csvRecord.size(); i++) {
                final String rawValue = csvRecord.get(i);

                final String rawFieldName;
                final DataType dataType;
                if (i >= numFieldNames) {
                    if (!dropUnknownFields) {
                        values.put("unknown_field_index_" + i, rawValue);
                    }

                    continue;
                } else {
                    final RecordField recordField = recordFields.get(i);
                    rawFieldName = recordField.getFieldName();
                    dataType = recordField.getDataType();
                }

                final Object value;
                if (coerceTypes) {
                    value = convert(rawValue, dataType, rawFieldName);
                } else {
                    // The CSV Reader is going to return all fields as Strings, because CSV doesn't have any way to
                    // dictate a field type. As a result, we will use the schema that we have to attempt to convert
                    // the value into the desired type if it's a simple type.
                    value = convertSimpleIfPossible(rawValue, dataType, rawFieldName);
                }

                values.put(rawFieldName, value);
            }

            return new MapRecord(schema, values, coerceTypes, dropUnknownFields);
        }

        return null;
    }

    private List<RecordField> getRecordFields() {
        if (this.recordFields != null) {
            return this.recordFields;
        }

        // Use a SortedMap keyed by index of the field so that we can get a List of field names in the correct order
        final SortedMap<Integer, String> sortedMap = new TreeMap<>();
        for (final Map.Entry<String, Integer> entry : csvParser.getHeaderMap().entrySet()) {
            sortedMap.put(entry.getValue(), entry.getKey());
        }

        final List<RecordField> fields = new ArrayList<>();
        final List<String> rawFieldNames = new ArrayList<>(sortedMap.values());
        for (final String rawFieldName : rawFieldNames) {
            final Optional<RecordField> option = schema.getField(rawFieldName);
            if (option.isPresent()) {
                fields.add(option.get());
            } else {
                fields.add(new RecordField(rawFieldName, RecordFieldType.STRING.getDataType()));
            }
        }

        this.recordFields = fields;
        return fields;
    }

    @Override
    public RecordSchema getSchema() {
        return schema;
    }

    protected Object convert(final String value, final DataType dataType, final String fieldName) {
        if (dataType == null || value == null) {
            return value;
        }

        final String trimmed = value.startsWith("\"") && value.endsWith("\"") ? value.substring(1, value.length() - 1) : value;
        if (trimmed.isEmpty()) {
            return null;
        }

        return DataTypeUtils.convertType(trimmed, dataType, LAZY_DATE_FORMAT, LAZY_TIME_FORMAT, LAZY_TIMESTAMP_FORMAT, fieldName);
    }

    private Object convertSimpleIfPossible(final String value, final DataType dataType, final String fieldName) {
        if (dataType == null || value == null) {
            return value;
        }

        final String trimmed = value.startsWith("\"") && value.endsWith("\"") ? value.substring(1, value.length() - 1) : value;
        if (trimmed.isEmpty()) {
            return null;
        }

        switch (dataType.getFieldType()) {
            case STRING:
                return value;
            case BOOLEAN:
            case INT:
            case LONG:
            case FLOAT:
            case DOUBLE:
            case BYTE:
            case CHAR:
            case SHORT:
            case TIME:
            case TIMESTAMP:
            case DATE:
                if (DataTypeUtils.isCompatibleDataType(trimmed, dataType)) {
                    return DataTypeUtils.convertType(trimmed, dataType, LAZY_DATE_FORMAT, LAZY_TIME_FORMAT, LAZY_TIMESTAMP_FORMAT, fieldName);
                } else {
                    return value;
                }
        }

        return value;
    }

    @Override
    public void close() throws IOException {
        csvParser.close();
    }
}


text:
/* jshint node: true */
"use strict";

var restify = require("restify"),
    logger = require("./../util/logger"),
    server = restify.createServer();

server.get("/info", function (req, rep, next) {
    var pkg = require("./../../package.json");

    rep.send({
        name: pkg.name,
        version: pkg.version,
        description: pkg.description
    });

    next();
});

server.listen(8000, function () {
    logger.info("HTTP server started on port 8000...");
});


text:
module Omnitest
  class Psychic
    class TaskNotImplementedError < NotImplementedError
      def initialize(task_alias)
        super("no active task factories can run a task named #{task_alias}")
      end
    end

    class ScriptNotRunnable < NotImplementedError
      def initialize(script)
        super("no active script factories no how to run #{script.source_file}")
      end
    end
  end
end


text:
package com.cloud.model.enumeration;

public enum DiskControllerType {
    IDE,
    VIRTIO,
    SCSI;

    public static DiskControllerType getGuestDiskModel(final String platformEmulator) {
        if (platformEmulator == null || platformEmulator.toLowerCase().contains("Non-VirtIO".toLowerCase())) {
            return DiskControllerType.IDE;
        } else if (platformEmulator.toLowerCase().contains("VirtIO-SCSI".toLowerCase())) {
            return DiskControllerType.SCSI;
        } else {
            return DiskControllerType.VIRTIO;
        }
    }
}


text:
<!DOCTYPE html>

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

	<title> More-Recipes | Home </title>

	<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

	<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

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

  			<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#toggle" aria-controls="toggle" aria-expanded="false" aria-label="Toggle navigation">

  			</button>
  			More-Recipes

				    <form class="form-inline my-2 my-lg-0 ">
				      <input class="form-control mr-sm-2 search" type="text" placeholder="Find a Recipe">
				      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
				    </form>

  					 Login/Signup

Spaghetti Bolognese

Spaghetti Bolognese is a plain spaghetti cooked in combination of minced meat, tomatoes and spices, prepared in a short time and enjoyable.

	    			view Reviews

Ingredients

 6 big Plum Tomatoes

 500g Beef Mince

1 big Onion

1 cooking spoon Vegetable Oil

 2 cloves garlic

3 leaves Bay leaf

1 tbsp dried Thyme

1 tbsp all-purpose Seasoning or mixed Spice

A small finger/chunk Ginger

Handful Scent leaves/Basil/Effirin

Salt and Pepper to taste

Water for cooking

 Directions

Put tomatoes, half of the onion, ginger, and scent leaves into a blender and puree untill smooth.

Place a frying pan on fire and add the oil. Once it is heated, add the garlic and the remaining onions (chopped), then saute till translucent.

Add the minced meat and stir to combine and cook till the brrf browns all over.

Pour the blended tomatoes into the beef and add the remaining ingredients. Pour in a cup of water and cover to cook for at least 25-30 minutes. Add more water if needed.

Once cooked, you will get a thick looking tasty sauce. Check for taste and bring down.

Meanwhile, boil water and cook your spaghetti with a little salt till it is done, then drain.

To mix your bolognese sauce with the spaghetti, scoop some of the sauce into a pot of spaghetti and set on medium heat. Combine well, simmer for a few minutes and bring down.

Adverts here

Quick Links

 Breakfast Recipes

 Lunch Recipes

 Dinner Recipes

 Dessert Recipes

About

Who we are

FAQs

Terms of Service

Privacy Policy

Support

Site Map

Contact Us

Customer Support

Media and Press

More-Recipes

Magazine

Newsletter

Blog

More-Recipes App

Site Map

Site Map

Recipes and Menus

Ingredients

Video

Advertising

Advertise with us

©2017.More-Recipes


text:
#include "./oxfw.h"

static void proc_read_formation(struct snd_info_entry *entry,
				struct snd_info_buffer *buffer)
{
	struct snd_oxfw *oxfw = entry->private_data;
	struct snd_oxfw_stream_formation formation, curr;
	u8 *format;
	char flag;
	int i, err;

	/* Show input. */
	err = snd_oxfw_stream_get_current_formation(oxfw,
						    AVC_GENERAL_PLUG_DIR_IN,
						    &curr);
	if (err < 0)
		return;

	snd_iprintf(buffer, "Input Stream to device:\n");
	snd_iprintf(buffer, "\tRate\tPCM\tMIDI\n");
	for (i = 0; i < SND_OXFW_STREAM_FORMAT_ENTRIES; i++) {
		format = oxfw->rx_stream_formats[i];
		if (format == NULL)
			continue;

		err = snd_oxfw_stream_parse_format(format, &formation);
		if (err < 0)
			continue;

		if (memcmp(&formation, &curr, sizeof(curr)) == 0)
			flag = '*';
		else
			flag = ' ';

		snd_iprintf(buffer, "%c\t%d\t%d\t%d\n", flag,
			    formation.rate, formation.pcm, formation.midi);
	}

	if (!oxfw->has_output)
		return;

	/* Show output. */
	err = snd_oxfw_stream_get_current_formation(oxfw,
						    AVC_GENERAL_PLUG_DIR_OUT,
						    &curr);
	if (err < 0)
		return;

	snd_iprintf(buffer, "Output Stream from device:\n");
	snd_iprintf(buffer, "\tRate\tPCM\tMIDI\n");
	for (i = 0; i < SND_OXFW_STREAM_FORMAT_ENTRIES; i++) {
		format = oxfw->tx_stream_formats[i];
		if (format == NULL)
			continue;

		err = snd_oxfw_stream_parse_format(format, &formation);
		if (err < 0)
			continue;

		if (memcmp(&formation, &curr, sizeof(curr)) == 0)
			flag = '*';
		else
			flag = ' ';

		snd_iprintf(buffer, "%c\t%d\t%d\t%d\n", flag,
			    formation.rate, formation.pcm, formation.midi);
	}
}

static void add_node(struct snd_oxfw *oxfw, struct snd_info_entry *root,
		     const char *name,
		     void (*op)(struct snd_info_entry *e,
				struct snd_info_buffer *b))
{
	struct snd_info_entry *entry;

	entry = snd_info_create_card_entry(oxfw->card, name, root);
	if (entry == NULL)
		return;

	snd_info_set_text_ops(entry, oxfw, op);
	if (snd_info_register(entry) < 0)
		snd_info_free_entry(entry);
}

void snd_oxfw_proc_init(struct snd_oxfw *oxfw)
{
	struct snd_info_entry *root;

	/*
	 * All nodes are automatically removed at snd_card_disconnect(),
	 * by following to link list.
	 */
	root = snd_info_create_card_entry(oxfw->card, "firewire",
					  oxfw->card->proc_root);
	if (root == NULL)
		return;
	root->mode = S_IFDIR | S_IRUGO | S_IXUGO;
	if (snd_info_register(root) < 0) {
		snd_info_free_entry(root);
		return;
	}

	add_node(oxfw, root, "formation", proc_read_formation);
}


text:
'use strict';

var Runnable = require('./runnable');
var Hook = require('./hook');
var State = require('./state');

module.exports = PostmanBDD;

/**
 * The Postman BDD runtime
 */
function PostmanBDD () {
  var state = this.state = new State();

  this.hooks = {
    before: new Hook('before', state),
    after: new Hook('after', state),
    beforeEach: new Hook('beforeEach', state),
    afterEach: new Hook('afterEach', state),
  };

  this.before = PostmanBDD.prototype.before.bind(this);
  this.after = PostmanBDD.prototype.after.bind(this);
  this.beforeEach = PostmanBDD.prototype.beforeEach.bind(this);
  this.afterEach = PostmanBDD.prototype.afterEach.bind(this);
  this.describe = PostmanBDD.prototype.describe.bind(this);
  this.it = PostmanBDD.prototype.it.bind(this);
}

/**
 * Registers a function to be called before any tests for a request.
 *
 * @param {string} [title] - Optinoal title for this hook
 * @param {function} fn - The hook to run
 */
PostmanBDD.prototype.before = function (title, fn) {
  this.hooks.before.push(title, fn);
};

/**
 * Registers a function to be called after all tests for a request.
 *
 * @param {string} [title] - Optinoal title for this hook
 * @param {function} fn - The hook to run
 */
PostmanBDD.prototype.after = function (title, fn) {
  this.hooks.after.push(title, fn);
};

/**
 * Registers a function to be called before each test.
 *
 * @param {string} [title] - Optinoal title for this hook
 * @param {function} fn - The hook to run
 */
PostmanBDD.prototype.beforeEach = function (title, fn) {
  this.hooks.beforeEach.push(title, fn);
};

/**
 * Registers a function to be called after each test.
 *
 * @param {string} [title] - Optinoal title for this hook
 * @param {function} fn - The hook to run
 */
PostmanBDD.prototype.afterEach = function (title, fn) {
  this.hooks.afterEach.push(title, fn);
};

/**
 * Runs a test suite.
 *
 * Any "before" hooks are run first.  Any "after" hooks are run afterward.
 *
 * @param {string} [title] - Optional title for this test suite
 * @param {function} fn - The test suite to run
 * @returns {object} - An object with test names as keys, and boolean results as values
 */
PostmanBDD.prototype.describe = function (title, fn) {
  var runnable = new Runnable('describe', this.state, title, fn);
  this.state.stack.push(runnable);

  this.oneTimeInitialization();

  runnable.run();

  if (this.state.isFinished()) {
    // This is a top-level `describe` block, so run any `after` hooks
    this.hooks.after.run();
  }

  this.state.stack.pop();
  return this.state.results;
};

/**
 * Runs a single test
 *
 * Any "beforeEach" hooks are run first.  Any "afterEach" hooks are run after.
 *
 * @param {string} [title] - Optional title for this test
 * @param {function} fn - The test to run
 * @returns {boolean} - The boolean result of the test
 */
PostmanBDD.prototype.it = function (title, fn) {
  var runnable = new Runnable('it', this.state, title, fn);
  this.state.stack.push(runnable);

  this.oneTimeInitialization();
  this.hooks.beforeEach.run();

  runnable.run();

  this.hooks.afterEach.run();
  this.state.stack.pop();
  return runnable.result;
};

/**
 * Inititializes state and runs `before` hooks before the first Runnable
 * in a new test script.
 */
PostmanBDD.prototype.oneTimeInitialization = function () {
  if (!this.state.isStarted()) {
    // This is the first Runnable, so run the `before` hooks
    this.hooks.before.run();
  }
};


text:
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <pthread.h>

static void *p;

static void
handler (int sig, siginfo_t *info, void *context)
{
  /* Copy to local vars, as the test wants to read them, and si_addr,
     etc. may be preprocessor defines.  */
  int ssi_errno = info->si_errno;
  int ssi_signo = info->si_signo;
  int ssi_code = info->si_code;
  void *ssi_addr = info->si_addr;

  _exit (0); /* set breakpoint here */
}

static void *
segv_thread (void *ptr)
{
  *(int *)ptr = 0;
}

int
main (void)
{
  pthread_t thr;

  /* Set up unwritable memory.  */
  {
    size_t len;
    len = sysconf(_SC_PAGESIZE);
    p = mmap (0, len, PROT_NONE, MAP_ANON|MAP_PRIVATE, -1, 0);
    if (p == MAP_FAILED)
      {
	perror ("mmap");
	return 1;
      }
  }
  /* Set up the signal handler.  */
  {
    struct sigaction action;
    memset (&action, 0, sizeof (action));
    action.sa_sigaction = handler;
    action.sa_flags |= SA_SIGINFO;
    if (sigaction (SIGSEGV, &action, NULL))
      {
	perror ("sigaction");
	return 1;
      }
  }

  /* Create a thread that will trigger SIGSEGV.  */
  pthread_create (&thr, NULL, segv_thread, p);

  pthread_join (thr, NULL);

  return 0;
}


text:
      subroutine setprob
      implicit double precision (a-h,o-z)
      character*12 fname
      common /comrp/ theta
c
c     # Burgers' equation at an angle theta to the grid,
c     #  u_t + cos(theta)*(0.5*u^2)_x + sin(theta)*(0.5*u^2)_y = 0
c
c     # Set theta for angle
c     # Passed to the Riemann solver rp1.f in a common block
c
c
      iunit = 7
      fname = 'setprob.data'
c     # open the unit with new routine from Clawpack 4.4 to skip over
c     # comment lines starting with #:
      call opendatafile(iunit, fname)

      read(7,*) theta

      return
      end


text:
app.controller('loginController', function ($scope, $http, toastr) {
    $scope.login = {
        usuario: '',
        senha: ''
    };

    $scope.fazerLogin = function () {
        $http.post('api/login', $scope.login)
            .success(function (data) {
                console.log(data);
                if (data.logado) {
                    window.location = "home.php"
                } else {
                    toastr.info('Verifique o usuário e a senha', 'Atenção');
                }
            });
    }

})


text:
@interface MOBProjectionEPSG31998 : MOBProjection

@end


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

class Footer extends Component {
    render() {
        return (

                      Application created for Natural Goodness Co-Op Group by Daniel Emery

        );
    }
}

export default Footer;


text:
<?php
include '../../connect.php';
$Edit_id = $_GET['id'];
$edit = mysql_query("select * from asisten where Id_Asisten='$Edit_id'");
while ($row = mysql_fetch_array($edit)) {
    $id = $row['Id_Asisten'];
    $nama = $row['Nama'];
}
?>

<!DOCTYPE html>

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

    <title>Laboratorium Komputer Jurusan Fisika</title>

    <link href="../../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="../../bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">

    <link href="../../dist/css/sb-admin-2.css" rel="stylesheet">

    <link href="../../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

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

                </button>
                Home

 Logout

                                <input type="text" class="form-control" placeholder="Search...">

                                    <button class="btn btn-default" type="button">

                                    </button>

                             Dashboard

                             Asisten

                                    Data Asisten

                                    Input Asisten

                             Jadwal

                                    Data Jadwal

                                    Input Jadwal

                             Praktikkan

                                    Data Praktikkan

                                    Input Praktikkan

                             Praktikum

                                    Data Praktikum

                                    Input Praktikum

                             Nilai

                                    Nilai Tugas Praktikum

                                    Nilai Tugas Rumah

                                    Nilai

Edit Data Asisten

                        <form role="form" name="form_edit" method="post" action="update.php">

                                Id Asisten :
                                <input name="id" class="form-control" value="<?php echo "$id"; ?>" id="disabledInput" type="text" readonly="">

                                Nama Asisten :
                                <input name="nama" class="form-control" value="<?php echo "$nama"; ?>" type="text" required="">

                            <button type="submit" class="btn btn-default">Edit</button>
                            <button type="reset" class="btn btn-default">Reset</button>
                        </form>


text:
html { background: rgba(0, 0, 0, 0.8); }

.banner { overflow: hidden; display: block; position: relative; width: 728px; height: 90px; background: lightgrey; }
.banner .branding { position: absolute; top: 0; right: 0; bottom: 0; z-index: 10; width: 175px; color: #333; font-size: 40px; background: white; }
.banner .branding .logo { position: absolute; bottom: 21px; right: 2px; -webkit-transform: scale(0.9); transform: scale(0.9); }
.banner .image1, .banner .image2, .banner .image3 { position: absolute; right: 175px; z-index: 3; height: 90px; }
.banner .image1 { bottom: 0; }
.banner .image2 { z-index: 4; opacity: 0; }
.banner .image3 { z-index: 5; height: 146px; opacity: 0; top: -28px; }
.banner .overlay { position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 6; width: 304px; background: #e36d57; }
.banner .overlay > .text1, .banner .overlay > .text2, .banner .overlay > .text3 { position: absolute; top: -28px; left: 0; -webkit-transform: scale(0.5); transform: scale(0.5); }
.banner .overlay > .text2 { top: -3px; top: -83px; left: -1px; -webkit-transform: scale(0.6); transform: scale(0.6); }
.banner .overlay > .text3 { top: -16px; left: -252px; -webkit-transform: scale(0.6); transform: scale(0.6); }
.banner .sub-overlay { position: absolute; top: 0; right: 475px; bottom: 0; left: 0; z-index: 5; background: #e36d57; }
.banner .button { position: absolute; top: 100px; right: 356px; bottom: 0; width: 84px; z-index: 6; }

/*# sourceMappingURL=banner.css.map */


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>JS | Clase 5</title>
    <link rel="stylesheet" href="styles.css">

 Curso JS-Desde-0 | Clase 5

        <form>
          <input id="keylogger" type="password" name="password" placeholder="contraseña">
        </form>


text:
from chainer.dataset.convert import concat_examples  # NOQA
from chainer.dataset.convert import ConcatWithAsyncTransfer  # NOQA
from chainer.dataset.convert import converter  # NOQA
from chainer.dataset.convert import to_device  # NOQA
from chainer.dataset.dataset_mixin import DatasetMixin  # NOQA
from chainer.dataset.download import cache_or_load_file  # NOQA
from chainer.dataset.download import cached_download  # NOQA
from chainer.dataset.download import get_dataset_directory  # NOQA
from chainer.dataset.download import get_dataset_root  # NOQA
from chainer.dataset.download import set_dataset_root  # NOQA
from chainer.dataset.iterator import Iterator  # NOQA
from chainer.dataset.tabular.tabular_dataset import TabularDataset  # NOQA


text:
const {SafeString, escapeExpression} = require('../../../../services/handlebars');

module.exports = function amp_style(options) { // eslint-disable-line camelcase
    if (options.data.site.accent_color) {
        const accentColor = escapeExpression(options.data.site.accent_color);
        return new SafeString(`:root {--ghost-accent-color: ${accentColor};}`);
    }
};


text:
using System;
using System.Collections.Generic;
using Oxide.Core.Plugins;

namespace Oxide.Core.Libraries
{
    /// <summary>
    /// The timer library
    /// </summary>
    public class Timer : Library
    {
        public override bool IsGlobal => false;

        public static int Count { get; private set; }

        internal static readonly object Lock = new object();

        internal static readonly OxideMod Oxide = Interface.Oxide;

        public class TimeSlot
        {
            public int Count;
            public TimerInstance FirstInstance;
            public TimerInstance LastInstance;

            public void GetExpired(double now, Queue<TimerInstance> queue)
            {
                var instance = FirstInstance;
                while (instance != null)
                {
                    if (instance.ExpiresAt > now) break;
                    queue.Enqueue(instance);
                    instance = instance.NextInstance;
                }
            }

            public void InsertTimer(TimerInstance timer)
            {
                var expires_at = timer.ExpiresAt;

                var first_instance = FirstInstance;
                var last_instance = LastInstance;

                var next_instance = first_instance;
                if (first_instance != null)
                {
                    var first_at = first_instance.ExpiresAt;
                    var last_at = last_instance.ExpiresAt;
                    if (expires_at <= first_at)
                    {
                        next_instance = first_instance;
                    }
                    else if (expires_at >= last_at)
                    {
                        next_instance = null;
                    }
                    else if (last_at - expires_at < expires_at - first_at)
                    {
                        next_instance = last_instance;
                        var instance = next_instance;
                        while (instance != null)
                        {
                            if (instance.ExpiresAt <= expires_at)
                            {
                                // We need to insert after this instance
                                break;
                            }
                            next_instance = instance;
                            instance = instance.PreviousInstance;
                        }
                    }
                    else
                    {
                        while (next_instance != null)
                        {
                            if (next_instance.ExpiresAt > expires_at) break;
                            next_instance = next_instance.NextInstance;
                        }
                    }
                }

                if (next_instance == null)
                {
                    timer.NextInstance = null;
                    if (last_instance == null)
                    {
                        FirstInstance = timer;
                        LastInstance = timer;
                    }
                    else
                    {
                        last_instance.NextInstance = timer;
                        timer.PreviousInstance = last_instance;
                        LastInstance = timer;
                    }
                }
                else
                {
                    var previous = next_instance.PreviousInstance;
                    if (previous == null)
                    {
                        FirstInstance = timer;
                    }
                    else
                    {
                        previous.NextInstance = timer;
                    }
                    next_instance.PreviousInstance = timer;
                    timer.PreviousInstance = previous;
                    timer.NextInstance = next_instance;
                }

                timer.Added(this);
            }
        }

        /// <summary>
        /// Represents a single timer instance
        /// </summary>
        public class TimerInstance
        {
            public const int MaxPooled = 5000;

            internal static Queue<TimerInstance> Pool = new Queue<TimerInstance>();

            /// <summary>
            /// Gets the number of repetitions left on this timer
            /// </summary>
            public int Repetitions { get; private set; }

            /// <summary>
            /// Gets the delay between each repetition
            /// </summary>
            public float Delay { get; private set; }

            /// <summary>
            /// Gets the callback delegate
            /// </summary>
            public Action Callback { get; private set; }

            /// <summary>
            /// Gets if this timer has been destroyed
            /// </summary>
            public bool Destroyed { get; private set; }

            /// <summary>
            /// Gets the plugin to which this timer belongs, if any
            /// </summary>
            public Plugin Owner { get; private set; }

            internal float ExpiresAt;

            internal TimeSlot TimeSlot;
            internal TimerInstance NextInstance;
            internal TimerInstance PreviousInstance;

            private Event.Callback<Plugin, PluginManager> removedFromManager;

            private Timer timer;

            internal TimerInstance(Timer timer, int repetitions, float delay, Action callback, Plugin owner)
            {
                Load(timer, repetitions, delay, callback, owner);
            }

            internal void Load(Timer timer, int repetitions, float delay, Action callback, Plugin owner)
            {
                this.timer = timer;
                Repetitions = repetitions;
                Delay = delay;
                Callback = callback;
                ExpiresAt = Oxide.Now + delay;
                Owner = owner;
                Destroyed = false;
                if (owner != null) removedFromManager = owner.OnRemovedFromManager.Add(OnRemovedFromManager);
            }

            /// <summary>
            /// Resets the timer optionally changing the delay setting a number of repetitions
            /// </summary>
            /// <param name="delay">The new delay between repetitions</param>
            /// <param name="repetitions">Number of repetitions before being destroyed</param>
            public void Reset(float delay = -1, int repetitions = 1)
            {
                lock (Lock)
                {
                    if (delay < 0)
                        delay = Delay;
                    else
                        Delay = delay;
                    Repetitions = repetitions;
                    ExpiresAt = Oxide.Now + delay;
                    if (Destroyed)
                    {
                        Destroyed = false;
                        var owner = Owner;
                        if (owner != null) removedFromManager = owner.OnRemovedFromManager.Add(OnRemovedFromManager);
                    }
                    else
                    {
                        Remove();
                    }
                    timer.InsertTimer(this);
                }
            }

            /// <summary>
            /// Destroys this timer
            /// </summary>
            public bool Destroy()
            {
                lock (Lock)
                {
                    if (Destroyed) return false;
                    Destroyed = true;
                    Remove();
                    Event.Remove(ref removedFromManager);
                }
                return true;
            }

            /// <summary>
            /// Destroys this timer and adds it to the pool
            /// </summary>
            public bool DestroyToPool()
            {
                lock (Lock)
                {
                    if (Destroyed) return false;
                    Destroyed = true;
                    Callback = null;
                    Remove();
                    Event.Remove(ref removedFromManager);
                    var pooled_instances = Pool;
                    if (pooled_instances.Count < MaxPooled) pooled_instances.Enqueue(this);
                }
                return true;
            }

            internal void Added(TimeSlot time_slot)
            {
                time_slot.Count++;
                Count++;
                TimeSlot = time_slot;
            }

            internal void Invoke(float now)
            {
                if (Repetitions > 0)
                {
                    if (--Repetitions == 0)
                    {
                        Destroy();
                        FireCallback();
                        return;
                    }
                }

                Remove();

                var expires_at = ExpiresAt + Delay;
                ExpiresAt = expires_at;
                timer.InsertTimer(this, expires_at < now);

                FireCallback();
            }

            internal void Remove()
            {
                var slot = TimeSlot;
                if (slot == null) return;

                slot.Count--;
                Count--;

                var previous = PreviousInstance;
                var next = NextInstance;

                if (next == null)
                {
                    slot.LastInstance = previous;
                }
                else
                {
                    next.PreviousInstance = previous;
                }

                if (previous == null)
                {
                    slot.FirstInstance = next;
                }
                else
                {
                    previous.NextInstance = next;
                }

                TimeSlot = null;
                PreviousInstance = null;
                NextInstance = null;
            }

            private void FireCallback()
            {
                Owner?.TrackStart();
                try
                {
                    Callback();
                }
                catch (Exception ex)
                {
                    Destroy();
                    var error_message = $"Failed to run a {Delay:0.00} timer";
                    if (Owner && Owner != null) error_message += $" in '{Owner.Name} v{Owner.Version}'";
                    Interface.Oxide.LogException(error_message, ex);
                    return;
                }
                finally
                {
                    Owner?.TrackEnd();
                }
            }

            private void OnRemovedFromManager(Plugin sender, PluginManager manager) => Destroy();
        }

        // An even number of time slots is required. More slots means more efficient inserts with a higher number of timers but also more per-frame overhead.
        public const int TimeSlots = 512;
        public const int LastTimeSlot = TimeSlots - 1;
        public const float TickDuration = .01f;

        private readonly TimeSlot[] timeSlots = new TimeSlot[TimeSlots];
        private readonly Queue<TimerInstance> expiredInstanceQueue = new Queue<TimerInstance>();

        private int currentSlot;

        // This needs to be a double in order to avoid precision errors
        private double nextSlotAt = TickDuration;

        public Timer()
        {
            for (var i = 0; i < TimeSlots; i++)
                timeSlots[i] = new TimeSlot();
        }

        /// <summary>
        /// Called every server frame to process expired timers
        /// </summary>
        public void Update(float delta)
        {
            var now = Oxide.Now;
            var time_slots = timeSlots;
            var expired_queue = expiredInstanceQueue;
            var checked_slots = 0;

            lock (Lock)
            {
                var current_slot = currentSlot;
                var next_slot_at = nextSlotAt;

                while (true)
                {
                    time_slots[current_slot].GetExpired(next_slot_at > now ? now : next_slot_at, expired_queue);

                    // Only move to the next slot once real time is out of the current slot so that the current slot is rechecked each frame
                    if (now <= next_slot_at) break;

                    checked_slots++;
                    current_slot = current_slot < LastTimeSlot ? current_slot + 1 : 0;
                    next_slot_at += TickDuration;
                }

                if (checked_slots > 0)
                {
                    currentSlot = current_slot;
                    nextSlotAt = next_slot_at;
                }

                var expired_count = expired_queue.Count;
                for (var i = 0; i < expired_count; i++)
                {
                    var instance = expired_queue.Dequeue();
                    if (!instance.Destroyed) instance.Invoke(now);
                }
            }
        }

        internal TimerInstance AddTimer(int repetitions, float delay, Action callback, Plugin owner = null)
        {
            lock (Lock)
            {
                TimerInstance timer;
                var pooled_instances = TimerInstance.Pool;
                if (pooled_instances.Count > 0)
                {
                    timer = pooled_instances.Dequeue();
                    timer.Load(this, repetitions, delay, callback, owner);
                }
                else
                {
                    timer = new TimerInstance(this, repetitions, delay, callback, owner);
                }
                InsertTimer(timer, timer.ExpiresAt < Oxide.Now);
                return timer;
            }
        }

        private void InsertTimer(TimerInstance timer, bool in_past = false)
        {
            var index = in_past ? currentSlot : (int)(timer.ExpiresAt / TickDuration) & LastTimeSlot;
            timeSlots[index].InsertTimer(timer);
        }

        /// <summary>
        /// Creates a timer that fires once
        /// </summary>
        /// <param name="delay"></param>
        /// <param name="callback"></param>
        /// <param name="owner"></param>
        /// <returns></returns>
        [LibraryFunction("Once")]
        public TimerInstance Once(float delay, Action callback, Plugin owner = null) => AddTimer(1, delay, callback, owner);

        /// <summary>
        /// Creates a timer that fires many times
        /// </summary>
        /// <param name="delay"></param>
        /// <param name="reps"></param>
        /// <param name="callback"></param>
        /// <param name="owner"></param>
        /// <returns></returns>
        [LibraryFunction("Repeat")]
        public TimerInstance Repeat(float delay, int reps, Action callback, Plugin owner = null) => AddTimer(reps, delay, callback, owner);

        /// <summary>
        /// Creates a timer that fires once next frame
        /// </summary>
        /// <param name="callback"></param>
        /// <returns></returns>
        [LibraryFunction("NextFrame")]
        public TimerInstance NextFrame(Action callback) => AddTimer(1, 0.0f, callback);
    }
}


text:
namespace Serenity.Web
{
    public interface INamedDynamicScript : IDynamicScript, IScriptName
    {
    }
}


text:
package org.codesharp.traffic.netty;

import io.netty.buffer.ByteBufAllocator;

import org.codesharp.traffic.drpc.DRPCTrafficTest;

public class TrafficTest extends DRPCTrafficTest {
	public TrafficTest() {
		n1_flag = 1L;
		n2_flag = 2L;
		n3_flag = 3L;
		n4_flag = 4L;
		n2_n1_id = 201L;
		n2_n3_id = 203L;
		n2_n4_id = 204L;
		n3_n4_id = 304L;
	}

	@Override
	protected DRPCMessageHandleImpl newHandle() {
		return new DRPCMessageHandleImpl(ByteBufAllocator.DEFAULT);
	}

	@Override
	protected Object newMessage(Object dst) {
		return String.format("{%s:'%s',%s:1,%s:%s}",
				DRPCMessageHandleImpl.TYPE,
				DRPCMessageHandleImpl.REQ,
				DRPCMessageHandleImpl.ID,
				DRPCMessageHandleImpl.TO,
				dst);
	}

	@Override
	protected Object newAck(Object msg) {
		return String.format("{%s:'%s',%s:1}",
				DRPCMessageHandleImpl.TYPE,
				DRPCMessageHandleImpl.REP,
				DRPCMessageHandleImpl.ID);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coryneum berkeleyi Cooke

### Remarks
null


text:
import Vue from 'vue';
import { Component, Emit, Prop } from 'vue-property-decorator';
import { time } from '../../../vue/filters/time';
import { AppTrackEvent } from '../../analytics/track-event.directive';
import { GameSong } from '../../game/song/song.model';
import { AppAudioPlayer } from '../player/player';
import AppAudioScrubber from '../scrubber/scrubber.vue'

@Component({
	components: {
		AppAudioPlayer,
		AppAudioScrubber,
	},
	directives: {
		AppTrackEvent,
	},
	filters: {
		time,
	},
})
export default class AppAudioPlaylist extends Vue {
	@Prop(Array)
	songs!: GameSong[];

	currentSong: GameSong | null = null;
	duration = 0;
	currentTime = 0;
	pausedSong: GameSong | null = null;
	pausedSongTime = 0;

	$refs!: {
		player: AppAudioPlayer;
	};

	/**
	 * When we pause the song, we actually unload the song from the DOM. We
	 * instead store it into the paused song so that we can replay it from where
	 * it left off. Because of this, we want to use the paused song title if it
	 * exists.
	 */
	get songTitle() {
		const song = this.currentSong || this.pausedSong;
		return song ? song.title : this.songs[0].title;
	}

	@Emit('play')
	private async playSong(song: GameSong) {
		this.currentSong = song;

		// If this song was previously paused, and now they're starting it
		// again, seek to the time they were at.
		await this.$nextTick();
		if (this.currentSong === this.pausedSong) {
			this.$refs.player.seek(this.pausedSongTime);
		}

		this.pausedSong = null;
		this.pausedSongTime = 0;
	}

	@Emit('stop')
	private async pauseSong() {
		this.pausedSongTime = this.currentTime;
		this.pausedSong = this.currentSong;
		this.currentSong = null;
		await this.$nextTick();
	}

	private async resetSong() {
		this.currentSong = null;
		await this.$nextTick();
		await this.playSong(this.songs[0]);
	}

	private async nextSong() {
		if (!this.currentSong) {
			return;
		}

		// If last song, wrap.
		if (this.currentSong.id === this.songs[this.songs.length - 1].id) {
			await this.resetSong();
		} else {
			const currentIndex = this.songs.findIndex(item => item.id === this.currentSong!.id);
			if (currentIndex !== -1) {
				await this.playSong(this.songs[currentIndex + 1]);
			}
		}
	}

	durationEvent(event: { duration: number; currentTime: number }) {
		this.duration = event.duration;
		this.currentTime = event.currentTime;
	}

	mainSongButton() {
		if (!this.currentSong) {
			if (this.pausedSong) {
				this.playSong(this.pausedSong);
			} else {
				this.playSong(this.songs[0]);
			}
		} else {
			this.pauseSong();
		}
	}

	toggleSong(song: GameSong) {
		if (this.currentSong && this.currentSong.id === song.id) {
			this.pauseSong();
		} else {
			this.playSong(song);
		}
	}

	async seek(pos: number) {
		const seekTime = this.duration * pos;
		let player = this.$refs.player;

		if (!player) {
			this.mainSongButton();
			await this.$nextTick();
			player = this.$refs.player;
		}

		player.seek(seekTime);
	}

	onSongEnded() {
		this.nextSong();
	}
}


text:
<?php
declare(strict_types=1);

namespace AOC\Tests\Day21\Part2;

use AOC\Day21\Part2\Main;
use AOC\Day21\Part1\Main as MainP1;

class MainTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Main
     */
    private $main;
    /**
     * @var MainP1
     */
    private $mainp1;

    public function setUp()
    {
        $this->mainp1 = new MainP1();
        $this->main = new Main();
    }

    public function test_run()
    {
        $operations = "swap position 4 with position 0\nswap letter d with letter b\nreverse positions 0 through 4\nrotate left 1 step\nmove position 1 to position 4\nmove position 3 to position 0\nrotate based on position of letter b\nrotate based on position of letter d\n";
        $input = 'abcdefgh';

        $scrambled = $this->mainp1->run($input, $operations);
        $unscrambled = $this->main->run($scrambled, $operations);

        $this->assertEquals($input, $unscrambled);
    }
}