text:
package org.wso2.andes.kernel.slot;

import com.google.common.util.concurrent.SettableFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.andes.kernel.AndesContext;
import org.wso2.andes.kernel.AndesException;
import org.wso2.andes.kernel.AndesMessageMetadata;
import org.wso2.andes.kernel.LocalSubscription;
import org.wso2.andes.kernel.MessageFlusher;
import org.wso2.andes.kernel.MessagingEngine;
import org.wso2.andes.kernel.OnflightMessageTracker;
import org.wso2.andes.store.FailureObservingStoreManager;
import org.wso2.andes.store.HealthAwareStore;
import org.wso2.andes.store.StoreHealthListener;
import org.wso2.andes.subscription.SubscriptionStore;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutionException;

/**
 * SlotDelivery worker is responsible of distributing messages to subscribers. Messages will be
 * taken from a slot.
 */
public class SlotDeliveryWorker extends Thread implements StoreHealthListener{

    /**
     * keeps storage queue name vs actual destination it represent
     */
    private ConcurrentSkipListMap<String, String> storageQueueNameToDestinationMap;

    private SubscriptionStore subscriptionStore;
    private static Log log = LogFactory.getLog(SlotDeliveryWorker.class);

    /**
     * This map contains slotId to slot hash map against queue name
     */
    private volatile boolean running;
    private MessageFlusher messageFlusher;
    private SlotCoordinator slotCoordinator;

    /**
     * Indicates and provides a barrier if messages stores become offline.
     * marked as volatile since this value could be set from a different thread
     * (other than those of Disruptor)
     */
    private volatile SettableFuture<Boolean> messageStoresUnavailable;

    /**
     * Maximum number to retries retrieve metadata list for a given storage
     * queue ( in the errors occur in message stores)
     */
    private static final int MAX_META_DATA_RETRIEVAL_COUNT = 5;

    public SlotDeliveryWorker() {
        messageFlusher = MessageFlusher.getInstance();
        this.storageQueueNameToDestinationMap = new ConcurrentSkipListMap<>();
        this.subscriptionStore = AndesContext.getInstance().getSubscriptionStore();
        slotCoordinator = MessagingEngine.getInstance().getSlotCoordinator();
        messageStoresUnavailable = null;
        FailureObservingStoreManager.registerStoreHealthListener(this);
    }

    @Override
    public void run() {
        /**
         * This while loop is necessary since whenever there are messages this thread should
         * deliver them
         */
        running = true;
        while (running) {

            //Iterate through all the queues registered in this thread
            int idleQueueCounter = 0;

            for (String storageQueueName : storageQueueNameToDestinationMap.keySet()) {
                String destinationOfMessagesInQueue = storageQueueNameToDestinationMap.get(storageQueueName);
                Collection<LocalSubscription> subscriptions4Queue;
                try {
                    subscriptions4Queue =
                            subscriptionStore.getActiveLocalSubscribersForQueuesAndTopics(destinationOfMessagesInQueue);
                    if (subscriptions4Queue != null && !subscriptions4Queue.isEmpty()) {
                        //Check in memory buffer in MessageFlusher has room
                        if (messageFlusher.getMessageDeliveryInfo(destinationOfMessagesInQueue)
                                .isMessageBufferFull()) {

                            //get a slot from coordinator.
                            Slot currentSlot = requestSlot(storageQueueName);
                            currentSlot.setDestinationOfMessagesInSlot(destinationOfMessagesInQueue);

                            /**
                             * If the slot is empty
                             */
                            if (0 == currentSlot.getEndMessageId()) {

                                    /*
                                    If the message buffer in MessageFlusher is not empty
                                     send those messages
                                     */
                                if (log.isDebugEnabled()) {
                                    log.debug("Received an empty slot from slot manager");
                                }
                                boolean sentFromMessageBuffer = sendFromMessageBuffer(
                                        destinationOfMessagesInQueue);
                                if (!sentFromMessageBuffer) {
                                    //No available free slots
                                    idleQueueCounter++;
                                    if (idleQueueCounter == storageQueueNameToDestinationMap.size()) {
                                        try {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Sleeping Slot Delivery Worker");
                                            }
                                            Thread.sleep(100);
                                        } catch (InterruptedException ignored) {
                                            //Silently ignore
                                        }
                                    }
                                }
                            } else {
                                if (log.isDebugEnabled()) {
                                    log.debug("Received slot for queue " + storageQueueName + " " +
                                            "is: " + currentSlot.getStartMessageId() +
                                            " - " + currentSlot.getEndMessageId() +
                                            "Thread Id:" + Thread.currentThread().getId());
                                }
                                List<AndesMessageMetadata> messagesRead =
                                                                          getMetaDataListBySlot(storageQueueName,
                                                                                currentSlot);

                                if (messagesRead != null &&
                                        !messagesRead.isEmpty()) {
                                    if (log.isDebugEnabled()) {
                                        log.debug("Number of messages read from slot " +
                                                currentSlot.getStartMessageId() + " - " +
                                                currentSlot.getEndMessageId() + " is " +
                                                messagesRead.size() + " queue= " + storageQueueName);
                                    }
                                    MessageFlusher.getInstance().sendMessageToBuffer(
                                            messagesRead, currentSlot);
                                    MessageFlusher.getInstance().sendMessagesInBuffer(
                                            currentSlot.getDestinationOfMessagesInSlot());
                                } else {
                                    currentSlot.setSlotInActive();
                                    deleteSlot(currentSlot);
                                }
                            }

                        } else {
                                /*If there are messages to be sent in the message
                                            buffer in MessageFlusher send them */
                            if (log.isDebugEnabled()) {
                                log.debug(
                                        "The queue " + storageQueueName + " has no room. Thus sending " +
                                                "from buffer.");
                            }
                            sendFromMessageBuffer(destinationOfMessagesInQueue);
                        }
                    } else {
                        idleQueueCounter++;
                        if (idleQueueCounter == storageQueueNameToDestinationMap.size()) {
                            try {
                                if (log.isDebugEnabled()) {
                                    log.debug("Sleeping Slot Delivery Worker");
                                }
                                Thread.sleep(100);
                            } catch (InterruptedException ignored) {
                                //Silently ignore
                            }
                        }
                    }
                } catch (AndesException e) {
                    log.error("Error running Message Store Reader " + e.getMessage(), e);
                } catch (ConnectionException e) {
                    log.error("Error occurred while connecting to the thrift coordinator " +
                            e.getMessage(), e);
                    setRunning(false);
                    //Any exception should be caught here. Otherwise SDW thread will stop
                    //and MB node will become useless
                } catch (Exception e) {
                    log.error("Error while running Slot Delivery Worker. ", e);
                }
            }
        }

    }

    /**
     * Returns a list of {@link AndesMessageMetadata} in specified slot
     * @param storageQueueName name of the storage queue which this slot belongs to
     * @param slot the slot which messages are retrieved.
     * @return a list of {@link AndesMessageMetadata}
     * @throws AndesException an exception if there are errors at message store level.
     */
    private List<AndesMessageMetadata> getMetaDataListBySlot(String storageQueueName,
                                                             Slot slot) throws AndesException {
        return getMetadataListBySlot(storageQueueName, slot, 0);
    }

    /**
     * Returns a list of {@link AndesMessageMetadata} in specified slot. This method is recursive.
     * @param storageQueueName storage queue of the slot
     * @param slot Retrieve metadata relevant to the given {@link org.wso2.andes.kernel.slot.Slot}
     * @param numberOfRetriesBefore retry count for the query
     * @return return a list of {@link org.wso2.andes.kernel.AndesMessageMetadata}
     * @throws AndesException
     */
    private List<AndesMessageMetadata> getMetadataListBySlot(String storageQueueName,
                                                             Slot slot,
                                                             int numberOfRetriesBefore) throws AndesException {

        List<AndesMessageMetadata> messagesRead;

        if ( messageStoresUnavailable != null){
            try {

                log.info("Message store has become unavailable therefore "+
                          "waiting until store becomes available. thread id: " + this.getId());
                messageStoresUnavailable.get();
                messageStoresUnavailable = null; // we are passing the blockade (therefore clear it).
                log.info("Message store became available. resuming work. thread id: " + this.getId());

            } catch (InterruptedException e) {
                throw new AndesException("Thread interrupted while waiting for message stores to come online", e);
            } catch (ExecutionException e){
                throw new AndesException("Error occurred while waiting for message stores to come online", e);
            }
        }

        try{

            long firstMsgId = slot.getStartMessageId();
            long lastMsgId = slot.getEndMessageId();
            //Read messages in the slot
            messagesRead =
                    MessagingEngine.getInstance().getMetaDataList(
                            storageQueueName, firstMsgId, lastMsgId);

            if (log.isDebugEnabled()) {
                StringBuilder messageIDString = new StringBuilder();
                for (AndesMessageMetadata metadata : messagesRead) {
                    messageIDString.append(metadata.getMessageID()).append(" , ");
                }
                log.debug("Messages Read: " + messageIDString);
            }

        }catch (AndesException aex){

            if (numberOfRetriesBefore <= MAX_META_DATA_RETRIEVAL_COUNT) {
                String errorMsg =
                                  String.format("error occurred retrieving metadata list for slot :"
                                                + " %s, retry count = %d",
                                                slot.toString(), numberOfRetriesBefore);
                log.error(errorMsg, aex);
                messagesRead = getMetadataListBySlot(storageQueueName, slot, numberOfRetriesBefore + 1);
            } else {
                String errorMsg =
                         String.format("error occurred retrieving metadata list for slot : %s, in final attempt = %d. "
                                       + "this slot will not be delivered and become stale in message store",
                                       slot.toString(), numberOfRetriesBefore);
                throw new AndesException(errorMsg, aex);
            }

        }

        return messagesRead;

    }

    /**
     * Get a slot from the Slot to deliver ( from the coordinator if the MB is clustered)
     * @param storageQueueName the storage queue name for from which a slot should be returned.
     * @return a {@link Slot}
     * @throws ConnectionException if connectivity to coordinator is lost.
     */
    private Slot requestSlot(String storageQueueName) throws ConnectionException {
        long startTime = System.currentTimeMillis();
        Slot currentSlot = slotCoordinator.getSlot(storageQueueName);
        long endTime = System.currentTimeMillis();

        if (log.isDebugEnabled()) {
            log.debug(
                    (endTime - startTime) + " milliSec took to get a slot" +
                            " from slot manager");
        }
        return currentSlot;
    }

    /**
     * Send messages from buffer in MessageFlusher if the buffer is not empty
     *
     * @param msgDestination queue/topic message is addressed to
     * @return whether the messages are sent from message buffer or not
     * @throws AndesException
     */
    private boolean sendFromMessageBuffer(String msgDestination) throws AndesException {
        boolean sentFromMessageBuffer = false;
        if (!messageFlusher.isMessageBufferEmpty(msgDestination)) {
            messageFlusher.sendMessagesInBuffer(msgDestination);
            sentFromMessageBuffer = true;
        }
        return sentFromMessageBuffer;
    }

    /**
     * Add a queue to queue list of this SlotDeliveryWorkerThread
     *
     * @param storageQueueName queue name of the newly added queue
     */
    public void addQueueToThread(String storageQueueName, String destination) {
        getStorageQueueNameToDestinationMap().put(storageQueueName, destination);
    }

    /**
     * Get queue list belongs to this thread
     *
     * @return queue list
     */
    public ConcurrentSkipListMap<String, String> getStorageQueueNameToDestinationMap() {
        return storageQueueNameToDestinationMap;
    }

    /**
     * @return Whether the worker thread is in running state or not
     */
    public boolean isRunning() {
        return running;
    }

    /**
     * Set state of the worker thread
     *
     * @param running new state of the worker
     */
    public void setRunning(boolean running) {
        this.running = running;
    }

    /**
     * Submit slot to execute delete
     *
     * @param slot slot to delete
     */
    public void deleteSlot(Slot slot) {
        SlotDeletionExecutor.getInstance().executeSlotDeletion(slot);
        OnflightMessageTracker.getInstance().releaseAllMessagesOfSlotFromTracking(slot);
    }

    /**
     * {@inheritDoc}
     * <p> Creates a {@link SettableFuture} indicating message store became offline.
     */
    @Override
    public void storeNonOperational(HealthAwareStore store, Exception ex) {

        log.info("Message stores became not operational therefore waiting");
        messageStoresUnavailable = SettableFuture.create();

    }

    /**
     * {@inheritDoc}
     * <p> Sets a value for {@link SettableFuture} indicating message store became online.
     */
    @Override
    public void storeOperational(HealthAwareStore store) {
        log.info("Message stores became operational therefore resuming work");
        messageStoresUnavailable.set(false);

    }
}


text:
<?php

$prefix="";
$page_menu = 'home';
include($prefix."static/connect_database.php");
$home_flag=1;

$get_list =mysql_query("
	SELECT * from tbl_home
	ORDER BY order_

",$con);

if (mysql_num_rows($get_list)!=null){

	$filename = array();
	$link = array();
	for ($counter=1;$counter<=mysql_num_rows($get_list);$counter++){
		$get_list_array=mysql_fetch_array($get_list);
		array_push($filename,$get_list_array["filename"]);
		array_push($link,$get_list_array["link"]);

	}

}

?>

<!DOCTYPE html>

    	<?php $page_title="";
			include($prefix."static/page_head.php");
		;?>

        <link rel="stylesheet" href="<?php echo $prefix;?>css/normalize.css">
        <link rel="stylesheet" href="<?php echo $prefix;?>css/main.css">

		<?php
		$link_ = current($link);
		$i=0;
		foreach ($filename as $filename_){
			echo '
'.$filename_.'
';
			echo '
'.$link_.'
';
			$i++;
			$link_ = next($link);
		}
		echo '
'.$i.'
';
		?>

Island Creamery

PREMIUM HOME MADE ICE CREAM IN THE MOST UNIQUE FLAVORS!

        <?php include('static/nav.php') ?>

                        Follow @IslandIndo

on Twitter

Facebook

redpajama_set_name: RedPajamaGithub


text:
package de.dala.simplenews.recycler;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import java.util.List;

import de.dala.simplenews.R;
import de.dala.simplenews.common.Feed;
import de.dala.simplenews.utilities.ColorManager;
import de.dala.simplenews.utilities.PrefUtilities;
import de.dala.simplenews.utilities.Utilities;

public class OpmlRecyclerAdapter extends ChoiceModeRecyclerAdapter<OpmlRecyclerAdapter.OpmlViewHolder, Feed> {

    private final Context mContext;

    public OpmlRecyclerAdapter(Context context, List<Feed> feeds, ChoiceModeListener listener) {
        super(feeds, listener);
        mContext = context;
    }

    @Override
    void onBindSelectedViewHolder(OpmlViewHolder holder, int position) {
        onBindNormalViewHolder(holder, position);
        holder.itemView.setBackgroundColor(ColorManager.moreAlpha(PrefUtilities.getInstance().getCurrentColor(), 70));
    }

    @Override
    void onBindNormalViewHolder(final OpmlViewHolder holder, int position) {
        final Feed feed = get(position);
        holder.name.setText(feed.getTitle() == null ? mContext.getString(R.string.feed_title_not_found) : feed.getTitle());
        holder.link.setText(feed.getXmlUrl());
        holder.checkBox.setChecked(isItemChecked(position));
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle(feed);
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                holder.checkBox.toggle();
                toggle(feed);
                return false;
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                holder.checkBox.toggle();
                toggle(feed);
            }
        });
        int pad = mContext.getResources().getDimensionPixelSize(R.dimen.card_layout_padding);
        holder.itemView.setPadding(pad, pad, pad, pad);
        Utilities.setPressedColorRippleDrawable(ContextCompat.getColor(mContext, R.color.list_background), PrefUtilities.getInstance().getCurrentColor(), holder.itemView);
    }

    @Override
    public OpmlViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.opml_list_item, parent, false);
        return new OpmlViewHolder(itemView);
    }

    class OpmlViewHolder extends RecyclerView.ViewHolder {
        final TextView name;
        final TextView link;
        final CheckBox checkBox;

        OpmlViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.title);
            link = (TextView) itemView.findViewById(R.id.url);
            checkBox = (CheckBox) itemView.findViewById(R.id.checkbox);
        }
    }

}


text:
export default {
  calendar: {
    fromDate: new Date(new Date().setDate(new Date().getDate() - 1)),
    toDate: new Date(new Date().setDate(new Date().getDate() + 7))
  }
};


text:
package com.base2.example.war.rest;

import com.base2.kagura.rest.AuthRest;
import com.base2.kagura.rest.exceptions.AuthenticationException;
import com.base2.kagura.rest.model.AuthenticationResult;
import com.base2.kagura.rest.model.ReportDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import java.io.Serializable;
import java.util.*;

/**
 * @author aubels
 *         Date: 26/08/13
 */
@Path("/auth")
@RequestScoped
public class AuthRestImpl extends AuthRest implements Serializable
{
    private static final Logger LOG = LoggerFactory.getLogger(AuthRestImpl.class);

    @Inject
    KaguraBean kaguraBean;

    @Override
    public AuthenticationResult getAuthToken(String user, String password)
    {
        try {
            kaguraBean.authenticateUser(user,password);
        } catch (Exception e) {
            LOG.info("Login error", e);
            return new AuthenticationResult()
            {{
                setError("Bad username / password");
            }};
        }
        kaguraBean.setUser(kaguraBean.getUserModel(user));
        return new AuthenticationResult()
        {{
                setError("");
                setToken(UUID.randomUUID().toString()); // UUID doesn't matter.
        }};
    }

    @Override
    public String testAuthToken(String authToken)
    {
        if (kaguraBean.getUser() == null)
        {
            return "Not OK";
        }
        return "Ok";
    }

    @Override
    public String logout(String authToken)
    {
        if (kaguraBean.getUser() == null)
        {
            return "Not done";
        }
        kaguraBean.setUser(null);
        return "Done";
    }

    @Override
    public List<String> getReports(String authToken)
    {
        if (kaguraBean.getUser() == null) throw new AuthenticationException("Authentication failure");
        return new ArrayList<String>()
        {{
            addAll(kaguraBean.getUserReports());
        }};
    }

    @Override
    public Map<String, ReportDetails> getReportsDetailed(final String authToken)
    {
        if (kaguraBean.getUser() == null) throw new AuthenticationException("Authentication failure");
        return new HashMap<String, ReportDetails>()
        {{
            for (String reportName : kaguraBean.getUserReports())
            {
                put(reportName, kaguraBean.getReportDetails(reportName, false, new ReportDetails()));
            }
        }};
    }
}


text:
Silex Cache Provider
====================

SilexCacheProvider is configurable to provide client interfaces for Memcache, APC, or a file-based cache.

Installation
------------

Run `composer require beryllium/silex-cache-provider` or add to your composer.json:

    "require": {
        "beryllium/silex-cache-provider": "*"
    }

Currently, the provider is only available with a minimum stability of "dev".

Configuration
-------------

### Memcache

Register the provider using Memcache (requires installation of the PHP memcache extension):

    $app->register(
        new Beryllium\SilexCacheProvider\SilexCacheProvider(),
        array(
            'be_cache.type' => 'memcache',
            'be_cache.host' => '127.0.0.1',
            'be_cache.port' => 11211,
        )
    );

The above settings are the provider defaults, so you can actually just do the following if that is your configuration:

    $app->register(new Beryllium\SilexCacheProvider\SilexCacheProvider());

### File Cache

This option requires a local folder with write access. The be\_cache service will use the folder to store serialized data from PHP.

    $app->register(
        new Beryllium\SilexCacheProvider\SilexCacheProvider(),
        array(
            'be_cache.type' => 'filecache',
            'be_cache.path' => __DIR__ . '/cache'
        )
    );

### APC Cache

This option requires the APC extension to be active.

    $app->register(
        new Beryllium\SilexCacheProvider\SilexCacheProvider(),
        array(
            'be_cache.type' => 'apc'
        )
    );

Usage
-----

Three methods are exposed by the cache service. Set, Get, and Delete.

### Set

This method takes three parameters: Key Name, Data, and Time-To-Live (in seconds).

To store the variable $data for 5 minutes, you would use:

    $app['be_cache']->set('key_name', $data, 300);

### Get and Delete

These methods only take one parameter: Key Name.

    $data = $app['be_cache']->get('key_name');
    // ...
    $app['be_cache']->delete('key_name');

Additional Tips
---------------

### Prefix

You may want to share your Memcache instance with other processes. In this scenario, you would want to namespace all of your application's keys so they won't conflict.

This can be done by specifying a prefix in your settings at registration:

    'be_cache.prefix' => 'example_prefix|';

### Get Client

You can retrieve the client from the service two ways:

    $client = $app['be_cache.client'];
    // or
    $client = $app['be_cache']->getClient();


text:
/*global assert:true */

'use strict';

describe('Minicart', function () {

    it('should add a paypal object to the window', function () {
        assert(window && window.paypal);
    });

    it('show have a render method', function () {
        assert(typeof window.paypal.minicart.render === 'function');
    });

    it('show have a reset method', function () {
        assert(typeof window.paypal.minicart.reset === 'function');
    });

});


text:
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Xamarin.Forms;

namespace XFormsApp.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}


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

namespace _05.Parse_tags
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * Problem 5. Parse tags
             *
             * You are given a text. Write a program that changes the text in all regions surrounded
             * by the tags <upcase> and </upcase> to upper-case.
             * The tags cannot be nested.
             *
             * Example: We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.
             * The expected result: We are living in a YELLOW SUBMARINE. We don't have ANYTHING else.
             */

            StringBuilder parsedText = new StringBuilder();
            string text = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";

            string startWord = "<upcase>";
            string endWord = "</upcase>";
            string searchingText = String.Empty;
            int index = 0;
            int end = 0;
            int start = 0;

            while (text.IndexOf(startWord, index) > 0)
            {
                if (parsedText.Length == 0)
                {
                    parsedText.Append(text);
                }

                start = text.IndexOf(startWord, index) + startWord.Length;
                end = text.IndexOf(endWord, index);
                int textLength = end - start;

                searchingText = text.Substring(start, textLength);
                searchingText = searchingText.ToUpper();
                index = end + endWord.Length;

                parsedText.Remove(start - startWord.Length, startWord.Length + searchingText.Length + endWord.Length);
                parsedText.Insert(start - startWord.Length, searchingText);

                start = 0;
                end = 0;
                index = 0;
                text = parsedText.ToString();
            }

            Console.WriteLine(parsedText);
        }
    }
}


text:
#ifndef NNVM_TOP_NN_H_
#define NNVM_TOP_NN_H_

#include <dmlc/base.h>
#include <dmlc/parameter.h>
#include <nnvm/tuple.h>
#include <nnvm/layout.h>
#include <string>
#include "tensor.h"

namespace nnvm {
namespace top {

struct DenseParam : public dmlc::Parameter<DenseParam> {
  int units;
  bool use_bias;

  DMLC_DECLARE_PARAMETER(DenseParam) {
    DMLC_DECLARE_FIELD(units).set_lower_bound(1)
    .describe("Number of hidden units of the dense transformation.");
    DMLC_DECLARE_FIELD(use_bias).set_default(true)
    .describe("Whether to use bias parameter");
  }
  // constants
  static const constexpr int kData = 0;
  static const constexpr int kWeight = 1;
  static const constexpr int kBias = 2;
};

struct DropoutParam : public dmlc::Parameter<DropoutParam> {
  float rate;

  DMLC_DECLARE_PARAMETER(DropoutParam) {
    DMLC_DECLARE_FIELD(rate).set_default(0.5)
        .set_range(0, 1)
        .describe("Fraction of the input that gets dropped out during training time.");
  }
};

struct BatchNormParam : public dmlc::Parameter<BatchNormParam> {
  int axis;
  double epsilon;
  double momentum;
  bool center;
  bool scale;

  DMLC_DECLARE_PARAMETER(BatchNormParam) {
    DMLC_DECLARE_FIELD(axis).set_default(1)
      .describe("Specify which shape axis the channel is specified.");
    DMLC_DECLARE_FIELD(epsilon).set_default(1e-5)
        .describe("Small float added to variance to avoid dividing by zero.");
    DMLC_DECLARE_FIELD(center).set_default(true)
        .describe("If True, add offset of `beta` to normalized tensor."
                  "If False, `beta` is ignored.");
    DMLC_DECLARE_FIELD(scale).set_default(true)
        .describe("If True, multiply by `gamma`. If False, `gamma` is not used."
                  "When the next layer is piecewise linear (also e.g. `nn.relu`),"
                  "this can be disabled since the scaling"
                  "will be done by the next layer.");
  }
  // constants
  static const constexpr int kData = 0;
  static const constexpr int kGamma = 1;
  static const constexpr int kBeta = 2;
  static const constexpr int kMovingMean = 3;
  static const constexpr int kMovingVariance = 4;
};

// Shared by softmax and log_softmax
struct SoftmaxParam : public dmlc::Parameter<SoftmaxParam> {
  int axis;

  DMLC_DECLARE_PARAMETER(SoftmaxParam) {
    DMLC_DECLARE_FIELD(axis).set_default(-1)
        .describe("The axis to sum over when computing softmax.");
  }
};

struct LeakyReLUParam : public dmlc::Parameter<LeakyReLUParam> {
  double alpha;

  DMLC_DECLARE_PARAMETER(LeakyReLUParam) {
    DMLC_DECLARE_FIELD(alpha).set_lower_bound(0.0).set_default(0.25)
        .describe("slope coefficient for the negative half axis.");
  }
};

struct PReLUParam : public dmlc::Parameter<PReLUParam> {
  int axis;
  DMLC_DECLARE_PARAMETER(PReLUParam) {
    DMLC_DECLARE_FIELD(axis).set_default(1)
      .describe("Specify which shape axis the channel is specified.");
  }
};

struct PadParam : public dmlc::Parameter<PadParam> {
  float pad_value;
  Tuple<Tuple<int> > pad_width;

  DMLC_DECLARE_PARAMETER(PadParam) {
    DMLC_DECLARE_FIELD(pad_value).set_default(0.0)
      .describe("The value to be padded.");
    DMLC_DECLARE_FIELD(pad_width)
      .describe("Number of values padded to the edges of each axis, "
                "in the format of ((before_1, after_1), ... (before_N, after_N))");
  }
};

struct Conv2DParam : public dmlc::Parameter<Conv2DParam> {
  int channels;
  TShape kernel_size;
  TShape strides;
  TShape padding;
  TShape dilation;
  int groups;
  std::string layout;
  std::string kernel_layout;
  std::string out_layout;
  int out_dtype;
  bool use_bias;

  DMLC_DECLARE_PARAMETER(Conv2DParam) {
    DMLC_DECLARE_FIELD(channels)
      .describe("The dimensionality of the output space"
                "i.e. the number of output channels in the convolution.");
    DMLC_DECLARE_FIELD(kernel_size)
      .describe("Specifies the dimensions of the convolution window.");
    DMLC_DECLARE_FIELD(strides).set_default(TShape({1, 1}))
      .describe("Specifies the strides of the convolution.");
    DMLC_DECLARE_FIELD(padding).set_default(TShape({0, 0}))
      .describe("If padding is non-zero, then the input is implicitly zero-padded"
                "on both sides for padding number of points");
    DMLC_DECLARE_FIELD(dilation).set_default(TShape({1, 1}))
      .describe("Specifies the dilation rate to use for dilated convolution.");
    DMLC_DECLARE_FIELD(groups).set_default(1)
      .describe("Controls the connections between inputs and outputs."
                "At groups=1, all inputs are convolved to all outputs."
                "At groups=2, the operation becomes equivalent to having two convolution"
                "layers side by side, each seeing half the input channels, and producing"
                "half the output channels, and both subsequently concatenated.");
    DMLC_DECLARE_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
    DMLC_DECLARE_FIELD(out_layout).set_default("__undef__")
      .describe("Dimension ordering of output. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Default to be same as input layout.");
    DMLC_DECLARE_FIELD(kernel_layout).set_default("OIHW")
      .describe("Dimension ordering of weight. Can be 'OIHW', 'OIHW16o16i', etc."
                "'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width"
                "dimensions respectively.");
    DMLC_DECLARE_DTYPE_FIELD(out_dtype)
      .add_enum("same", -1)
      .set_default(-1)
      .describe("Output data type, set to explicit type under mixed precision setting");

    DMLC_DECLARE_FIELD(use_bias).set_default(true)
      .describe("Whether the layer uses a bias vector.");
  }
  // constants
  static const constexpr int kData = 0;
  static const constexpr int kWeight = 1;
  static const constexpr int kBias = 2;
};

struct WinogradWeightTransformParam : public dmlc::Parameter<WinogradWeightTransformParam> {
    int tile_size;

    DMLC_DECLARE_PARAMETER(WinogradWeightTransformParam) {
      DMLC_DECLARE_FIELD(tile_size)
        .describe("Tile size of winograd. E.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)");
    }

    static const constexpr int kWeight = 0;
};

struct WinogradConv2DParam : public dmlc::Parameter<WinogradConv2DParam> {
  int channels;
  TShape kernel_size;
  TShape strides;
  TShape padding;
  TShape dilation;
  int groups;
  std::string layout;
  std::string kernel_layout;
  std::string out_layout;
  int out_dtype;
  bool use_bias;
  int tile_size;

  DMLC_DECLARE_PARAMETER(WinogradConv2DParam) {
    DMLC_DECLARE_FIELD(channels)
      .describe("The dimensionality of the output space"
                "i.e. the number of output channels in the convolution.");
    DMLC_DECLARE_FIELD(kernel_size)
      .describe("Specifies the dimensions of the convolution window.");
    DMLC_DECLARE_FIELD(strides).set_default(TShape({1, 1}))
      .describe("Specifies the strides of the convolution.");
    DMLC_DECLARE_FIELD(padding).set_default(TShape({0, 0}))
      .describe("If padding is non-zero, then the input is implicitly zero-padded"
                "on both sides for padding number of points");
    DMLC_DECLARE_FIELD(dilation).set_default(TShape({1, 1}))
      .describe("Specifies the dilation rate to use for dilated convolution.");
    DMLC_DECLARE_FIELD(groups).set_default(1)
      .describe("Controls the connections between inputs and outputs."
                "At groups=1, all inputs are convolved to all outputs."
                "At groups=2, the operation becomes equivalent to having two convolution"
                "layers side by side, each seeing half the input channels, and producing"
                "half the output channels, and both subsequently concatenated.");
    DMLC_DECLARE_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of input data. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
    DMLC_DECLARE_FIELD(out_layout).set_default("__undef__")
      .describe("Dimension ordering of output. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Default to be same as input layout.");
    DMLC_DECLARE_FIELD(kernel_layout).set_default("OIHW")
      .describe("Dimension ordering of weight. Can be 'OIHW', 'OIHW16o16i', etc."
                "'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width"
                "dimensions respectively.");
    DMLC_DECLARE_DTYPE_FIELD(out_dtype)
      .add_enum("same", -1)
      .set_default(-1)
      .describe("Output data type, set to explicit type under mixed precision setting");
    DMLC_DECLARE_FIELD(use_bias).set_default(true)
      .describe("Whether the layer uses a bias vector.");
    DMLC_DECLARE_FIELD(tile_size)
      .describe("Tile size of winograd. E.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3)");
  }
  // constants
  static const constexpr int kData = 0;
  static const constexpr int kWeight = 1;
  static const constexpr int kBias = 2;
};

struct Conv2DTransposeParam : public dmlc::Parameter<Conv2DTransposeParam> {
  int channels;
  TShape kernel_size;
  TShape strides;
  TShape padding;
  TShape output_padding;
  TShape dilation;
  int groups;
  std::string layout;
  std::string kernel_layout;
  int out_dtype;
  bool use_bias;

  DMLC_DECLARE_PARAMETER(Conv2DTransposeParam) {
    DMLC_DECLARE_FIELD(channels)
      .describe("The dimensionality of the output space"
                "i.e. the number of output channels in the convolution.");
    DMLC_DECLARE_FIELD(kernel_size)
      .describe("Specifies the dimensions of the convolution window.");
    DMLC_DECLARE_FIELD(strides).set_default(TShape({1, 1}))
      .describe("Specifies the strides of the convolution.");
    DMLC_DECLARE_FIELD(output_padding).set_default(TShape({0, 0}))
      .describe("Zero-padding added to one side of the output.");
    DMLC_DECLARE_FIELD(padding).set_default(TShape({0, 0}))
      .describe("If padding is non-zero, then the input is implicitly zero-padded"
                "on both sides for padding number of points");
    DMLC_DECLARE_FIELD(dilation).set_default(TShape({1, 1}))
      .describe("Specifies the dilation rate to use for dilated convolution.");
    DMLC_DECLARE_FIELD(groups).set_default(1)
      .describe("Controls the connections between inputs and outputs."
                "At groups=1, all inputs are convolved to all outputs."
                "At groups=2, the operation becomes equivalent to having two convolution"
                "layers side by side, each seeing half the input channels, and producing"
                "half the output channels, and both subsequently concatenated.");
    DMLC_DECLARE_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of data. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
    DMLC_DECLARE_FIELD(kernel_layout).set_default("OIHW")
      .describe("Dimension ordering of data and weight. Can be 'OIHW', 'OIHW16o16i', etc."
                "'O', 'I', 'H', 'W' stands for num_filter, input_channel, height, and width"
                "dimensions respectively.");
    DMLC_DECLARE_DTYPE_FIELD(out_dtype)
        .add_enum("same", -1)
        .set_default(-1)
        .describe("Output data type, set to explicit type under mixed precision setting");
    DMLC_DECLARE_FIELD(use_bias).set_default(true)
      .describe("Whether the layer uses a bias vector.");
  }
  // constants
  static const constexpr int kData = 0;
  static const constexpr int kWeight = 1;
  static const constexpr int kBias = 2;
};

struct MaxPool2DParam : public dmlc::Parameter<MaxPool2DParam> {
  TShape pool_size;
  TShape strides;
  TShape padding;
  std::string layout;
  bool ceil_mode;

  DMLC_DECLARE_PARAMETER(MaxPool2DParam) {
    DMLC_DECLARE_FIELD(pool_size)
      .describe("Size of the pooling windows..");
    DMLC_DECLARE_FIELD(strides).set_default(TShape({1, 1}))
      .describe("Specifies the strides of the convolution.");
    DMLC_DECLARE_FIELD(padding).set_default(TShape({0, 0}))
      .describe("If padding is non-zero, then the input is implicitly zero-padded"
                "Padding support both symmetric and asymmetric as"
                "one int : same padding used on all sides"
                "two int : bottom, right will use same padding as top, left"
                "four int : padding width in the order of (top, left, bottom, right)");
    DMLC_DECLARE_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of data and weight. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
    DMLC_DECLARE_FIELD(ceil_mode).set_default(false)
      .describe("When true, will use ceil instead of floor to compute the output shape.");
  }
};

struct AvgPool2DParam : public dmlc::Parameter<AvgPool2DParam> {
  TShape pool_size;
  TShape strides;
  TShape padding;
  std::string layout;
  bool ceil_mode;
  bool count_include_pad;

  DMLC_DECLARE_PARAMETER(AvgPool2DParam) {
    DMLC_DECLARE_FIELD(pool_size)
      .describe("Size of the pooling windows..");
    DMLC_DECLARE_FIELD(strides).set_default(TShape({1, 1}))
      .describe("Specifies the strides of the convolution.");
    DMLC_DECLARE_FIELD(padding).set_default(TShape({0, 0}))
      .describe("If padding is non-zero, then the input is implicitly zero-padded"
                "Padding support both symmetric and asymmetric as"
                "one int : same padding used on all sides"
                "two int : bottom, right will use same padding as top, left"
                "four int : padding width in the order of (top, left, bottom, right)");
    DMLC_DECLARE_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of data and weight. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
    DMLC_DECLARE_FIELD(ceil_mode).set_default(false)
      .describe("When true, will use ceil instead of floor to compute the output shape.");
    DMLC_DECLARE_FIELD(count_include_pad).set_default(false)
      .describe("When true, will include padding to compute the average");
  }
};

struct GlobalPool2DParam : public dmlc::Parameter<GlobalPool2DParam> {
  std::string layout;

  DMLC_DECLARE_PARAMETER(GlobalPool2DParam) {
    DMLC_DECLARE_FIELD(layout).set_default("NCHW")
      .describe("Dimension ordering of data and weight. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Convolution is applied on the 'H' and"
                "'W' dimensions.");
  }
};

struct UpSamplingParam : public dmlc::Parameter<UpSamplingParam> {
  int scale;
  std::string layout;
  std::string method;

  DMLC_DECLARE_PARAMETER(UpSamplingParam) {
    DMLC_DECLARE_FIELD(scale)
      .describe("upsampling scaling factor");
    DMLC_DECLARE_FIELD(layout)
      .set_default("NCHW")
      .describe("Dimension ordering of data. Can be 'NCHW', 'NHWC', etc."
                "'N', 'C', 'H', 'W' stands for batch, channel, height, and width"
                "dimensions respectively. Upsampling is applied on the 'H' and"
                "'W' dimensions.");
    DMLC_DECLARE_FIELD(method)
      .set_default("NEAREST_NEIGHBOR")
      .describe("Specify the mode to use for scaling."
                "NEAREST_NEIGHBOR -  Nearest Neighbor"
                "BILINEAR - Bilinear Interpolation");
  }
};

struct LayoutTransformParam : public dmlc::Parameter<LayoutTransformParam> {
  std::string src_layout;
  std::string dst_layout;

  DMLC_DECLARE_PARAMETER(LayoutTransformParam) {
    DMLC_DECLARE_FIELD(src_layout).set_default("__undef__")
    .describe("Dimension ordering of data");
    DMLC_DECLARE_FIELD(dst_layout).set_default("__undef__")
    .describe("Dimension ordering of data.");
  }
};

struct MultiBoxPriorParam : public dmlc::Parameter<MultiBoxPriorParam> {
  Tuple<float> sizes;
  Tuple<float> ratios;
  Tuple<float> steps;
  Tuple<float> offsets;
  bool clip;

  DMLC_DECLARE_PARAMETER(MultiBoxPriorParam) {
    DMLC_DECLARE_FIELD(sizes).set_default(Tuple<float>({1.0}))
      .describe("List of sizes of generated MultiBoxPriores.");
    DMLC_DECLARE_FIELD(ratios).set_default(Tuple<float>({1.0}))
    .describe("List of aspect ratios of generated MultiBoxPriores.");
    DMLC_DECLARE_FIELD(steps).set_default(Tuple<float>({-1.0, -1.0}))
    .describe("Priorbox step across y and x, -1 for auto calculation.");
    DMLC_DECLARE_FIELD(offsets).set_default(Tuple<float>({0.5, 0.5}))
    .describe("Priorbox center offsets, y and x respectively.");
    DMLC_DECLARE_FIELD(clip).set_default(false)
    .describe("Whether to clip out-of-boundary boxes.");
  }
};

struct MultiBoxTransformLocParam : public dmlc::Parameter<MultiBoxTransformLocParam> {
  bool clip;
  float threshold;
  Tuple<float> variances;
  DMLC_DECLARE_PARAMETER(MultiBoxTransformLocParam) {
    DMLC_DECLARE_FIELD(clip).set_default(true)
      .describe("Clip out-of-boundary boxes.");
    DMLC_DECLARE_FIELD(threshold).set_default(0.01)
    .describe("Threshold to be a positive prediction.");
    DMLC_DECLARE_FIELD(variances).set_default(Tuple<float>({0.1f, 0.1f, 0.2f, 0.2f}))
    .describe("Variances to be decoded from box regression output.");
  }
};

struct NMSParam : public dmlc::Parameter<NMSParam> {
  float nms_threshold;
  bool force_suppress;
  int nms_topk;
  DMLC_DECLARE_PARAMETER(NMSParam) {
    DMLC_DECLARE_FIELD(nms_threshold).set_default(0.5)
      .describe("Non-maximum suppression threshold.");
    DMLC_DECLARE_FIELD(force_suppress).set_default(false)
    .describe("Suppress all detections regardless of class_id.");
    DMLC_DECLARE_FIELD(nms_topk).set_default(-1)
    .describe("Keep maximum top k detections before nms, -1 for no limit.");
  }
};

struct LRNParam : public dmlc::Parameter<LRNParam> {
  int size;
  int axis;
  float alpha;
  float beta;
  float bias;

  DMLC_DECLARE_PARAMETER(LRNParam) {
    DMLC_DECLARE_FIELD(size)
      .describe("The size of the local region to be considered for normalization.");
    DMLC_DECLARE_FIELD(axis)
      .describe("input data layout channel axis");
    DMLC_DECLARE_FIELD(alpha)
      .describe("The scaling parameter.");
    DMLC_DECLARE_FIELD(beta)
      .describe("The exponent parameter.");
    DMLC_DECLARE_FIELD(bias)
      .describe("The offset parameter.");
  }
  // constants
  static const constexpr int kData = 0;
};

struct L2NormalizeParam : public dmlc::Parameter<L2NormalizeParam> {
  float eps;
  Tuple<int> axis;

  DMLC_DECLARE_PARAMETER(L2NormalizeParam) {
    DMLC_DECLARE_FIELD(eps)
      .describe("float type epsilon value.");
    DMLC_DECLARE_FIELD(axis)
      .describe("axis over the normalization applied");
  }
};

}  // namespace top
}  // namespace nnvm

#endif  // NNVM_TOP_NN_H_


text:
package cli

import (
	"context"
	"errors"
	"fmt"
	"time"

	kingpin "gopkg.in/alecthomas/kingpin.v2"

	"github.com/prometheus/alertmanager/api/v2/client/silence"
	"github.com/prometheus/alertmanager/api/v2/models"
	"github.com/prometheus/alertmanager/cli/format"
	"github.com/prometheus/alertmanager/pkg/labels"
)

type silenceQueryCmd struct {
	expired   bool
	quiet     bool
	createdBy string
	matchers  []string
	within    time.Duration
}

const querySilenceHelp = `Query Alertmanager silences.

Amtool has a simplified prometheus query syntax, but contains robust support for
bash variable expansions. The non-option section of arguments constructs a list
of "Matcher Groups" that will be used to filter your query. The following
examples will attempt to show this behaviour in action:

amtool silence query alertname=foo node=bar

	This query will match all silences with the alertname=foo and node=bar label
	value pairs set.

amtool silence query foo node=bar

	If alertname is omitted and the first argument does not contain a '=' or a
	'=~' then it will be assumed to be the value of the alertname pair.

amtool silence query 'alertname=~foo.*'

	As well as direct equality, regex matching is also supported. The '=~' syntax
	(similar to prometheus) is used to represent a regex match. Regex matching
	can be used in combination with a direct match.

In addition to filtering by silence labels, one can also query for silences
that are due to expire soon with the "--within" parameter. In the event that
you want to preemptively act upon expiring silences by either fixing them or
extending them. For example:

amtool silence query --within 8h

returns all the silences due to expire within the next 8 hours. This syntax can
also be combined with the label based filtering above for more flexibility.

The "--expired" parameter returns only expired silences. Used in combination
with "--within=TIME", amtool returns the silences that expired within the
preceding duration.

amtool silence query --within 2h --expired

returns all silences that expired within the preceding 2 hours.
`

func configureSilenceQueryCmd(cc *kingpin.CmdClause) {
	var (
		c        = &silenceQueryCmd{}
		queryCmd = cc.Command("query", querySilenceHelp).Default()
	)

	queryCmd.Flag("expired", "Show expired silences instead of active").BoolVar(&c.expired)
	queryCmd.Flag("quiet", "Only show silence ids").Short('q').BoolVar(&c.quiet)
	queryCmd.Flag("created-by", "Show silences that belong to this creator").StringVar(&c.createdBy)
	queryCmd.Arg("matcher-groups", "Query filter").StringsVar(&c.matchers)
	queryCmd.Flag("within", "Show silences that will expire or have expired within a duration").DurationVar(&c.within)
	queryCmd.Action(execWithTimeout(c.query))
}

func (c *silenceQueryCmd) query(ctx context.Context, _ *kingpin.ParseContext) error {
	if len(c.matchers) > 0 {
		// If the parser fails then we likely don't have a (=|=~|!=|!~) so lets
		// assume that the user wants alertname=<arg> and prepend `alertname=`
		// to the front.
		_, err := labels.ParseMatcher(c.matchers[0])
		if err != nil {
			c.matchers[0] = fmt.Sprintf("alertname=%s", c.matchers[0])
		}
	}

	silenceParams := silence.NewGetSilencesParams().WithContext(ctx).WithFilter(c.matchers)

	amclient := NewAlertmanagerClient(alertmanagerURL)

	getOk, err := amclient.Silence.GetSilences(silenceParams)
	if err != nil {
		return err
	}

	displaySilences := []models.GettableSilence{}
	for _, silence := range getOk.Payload {
		// skip expired silences if --expired is not set
		if !c.expired && time.Time(*silence.EndsAt).Before(time.Now()) {
			continue
		}
		// skip active silences if --expired is set
		if c.expired && time.Time(*silence.EndsAt).After(time.Now()) {
			continue
		}
		// skip active silences expiring after "--within"
		if !c.expired && int64(c.within) > 0 && time.Time(*silence.EndsAt).After(time.Now().UTC().Add(c.within)) {
			continue
		}
		// skip silences that expired before "--within"
		if c.expired && int64(c.within) > 0 && time.Time(*silence.EndsAt).Before(time.Now().UTC().Add(-c.within)) {
			continue
		}
		// Skip silences if the author doesn't match.
		if c.createdBy != "" && *silence.CreatedBy != c.createdBy {
			continue
		}

		displaySilences = append(displaySilences, *silence)
	}

	if c.quiet {
		for _, silence := range displaySilences {
			fmt.Println(*silence.ID)
		}
	} else {
		formatter, found := format.Formatters[output]
		if !found {
			return errors.New("unknown output formatter")
		}
		if err := formatter.FormatSilences(displaySilences); err != nil {
			return fmt.Errorf("error formatting silences: %v", err)
		}
	}
	return nil
}


text:
package uk.co.pilllogger.events;

import uk.co.pilllogger.models.Pill;

/**
 * Created by Alex on 20/07/2014
 * in uk.co.pilllogger.events.
 */
public class UpdatedPillEvent {
    private final Pill _pill;
    private boolean _deleted = false;

    public UpdatedPillEvent(Pill pill){
        _pill = pill;
    }

    public UpdatedPillEvent(Pill pill, boolean deleted) {
        this(pill);
        _deleted = deleted;
    }

    public Pill getPill() {
        return _pill;
    }

    public boolean wasDeleted(){
        return _deleted;
    }
}


text:
<head>
  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=UA-115145410-1"></script>
  <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'UA-115145410-1');
  </script>

  <title>Samuel James Bell</title>
  <link rel="stylesheet" href="../css/styles.css">
</head>


text:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace NDoc.Gui
{
	/// <summary>
	/// Summary description for SolutionForm.
	/// </summary>
	public class SolutionForm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Button okButton;
		private System.Windows.Forms.Button cancelButton;
		private System.Windows.Forms.ListBox configList;

		/// <summary>
		/// Listbox of solution's configurations.
		/// </summary>
		public ListBox ConfigList
		{
			get { return configList; }
		}

		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		/// <summary>
		/// Initializes a new instance of the SolutionForm class.
		/// </summary>
		public SolutionForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.cancelButton = new System.Windows.Forms.Button();
			this.label1 = new System.Windows.Forms.Label();
			this.okButton = new System.Windows.Forms.Button();
			this.configList = new System.Windows.Forms.ListBox();
			this.SuspendLayout();
			//
			// cancelButton
			//
			this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.cancelButton.Location = new System.Drawing.Point(96, 112);
			this.cancelButton.Name = "cancelButton";
			this.cancelButton.Size = new System.Drawing.Size(80, 24);
			this.cancelButton.TabIndex = 3;
			this.cancelButton.Text = "Cancel";
			this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
			//
			// label1
			//
			this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.label1.Location = new System.Drawing.Point(8, 8);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(184, 16);
			this.label1.TabIndex = 1;
			this.label1.Text = "Select a solution configuration:";
			//
			// okButton
			//
			this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.okButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.okButton.Location = new System.Drawing.Point(8, 112);
			this.okButton.Name = "okButton";
			this.okButton.Size = new System.Drawing.Size(80, 24);
			this.okButton.TabIndex = 3;
			this.okButton.Text = "OK";
			this.okButton.Click += new System.EventHandler(this.okButton_Click);
			//
			// configList
			//
			this.configList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
				| System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.configList.Location = new System.Drawing.Point(8, 24);
			this.configList.Name = "configList";
			this.configList.Size = new System.Drawing.Size(168, 82);
			this.configList.TabIndex = 2;
			this.configList.DoubleClick += new System.EventHandler(this.okButton_Click);
			//
			// SolutionForm
			//
			this.AcceptButton = this.okButton;
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.CancelButton = this.cancelButton;
			this.ClientSize = new System.Drawing.Size(186, 144);
			this.Controls.Add(this.cancelButton);
			this.Controls.Add(this.okButton);
			this.Controls.Add(this.configList);
			this.Controls.Add(this.label1);
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.MinimumSize = new System.Drawing.Size(194, 178);
			this.Name = "SolutionForm";
			this.ShowInTaskbar = false;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
			this.Text = "Solution";
			this.ResumeLayout(false);

		}
		#endregion

		private void okButton_Click(object sender, System.EventArgs e)
		{
			if (configList.SelectedIndex > -1)
			{
				this.Close();
			}
		}

		private void cancelButton_Click(object sender, System.EventArgs e)
		{
			configList.ClearSelected();
		}

	}
}


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

namespace PoshSec.Framework.Strings
{
    internal static class StringValue
    {
        public const string psftitle = "PoshSec Framework";
        public const string AlertBalloon = "You have an alert!";
        public const string AlertsBalloon = "You have {0} alerts!";
        public const string PSRequirements = "It appears that your environment is not configured correctly for PoshSec Framework to work correctly.\r\nYou need PowerShell 3.0 (Windows Management Framework 3.0) and Microsoft .NET 4.5\r\nPlease download and install WMF 3.0 before running PoshSec Framework.";
        public const string RootDrive = "You are running PoshSec Framework from the root of a disk drive. It is recommended to put PoshSec Framework in a subfolder.\r\n\r\nFor example: C:\\psf\\\r\n\r\nDo you wish to continue anyway?";
        public const string ActiveScriptsRunning = "You have active scripts running. If you exit, all running scripts will be terminated. Are you sure you want to exit?";
        public const string ReloadScriptsRunning = "Can not reload the framework because there are scripts running. Please stop all scripts before issuing the reload command again.";
        public const string SettingScriptsRunning = "You can not change the settings while scripts or commands are running. Please stop any commands or scripts and then try again.";
        public const string CommandRunning = "A command is already running. Please wait, or cancel the command and try again.";
        public const string RequireParams = "There are required paramaters that are missing values. Please fill in all of the required parameters before proceeding.";
        public const string SelectIPScan = "Please select an IP to scan.";
        public const string SelectNetwork = "Please select a network first.";
        public const string ScriptPathError = "The specified script directory does not exist.";
        public const string ModulePathError = "The specified module directory does not exist.";
        public const string CreatePath = " Would you like to create the directory?";
        public const string ImportError = "There was an error when importing the PoshSec Framework file.";
        public const string ClearAlerts = "Are you sure you want to clear all of the alerts?";
        public const string ClearAlert = "Are you sure you want to clear the selected alerts?";
        public const string UnhandledException = "Unhandled exception in script function.";
        public const string ConfirmScheduleDelete = "Are you sure you want to delete the selected schedules?";
        public const string ConfirmNetworkDelete = "Are you sure you want to delete the selected network?";
        public const string ConfirmModuleDelete = "Are you sure you want to delete the selected module(s)?";
        public const string ConfirmScriptDelete = "There are existing scripts in the Scripts folder. Downloading the current scripts will delete any existing scripts in that folder. Proceed?";
        public const string SelectWeekdays = "Please select the days of the week to schedule this script.";
        public const string SelectMonths = "Please select the months of the year and the dates to schedule this script.";
        public const string SelectSystems = "Please select some systems first.";
        public const string InvalidNetworkName = "Please enter a unique and valid network name. (i.e. system.local)";
        public const string InvalidSystemName = "Please enter a unique and valid system name. (i.e. PC123456)";
        public const string InvalidSyslog = "Please enter a valid host name or IP address for the syslog server.";
        public const string InvalidAlertType = "That is not a valid Alert Type. The valid alert types are ";
        public const string FileSavedSuccessfully = "File saved successfully.";
        public const string RestartRequired = "PoshSec Framework needs to be restarted. Would you like to restart now?";

        public const string TNSetExecutionPolicy = "\r\n\r\nFor more information, please visit\r\nhttp://technet.microsoft.com/en-us/library/ee176961.aspx";
        public const string TNUpdateHelp = "\r\n\r\nFor more information, please visit\r\nhttp://technet.microsoft.com/en-us/library/hh849720.aspx";
        public const string TNUnblockFile = "\r\n\r\nFor more information, please visit\r\nhttp://technet.microsoft.com/en-us/library/ee176841.aspx\r\nhttp://technet.microsoft.com/en-us/library/hh849924.aspx";

        public const string FTCheckSettings = "This will ensure that the settings are pointing to the proper directories and files necessary for the PoshSec Framework to function properly.";
        public const string FTInitialDownload = "This will download the PoshSec repository from github. This step can be skipped if you would prefer to use other repositories.";
        public const string FTUnblockFiles = "This will execute the command\r\n'Get-ChildItem -recurse <path to poshsecframework> | Unblock-File'. \r\n\r\nGet-ChildItem -recurse gets a listing of all of the files in the poshsecframework directory, and subdirectories, and sends that to the Unblock-File Cmdlet. This will remove the 'Blocked' file attibute on those files." + TNUnblockFile;
        public const string FTUpdateHelp = "This will execute the command\r\n'Update-Help -Force'.\r\n\r\nThis is required when using the Get-Help Cmdlet. This requires an active internet connection." + TNUpdateHelp;
        public const string FTSetExecutionPolicy = "This will execute the command\r\n'Set-ExecutionPolicy RemoteSigned -Force'.\r\n\r\nThis allows for downloaded scripts that are signed by a trusted publisher to run on your system.\r\n\r\nPoshSec Framework requires this ExecutionPolicy to work." + TNSetExecutionPolicy;
        public const string FTRunSampleScript = "This will run a sample powershell script after the configuration is complete to ensure that everything is configured properly.";
        public const string NoStepDescription = "Unable to find step description.";
        public const string RunAsAdministratorError = "You will need to run PoshSec Framework as an Administrator for this command to work, or resolve the errors listed. Would you like to attempt to run this step again?";
        public const string StepCompleteDescription = "Click a step to view any error, or status, messages.";
        public const string StepSelectDescription = "Select a step to the left to read the description.";
        public const string StepSuccessDescription = "The step executed successfully.";
        public const string StepIgnoredDescription = "The step was ignored.";
        public const string StepSuccess = "Success";
        public const string StepRunning = "Running...";
        public const string StepIgnored = "Ignored";
        public const string StepFailed = "Failed!";
        public const string MustSelectStep = "You must select at least 1 step to continue.";
        public const string AlertFormat = "Severity: {0}\\r\\nMessage: {1}\\r\\nTimestamp: {2}\\r\\nScript: {3}\\r\\n";
        public const string ScriptBlockNoFile = "\r\nat <ScriptBlock>, <No file>: line 1";

        public const string ScriptCancelled = "Script cancelled by user.";
        public const string CommandCancelled = "Command cancelled by user.";

        public const string ActiveScripts = "Active Scripts";
        public const string SelectActiveScript = "Please select an active script.";

        public const string psf = "psf > ";
        public const string Ready = "Ready";
        public const string NotImplemented = "Not implemented yet. Soon!";
        public const string WriteError = "\r\nWrite-Output $error";
        public const string ModRestartFilename = "modrestart.psf";

        public const string LocalNetwork = "Local Network";
        public const string Up = "Up";
        public const string Down = "Down";
        public const string NotInstalled = "Not Installed";
        public const string TimeFormat = "MM/dd/yyyy hh:mm tt";
        public const string LogDateFormat = "MM/dd/yyyy";
        public const string LogTimeFormat = "hh:mm:ss tt";
        public const string SyslogTimeFormat = "MMM dd yyyy hh:mm:ss";
        public const string WaitingForHostResp = "Waiting for hostname responses, please wait...";
        public const string BlankMAC = "00-00-00-00-00-00";
        public const string NAHost = "N/A";
        public const string UnknownHost = "0.0.0.0";

        public const string CLS = "CLS";
        public const string Clear = "CLEAR";
        public const string AptGetUpdate = "APT-GET UPDATE";
        public const string Reload = "RELOAD";
        public const string Exit = "EXIT";

        public const string GetCommand = "Get-Command";
        public const string OutString = "Out-String";
        public const string GetHelpFull = "Get-Help {0} -full";
        public const string SetExecutionPolicy = "Set-ExecutionPolicy RemoteSigned -Force";
        public const string UpdateHelp = "Update-Help -Force";
        public const string UnblockFiles = "Unblock-File -Path ";

        public const string UpdateURI = "https://github.com/PoshSec/PoshSecFramework/commits/master";
        public const string WikiURI = "https://github.com/PoshSec/PoshSecFramework/wiki/_pages";
        public const string GithubURI = "https://api.github.com/";
        public const string GithubURL = "https://github.com/";
        public const string RateLimitURL = "http://developer.github.com/v3/#rate-limiting";
        public const string PSFScriptsPath = "repos/PoshSec/PoshSecScripts/zipball/master";
        public const string ArchiveFormat = "repos/{0}/{1}/zipball/{2}";
        public const string LastModifiedFormat = "repos/{0}/{1}";
        public const string BranchFormat = "repos/{0}/{1}/branches";
        public const string AccessToken = "?access_token={0}";
        public const string ModuleSaveFormat = "{0}|{1}|{2}|{3}";
        public const string ContentTypeJSON = "application/json; charset=utf-8";
        public const string DefaultBranch = "master";
        public const string RateLimitKey = "X-RateLimit-Remaining";
        public const string LastModifiedKey = "Last-Modified";
        public const string NotModified = "304 Not Modified";
        public const string IfModifiedSince = "If-Modified-Since";
        public const string InvalidPSModule = "The repository {0} in branch {1} does not have a valid .psd1 file. This is required for PowerShell modules. Please check the path, repository, and/or branch and try again.";
        public const string InvalidRepositoryURL = "The URL specified is not a valid Github repository URL. Please enter the URL again.";
        public const string BranchNotFound = "The specified branch of {0} was not found as a valid branch for this repository.";
        public const string ModuleUptoDate = "That module is up to date. There are no updates available.";
        public const string ModuleUpdateAvailable = "This module was updated on {0}. Would you like to update your copy now?";
        public const string ConfirmRemoveSystem = "Are you sure you want to remove the ({0}) {1} system(s)?";

        public const string ExportFormats = "Extensible Markup Language (*.xml)|*.xml|Comma Separate Values (*.csv)|*.csv|Tabbed Delimited (*.txt)|*.txt";
        public const string OutputLogFormat = "[{0}:{1}] - {2}";
        public const string SyslogFormat = "{0}{1} {2} : %{3}-{4}: {5}";
        public const string PriorityFormat = "<{0}>";
        public const string AlertLabelFormat = "{0} ({1})";
        public const string NetworkSettingsPath = "networks.json";
    }
}


text:
import React, {useCallback} from 'react';
import {useIntl} from 'react-intl';

import {enableChannelCalls} from '@calls/actions';
import {useTryCallsFunction} from '@calls/hooks';
import OptionItem from '@components/option_item';
import {useServerUrl} from '@context/server';
import {preventDoubleTap} from '@utils/tap';

interface Props {
    channelId: string;
    enabled: boolean;
}

const ChannelInfoEnableCalls = ({channelId, enabled}: Props) => {
    const {formatMessage} = useIntl();
    const serverUrl = useServerUrl();

    const toggleCalls = useCallback(async () => {
        enableChannelCalls(serverUrl, channelId, !enabled);
    }, [serverUrl, channelId, enabled]);

    const [tryOnPress, msgPostfix] = useTryCallsFunction(toggleCalls);

    const disableText = formatMessage({id: 'mobile.calls_disable', defaultMessage: 'Disable calls'});
    const enableText = formatMessage({id: 'mobile.calls_enable', defaultMessage: 'Enable calls'});

    return (
        <OptionItem
            action={preventDoubleTap(tryOnPress)}
            label={(enabled ? disableText : enableText) + msgPostfix}
            icon='phone-outline'
            type='default'
            testID='channel_info.options.enable_disable_calls.option'
        />
    );
};

export default ChannelInfoEnableCalls;


text:
/*
* WebTemplate 1.0
* Luca Vercelli 2017
*
*/
package com.example.myapp.login.eesecurity;

import java.io.IOException;
import java.util.Base64;
import java.util.Map;

import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import javax.security.auth.message.callback.GroupPrincipalCallback;
import javax.security.auth.message.module.ServerAuthModule;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static javax.security.auth.message.AuthStatus.*;

/**
 * Java EE Security login module, for JASPIC (i.e. custom) login. This is the actual
 * Server Authentication Module AKA SAM. Currently not used.
 *
 * @see https://dzone.com/refcardz/getting-started-java-ee,
 *      http://arjan-tijms.omnifaces.org/2012/11/implementing-container-authentication.html,
 *      https://github.com/javaee/security-examples
 *      https://blogs.oracle.com/enterprisetechtips/adding-authentication-mechanisms-to-the-glassfish-servlet-container
 *
 */
public class MyServerAuthModule implements ServerAuthModule {

	private CallbackHandler handler;

	private Class<?>[] supportedMessageTypes = new Class[] { HttpServletRequest.class, HttpServletResponse.class };

	/**
	 * Called by container at startup
	 */
	@Override
	public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler,
			@SuppressWarnings("rawtypes") Map options) throws AuthException {

		this.handler = handler;
	}

	/**
	 * Called by container before each request? Should return SUCCESS or
	 * FAILURE.
	 */
	@Override
	public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
			throws AuthException {

		final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();

		// final String[] credentials = getBasicAuthCredentials(request);
		final String[] credentials = getFormCredentials(request);

		final String username = credentials[0];
		final String password = credentials[1];

		// Should we really check auth here? or handler.handle() does that?
		if (!"snoopy".equals(username) || !"woodst0ck".equals(password)) {
			return FAILURE;
		}

		CallerPrincipalCallback callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, username);

		GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject,
				new String[] { "users" });
		try {

			// Communicate the details of the authenticated user to the
			// container. In many cases the handler will just store the details
			// and the container will actually handle the login after we return
			// from this method.
			handler.handle(new Callback[] { callerPrincipalCallback, groupPrincipalCallback });

		} catch (IOException | UnsupportedCallbackException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * A compliant implementation should return HttpServletRequest and
	 * HttpServletResponse, so the delegation class {@link ServerAuthContext}
	 * can choose the right SAM to delegate to. In this example there is only
	 * one SAM and thus the return value actually doesn't matter here.
	 */
	@Override
	public Class<?>[] getSupportedMessageTypes() {
		return supportedMessageTypes;
	}

	/**
	 * Get credentials from HTTP Basic Authentication. I don't like that.
	 *
	 * @return username and password
	 */
	protected String[] getBasicAuthCredentials(HttpServletRequest request) {
		final String header = request.getHeader("Authorization");
		final byte[] decoded = Base64.getDecoder().decode(header.replace("Basic ", ""));
		return new String(decoded).split(":");
	}

	/**
	 * Get credentials from a custom login form.
	 *
	 * @return username and password
	 */
	protected String[] getFormCredentials(HttpServletRequest request) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		return new String[] { username, password };
	}

	/**
	 * This method will be called after the last Filter or Servlet in the
	 * request has been invoked. WebLogic 12c calls this before Servlet is
	 * called, Geronimo v3 after, JBoss EAP 6 and GlassFish 3.1.2.2 don't call
	 * this at all. WebLogic (seemingly) only continues if SEND_SUCCESS is
	 * returned, Geronimo completely ignores return value.
	 */
	@Override
	public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {
		return SEND_SUCCESS;
	}

	/**
	 * This method will be called when HttpServletRequest#logout is explicitly
	 * called
	 */
	@Override
	public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException {
		if (subject != null) {
			subject.getPrincipals().clear();
		}
	}
}


text:
name: "🚀 Feature Request"
about: "I have a suggestion (and may want to implement it!)"

---

<!--
IMPORTANT: Feature requests on this GitHub issue tracker are only accepted in case they have been approved by a core developer or contain extensive argumentation and directions for implementation. For all other feature requests, ideas and feedback please post in the Flarum Community: https://discuss.flarum.org/t/feedback.
-->

## Feature Request

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. eg. I have an issue when [...]

**Describe the solution you'd like**
A detailed description of your proposed solution. Include:
- How the feature would work/behave
- Any potential drawbacks
- Maybe a screenshot, design, or example code

**Justify why this feature belongs in Flarum's core, rather than in a third-party extension**
Consider who this change will be useful to – most Flarum forums, or just a few?

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.


text:
'use strict';

var utils = require('radiodan-client').utils,
    playlistInfo = function(radio, options) {
      return radio.sendCommands([['playlistinfo']])
        .then(function(response) {
          return formatResponse(radio, response);
        });
    };

playlistInfo.formatResponse = formatResponse;

module.exports = playlistInfo;

function formatResponse(radio, playlistInfo) {
  var playlistArray = radio.formatResponse(playlistInfo, true),
      playlist      = formatPlaylist(playlistArray);

  return utils.promise.resolve(playlist);
}

function formatPlaylist(playlist) {
  var output = [],
      playlistItem = {};

  playlist.forEach(function(line) {
    var key = line[0], value = line[1];

    if(key == 'file' && playlistItem.hasOwnProperty('file')) {
      output.push(playlistItem);
      playlistItem = {};
    }

    playlistItem[key] = value;
  });

  // If any properties have been added to item
  if( Object.keys(playlistItem).length > 0 ) {
    output.push(playlistItem);
  }

  return output;
}


text:
import random

def create_number():
    number = random.randint(0, 99)
    return number

def make_prediction():
    return input("Guess the number: ")

def check(guess, number):
    if guess > number:
        print("Lower")
    elif guess < number:
        print("Higher")
    return guess == number

def program():
    number = create_number()
    numberoftrials = 0
    while numberoftrials <= 10:
        guess = make_prediction()

        try:
            if check(int(guess), number):
                print("Congratulations you found it. Number of trials: {}".format(numberoftrials))
                break
            else:
                numberoftrials += 1

        except ValueError:
            print("Prediction must be number.")

        except:
            print("Something that should not give an error gave an error.")

    if numberoftrials > 10:

        print("Your predictions were wrong. Number was {}. Sorry :(".format(number))

program()


text:
Fabricator(:user_avatar) do
  user
end


text:
Original Ping Pong game you all know and love!

**WARNING THIS IS HACKERY CODE. DO NOT TRY LEARNING FROM THIS. THIS WAS MADE IN 15 MINUTES FOR FUN IF YOU WOULD LIKE ME TO WRITE A PROPER VERSION OF THIS PLEASE TELL ME**
**not all the code is mine**
I do not own these songs. they all belong to their original owners which are listed below in order of songs:

1. Alan Walker - Spectre [NCS Release] 0:00-3:44
2. Axwell - Ingrosso - More Than You Know 3:44-7:00
3. Ed Sheeran - Shape Of You 7:01-10:54
4. Ed Sheeran - Galway Girl 10:55-13:40
5. Jonas Blue - Mama ft. William Singe 13:41-16:38
6. Niall Horan - Slow Hands (Lyric Video) 16:40-19:48
7. Spektrem - Shine (Original Mix) 19:57-24:13


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>HBase 0.98.8-hadoop2 Reference Package org.apache.hadoop.hbase.ipc</title>
		<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="style" />

        	org.apache.hadoop.hbase.ipc

Classes

            	FaultyTestDelayedImplementation

            	ListAppender

            	MetricsHBaseServerWrapperStub

            	PBServerImpl

            	TestBufferChain

            	TestCallRunner

            	TestDelayedImplementation

            	TestDelayedRpc

            	TestHBaseClient

            	TestIPC

            	TestIPCUtil

            	TestPayloadCarryingRpcController

            	TestProtoBufRpc

            	TestRpcMetrics

            	TestRpcServer

            	TestSimpleRpcScheduler

            	TestThread


text:
#include "MengeCore/Agents/SimulatorInterface.h"

#include "MengeCore/Agents/Elevations/ElevationFlat.h"
#include "MengeCore/Agents/Obstacle.h"
#include "MengeCore/Agents/SCBWriter.h"
#include "MengeCore/Agents/SpatialQueries/SpatialQuery.h"
#include "MengeCore/BFSM/FSM.h"
#include "MengeCore/Core.h"

namespace Menge {

namespace Agents {

////////////////////////////////////////////////////////////////////////////
//      Implementation of SimulatorInterface
////////////////////////////////////////////////////////////////

float SimulatorInterface::LOGICAL_TIME_STEP = 0.1f;

float SimulatorInterface::TIME_STEP = 0.1f;

size_t SimulatorInterface::SUB_STEPS = 0;

////////////////////////////////////////////////////////////////////////////

SimulatorInterface::SimulatorInterface()
    : XMLSimulatorBase(),
      _globalTime(0.f),
      _elevation(0x0),
      _spatialQuery(0x0),
      _fsm(0x0),
      _scbWriter(0x0),
      _isRunning(true),
      _maxDuration(100.f) {}

////////////////////////////////////////////////////////////////////////////

SimulatorInterface::~SimulatorInterface() {
  if (_fsm) delete _fsm;
  if (_spatialQuery != 0x0) _spatialQuery->destroy();
  if (_elevation) _elevation->destroy();
}

////////////////////////////////////////////////////////////////////////////

void SimulatorInterface::setBFSM(BFSM::FSM* fsm) { _fsm = fsm; }

////////////////////////////////////////////////////////////////////////////

bool SimulatorInterface::step() {
  const int agtCount = static_cast<int>(getNumAgents());
  if (_isRunning) {
    if (_scbWriter) _scbWriter->writeFrame(_fsm);
    if (_globalTime >= _maxDuration) {
      _isRunning = false;
    } else {
      for (size_t i = 0; i <= SUB_STEPS; ++i) {
        try {
          // TODO: doStep for FSM is a *bad* name; it should be "evaluate".
          _isRunning = !_fsm->doStep();
          doStep();
          _fsm->doTasks();
          _fsm->moveGoals(TIME_STEP);
        } catch (BFSM::FSMFatalException& e) {
          logger << Logger::ERR_MSG << "Error in updating the finite state ";
          logger << "machine -- stopping!\n";
          logger << "\t" << e.what() << "\n";
          _isRunning = false;
        }
      }
    }
  }
  return _isRunning;
}

////////////////////////////////////////////////////////////////////////////

float SimulatorInterface::getElevation(const BaseAgent* agent) const {
  return _elevation->getElevation(agent);
}

////////////////////////////////////////////////////////////////////////////

float SimulatorInterface::getElevation(const Vector2& point) const {
  return _elevation->getElevation(point);
}

////////////////////////////////////////////////////////////////////////////

void SimulatorInterface::setElevationInstance(Elevation* elevation) {
  assert(_elevation == 0x0 && "Trying to set the elevation that already exists");
  _elevation = elevation;
}

////////////////////////////////////////////////////////////////

void SimulatorInterface::setSpatialQuery(SpatialQuery* spatialQuery) {
  assert(_spatialQuery == 0x0 && "Trying to set the spatial query when one already exists");
  _spatialQuery = spatialQuery;
}

////////////////////////////////////////////////////////////////

void SimulatorInterface::finalize() {
  if (_fsm == 0x0) throw BFSM::FSMFatalException("No BFSM defined for simulation.");
  if (_elevation == 0x0) {
    logger << Logger::WARN_MSG
           << "No elevation implementation specified.  "
              "Using \"flat\" implementation.";
    _elevation = new FlatElevation();
    Menge::ELEVATION = _elevation;
  }
}

////////////////////////////////////////////////////////////////

bool SimulatorInterface::setOutput(const std::string& outFileName, const std::string& scbVersion) {
  try {
    _scbWriter = new SCBWriter(outFileName, scbVersion, this);
    return true;
  } catch (SCBFileException) {
    logger << Logger::WARN_MSG << "Error preparing output trajectory file: ";
    logger << outFileName << ".";
    return false;
  }
}

////////////////////////////////////////////////////////////////////////////

}  // namespace Agents
}  // namespace Menge


text:
/*------------------------------------------------------------------------
 * filename - rules.h
 *
 *      Standard rules for C
 *-----------------------------------------------------------------------*/

/*[]------------------------------------------------------------[]*/
/*|                                                              |*/
/*|     C/C++ Run Time Library - Version 4.0                     |*/
/*|                                                              |*/
/*|                                                              |*/
/*|     Copyright (c) 1987, 1991 by Borland International        |*/
/*|     All Rights Reserved.                                     |*/
/*|                                                              |*/
/*[]------------------------------------------------------------[]*/

#ifdef __STDC__
#define _Cdecl
#else
#define _Cdecl  cdecl
#endif

#ifndef __PAS__
#define _CType _Cdecl
#else
#define _CType pascal
#endif

/*      Precise types for portability and clarity of intent.

- chars are for strings or text (16 bits for Oriental or video buffers)
- ordinals are for indexes and offsets
- cardinals count how many of something
- integers can be negative
- bitsets are for bits, unknown patterns, and binary trickery
*/

typedef enum { false, true }   booleanT;
typedef unsigned char   boolean;

typedef signed   char   int8;
typedef char            char8;
typedef unsigned char   card8;
typedef unsigned char   ord8;
typedef unsigned char   bits8;

typedef short           int16;
typedef unsigned short  char16;
typedef unsigned short  card16;
typedef unsigned short  ord16;
typedef unsigned short  bits16;

typedef long            int32;
typedef unsigned long   card32;
typedef unsigned long   ord32;
typedef unsigned long   bits32;

typedef short   status;                 /* >0 = OK, minus is error/failure  */
typedef short   handle;                 /* 0..19 are files, -1 = failure    */
typedef unsigned short  keyval;         /* key code, including special keys */

#ifndef MIN
#   define MIN(a,b)  ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX
#   define MAX(a,b)  ((a) > (b) ? (a) : (b))
#endif
#ifndef NULL
#   define NULL ((void *)0)
#endif

#define O_WP    "w+"
#define O_WPB   "w+b"
#define O_RPB   "r+b"


text:
package psyco;

import com.google.common.collect.Lists;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by lipeng on 15/8/25.
 */
public class JDBCInfo {

    private String DB_URL;
    private String DB_USER;
    private String DB_PASSWORD;
    public Connection connection;
    public DatabaseMetaData databaseMetaData;

    public JDBCInfo(String DB_URL, String DB_USER, String DB_PASSWORD) {
        this.DB_URL = DB_URL;
        this.DB_USER = DB_USER;
        this.DB_PASSWORD = DB_PASSWORD;
    }

    public void init() throws Exception {
        connection = getConnection(DB_URL, DB_USER, DB_PASSWORD);
        databaseMetaData = connection.getMetaData();
    }

    Connection getConnection(String URL, String USER, String PASS) throws SQLException {
        return DriverManager.getConnection(URL, USER, PASS);
    }

    public List<String> getTablesNames() {
        List<String> re = new LinkedList<>();
        try {
            ResultSet result = databaseMetaData.getTables(null, null, null, new String[]{"TABLE"});
            while (result.next()) {
                re.add(result.getString(3));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return re;
    }

    public List<List<String>> getTable(String table) {
        List<List<String>> re = Lists.newLinkedList();
        try {
            ResultSet primaryKeys = databaseMetaData.getPrimaryKeys(null, null, table);
            String pk = primaryKeys.next() ? primaryKeys.getString("COLUMN_NAME") : null;
            ResultSet resultSet = databaseMetaData.getColumns(null, null, table, null);
            while (resultSet.next()) {
                re.add(Lists.newArrayList(
                        resultSet.getString("COLUMN_NAME"),
                        resultSet.getString("TYPE_NAME"),
                        String.valueOf(resultSet.getInt("COLUMN_SIZE")),
                        String.valueOf(Objects.equals(pk, resultSet.getString("COLUMN_NAME"))),
                        /*not used*/
                        String.valueOf(resultSet.getInt("NULLABLE")),
                        resultSet.getString("TABLE_SCHEM")
                ));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return re;
    }

    public Map<String, List<List<String>>> getTables() {
        return getTablesNames().stream().collect(Collectors.toMap((String t) -> t, (String e) -> getTable(e)));
    }

    @Deprecated
    public void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("close jdbc connection ....");
        if (connection != null) {
            connection.close();
        }
        super.finalize();
    }

}


text:
import { IMaterial } from "../material";

export interface IVideo extends IMaterial {
    url: string;
}


text:
module TypeScript {
    export module CompilerDiagnostics {
        export var debug = false;
        export interface IDiagnosticWriter {
            Alert(output: string): void;
        }

        export var diagnosticWriter: IDiagnosticWriter = null;

        export var analysisPass: number = 0;

        export function Alert(output: string) {
            if (diagnosticWriter) {
                diagnosticWriter.Alert(output);
            }
        }

        export function debugPrint(s: string) {
            if (debug) {
                Alert(s);
            }
        }

        export function assert(condition: boolean, s: string) {
            if (debug) {
                if (!condition) {
                    Alert(s);
                }
            }
        }

    }

    export interface ILogger {
        information(): boolean;
        debug(): boolean;
        warning(): boolean;
        error(): boolean;
        fatal(): boolean;
        log(s: string): void;
    }

    export class NullLogger implements ILogger {
        public information(): boolean { return false; }
        public debug(): boolean { return false; }
        public warning(): boolean { return false; }
        public error(): boolean { return false; }
        public fatal(): boolean { return false; }
        public log(s: string): void {
        }
    }

    export function timeFunction(logger: ILogger, funcDescription: string, func: () => any): any {
        var start = (new Date()).getTime();
        var result = func();
        var end = (new Date()).getTime();
        logger.log(funcDescription + " completed in " + (end - start) + " msec");
        return result;
    }
}


text:
<!DOCTYPE html>
<html class="reftest-wait">
<title>WebVTT rendering, set align start and the cue contains two lines with different writing directions</title>
<link rel="match" href="start_alignment-ref.html">
<style>
html { overflow:hidden }
body { margin:0 }
::cue {
    font-family: sans-serif;
    color: green;
}
</style>
<script src="/common/reftest-wait.js"></script>
<video width="320" height="180" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();">
    <source src="/media/white.webm" type="video/webm">
    <source src="/media/white.mp4" type="video/mp4">
    <track src="../support/start_alignment.vtt" default>
</video>
</html>


text:
package com.xnx3.j2ee.service;

import java.util.List;
import com.xnx3.j2ee.entity.FriendLog;

/**
 * 好友纪录
 * @author 管雷鸣
 *
 */
public interface FriendLogService {

	public void save(FriendLog transientInstance);

	public void delete(FriendLog persistentInstance);

	public FriendLog findById(java.lang.Integer id);

	public List<FriendLog> findByExample(FriendLog instance);

	public List findByProperty(String propertyName, Object value);

	public List<FriendLog> findBySelf(Object self);

	public List<FriendLog> findByOther(Object other);

	public List<FriendLog> findByTime(Object time);

	public List<FriendLog> findByState(Object state);

	public List<FriendLog> findByIp(Object ip);

	public List findAll();

	public FriendLog merge(FriendLog detachedInstance);

	public void attachDirty(FriendLog instance);

	public void attachClean(FriendLog instance);

}


text:
import numpy as np

from ._op import OpRunUnaryNum

class HardSigmoid(OpRunUnaryNum):
    def _run(self, x, alpha=None, beta=None):  # type: ignore
        alpha = alpha or self.alpha  # type: ignore
        beta = beta or self.beta  # type: ignore
        y = np.maximum(0, np.minimum(1, x * alpha + beta))
        return (y,)


text:
import { CompanyService } from './../../services/company.service';
import { Company, Location } from './../../model/company';
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'my-company',
    templateUrl: 'company.component.html'
})

export class CompanyComponent implements OnInit {
    company: Company;
    location: Location;
    success: boolean;
    error: boolean;
    isUpdate: boolean;
    companies: Company[];
    textBtn: string;

    constructor(private companyService: CompanyService) {}

    getCompanies() {
        this.companyService.get()
        .map(data => {
            this.companies = data.data;
        })
        .subscribe();
        this.textBtn = "Create";
        this.company = new Company();
        this.location = new Location();
    }

    ngOnInit(): void {
        this.getCompanies();
    }

    save(form): void {
        this.company.locations = new Array<Location>();
        this.company.locations.push(this.location);
        if (this.isUpdate) {
            this.companyService.update(this.company)
            .subscribe(response => {
                },
            error => {
                this.error = true;
                console.log(error);
            });
        } else {
            this.companyService.create(this.company)
            .subscribe(response => {
                },
            error => {
                this.error = true;
                console.log(error);
            });
        }
        this.success = true;
        this.getCompanies();
        form.reset();
    }

    select(company: Company): void{
        this.textBtn = "Update";
        this.company = company;
        this.location = company.locations[0];
        this.isUpdate = true;

    }

}