text:
package com.intellij.spellchecker.settings;

import com.intellij.ide.DataManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.ex.Settings;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.profile.codeInspection.ui.ErrorsConfigurable;
import com.intellij.spellchecker.SpellCheckerManager;
import com.intellij.spellchecker.dictionary.EditableDictionary;
import com.intellij.spellchecker.inspections.SpellCheckingInspection;
import com.intellij.spellchecker.util.SPFileUtil;
import com.intellij.spellchecker.util.SpellCheckerBundle;
import com.intellij.spellchecker.util.Strings;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.Consumer;
import consulo.disposer.Disposable;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.util.List;
import java.util.*;

public class SpellCheckerSettingsPane extends JPanel implements Disposable
{
	private OptionalChooserComponent<String> myOptionalChooserComponent;
	private PathsChooserComponent myPathsChooserComponent;
	private final List<Pair<String, Boolean>> myAllDictionaries = new ArrayList<Pair<String, Boolean>>();
	private final List<String> myDictionariesFolders = new ArrayList<String>();
	private final List<String> myRemovedDictionaries = new ArrayList<String>();
	private final WordsPanel myWordsPanel;
	private final SpellCheckerManager myManager;
	private final SpellCheckerSettings mySpellCheckerSettings;

	public SpellCheckerSettingsPane(SpellCheckerSettings settings, final Project project)
	{
		super(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, true));

		mySpellCheckerSettings = settings;
		myManager = SpellCheckerManager.getInstance(project);
		HyperlinkLabel link = new HyperlinkLabel(SpellCheckerBundle.message("link.to.inspection.settings"));
		link.addHyperlinkListener(new HyperlinkListener()
		{
			@Override
			public void hyperlinkUpdate(final HyperlinkEvent e)
			{
				if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
				{
					final Settings optionsEditor = DataManager.getInstance().getDataContext().getData(Settings.KEY);
					if(optionsEditor != null)
					{
						final ErrorsConfigurable errorsConfigurable = optionsEditor.findConfigurable(ErrorsConfigurable.class);
						if(errorsConfigurable != null)
						{
							optionsEditor.clearSearchAndSelect(errorsConfigurable).doWhenDone(new Runnable()
							{
								@Override
								public void run()
								{
									errorsConfigurable.selectInspectionTool(SpellCheckingInspection.SPELL_CHECKING_INSPECTION_TOOL_NAME);
								}
							});
						}
					}
				}
			}
		});

		JPanel linkContainer = new JPanel(new BorderLayout());
		linkContainer.setPreferredSize(new Dimension(24, 38));
		linkContainer.add(link, BorderLayout.CENTER);
		add(linkContainer);

		// Fill in all the dictionaries folders (not implemented yet) and enabled dictionaries
		fillAllDictionaries();

		myPathsChooserComponent = new PathsChooserComponent(myDictionariesFolders, new PathsChooserComponent.PathProcessor()
		{
			@Override
			public boolean addPath(List<String> paths, String path)
			{
				if(paths.contains(path))
				{
					final String title = SpellCheckerBundle.message("add.directory.title");
					final String msg = SpellCheckerBundle.message("directory.is.already.included");
					Messages.showErrorDialog(SpellCheckerSettingsPane.this, msg, title);
					return false;
				}
				paths.add(path);

				final ArrayList<Pair<String, Boolean>> currentDictionaries = myOptionalChooserComponent.getCurrentModel();
				SPFileUtil.processFilesRecursively(path, new Consumer<String>()
				{
					@Override
					public void consume(final String s)
					{
						currentDictionaries.add(Pair.create(s, true));
					}
				});
				myOptionalChooserComponent.refresh();
				return true;
			}

			@Override
			public boolean removePath(List<String> paths, String path)
			{
				if(paths.remove(path))
				{
					final ArrayList<Pair<String, Boolean>> result = new ArrayList<Pair<String, Boolean>>();
					final ArrayList<Pair<String, Boolean>> currentDictionaries = myOptionalChooserComponent.getCurrentModel();
					for(Pair<String, Boolean> pair : currentDictionaries)
					{
						if(!pair.first.startsWith(FileUtil.toSystemDependentName(path)))
						{
							result.add(pair);
						}
						else
						{
							myRemovedDictionaries.add(pair.first);
						}
					}
					currentDictionaries.clear();
					currentDictionaries.addAll(result);
					myOptionalChooserComponent.refresh();
					return true;
				}
				return false;
			}
		}, project);

		myPathsChooserComponent.getEmptyText().setText(SpellCheckerBundle.message("no.custom.folders"));

		myOptionalChooserComponent = new OptionalChooserComponent<String>(myAllDictionaries)
		{
			@Override
			public JCheckBox createCheckBox(String path, boolean checked)
			{
				if(isUserDictionary(path))
				{
					path = FileUtil.toSystemIndependentName(path);
					final int i = path.lastIndexOf('/');
					if(i != -1)
					{
						final String name = path.substring(i + 1);
						return new JCheckBox("[user] " + name, checked);
					}
				}
				return new JCheckBox("[bundled] " + FileUtil.toSystemDependentName(path), checked);
			}
		};

		myWordsPanel = new WordsPanel(myManager);

		TabbedPaneWrapper tabbedPaneWrapper = new TabbedPaneWrapper(this);
		tabbedPaneWrapper.addTab("Accepted Words", myWordsPanel);

		JPanel secondPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, true));

		JPanel customDictionariesPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, true));
		customDictionariesPanel.setBorder(IdeBorderFactory.createTitledBorder(SpellCheckerBundle.message("add.directory.title"), false));
		customDictionariesPanel.add(new JBLabel(SpellCheckerBundle.message("add.directory.description")));
		customDictionariesPanel.add(myPathsChooserComponent.getContentPane());
		secondPanel.add(customDictionariesPanel);

		myOptionalChooserComponent.getEmptyText().setText(SpellCheckerBundle.message("no.dictionaries"));
		JPanel dictionariesPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, true));
		dictionariesPanel.setBorder(IdeBorderFactory.createTitledBorder(SpellCheckerBundle.message("dictionaries.panel.title"), false));
		dictionariesPanel.add(new JBLabel(SpellCheckerBundle.message("dictionaries.panel.description")));
		dictionariesPanel.add(ScrollPaneFactory.createScrollPane(myOptionalChooserComponent.getContentPane()));
		secondPanel.add(dictionariesPanel);

		tabbedPaneWrapper.addTab("Dictionaries", secondPanel);

		add(tabbedPaneWrapper.getComponent());
	}

	public boolean isModified()
	{
		return myWordsPanel.isModified() || myOptionalChooserComponent.isModified() || myPathsChooserComponent.isModified();
	}

	public void apply() throws ConfigurationException
	{
		if(myWordsPanel.isModified())
		{
			myManager.updateUserDictionary(myWordsPanel.getWords());
		}
		if(!myOptionalChooserComponent.isModified() && !myPathsChooserComponent.isModified())
		{
			return;
		}

		myOptionalChooserComponent.apply();
		myPathsChooserComponent.apply();
		mySpellCheckerSettings.setDictionaryFoldersPaths(myPathsChooserComponent.getValues());

		final HashSet<String> disabledDictionaries = new HashSet<String>();
		final HashSet<String> bundledDisabledDictionaries = new HashSet<String>();
		for(Pair<String, Boolean> pair : myAllDictionaries)
		{
			if(!pair.second)
			{
				final String scriptPath = pair.first;
				if(isUserDictionary(scriptPath))
				{
					disabledDictionaries.add(scriptPath);
				}
				else
				{
					bundledDisabledDictionaries.add(scriptPath);
				}
			}

		}
		mySpellCheckerSettings.setDisabledDictionariesPaths(disabledDictionaries);
		mySpellCheckerSettings.setBundledDisabledDictionariesPaths(bundledDisabledDictionaries);

		myManager.updateBundledDictionaries(myRemovedDictionaries);
	}

	private boolean isUserDictionary(final String dictionary)
	{
		boolean isUserDictionary = false;
		for(String dictionaryFolder : myPathsChooserComponent.getValues())
		{
			if(FileUtil.toSystemIndependentName(dictionary).startsWith(dictionaryFolder))
			{
				isUserDictionary = true;
				break;
			}
		}
		return isUserDictionary;

	}

	public void reset()
	{
		myPathsChooserComponent.reset();
		fillAllDictionaries();
		myOptionalChooserComponent.reset();
		myRemovedDictionaries.clear();
	}

	private void fillAllDictionaries()
	{
		myDictionariesFolders.clear();
		myDictionariesFolders.addAll(mySpellCheckerSettings.getDictionaryFoldersPaths());
		myAllDictionaries.clear();
		for(String dictionary : SpellCheckerManager.getBundledDictionaries())
		{
			myAllDictionaries.add(Pair.create(dictionary, !mySpellCheckerSettings.getBundledDisabledDictionariesPaths().contains(dictionary)));
		}

		// user
		//todo [shkate]: refactoring  - SpellCheckerManager contains the same code withing reloadConfiguration()
		final Set<String> disabledDictionaries = mySpellCheckerSettings.getDisabledDictionariesPaths();
		for(String folder : myDictionariesFolders)
		{
			SPFileUtil.processFilesRecursively(folder, new Consumer<String>()
			{
				@Override
				public void consume(final String s)
				{
					myAllDictionaries.add(Pair.create(s, !disabledDictionaries.contains(s)));
				}
			});
		}
	}

	@Override
	public void dispose()
	{
		if(myWordsPanel != null)
		{
			myWordsPanel.dispose();
		}
	}

	public static final class WordDescriber
	{
		private final EditableDictionary dictionary;

		public WordDescriber(EditableDictionary dictionary)
		{
			this.dictionary = dictionary;
		}

		@Nonnull
		public List<String> process()
		{
			if(this.dictionary == null)
			{
				return new ArrayList<String>();
			}
			Set<String> words = this.dictionary.getEditableWords();
			if(words == null)
			{
				return new ArrayList<String>();
			}
			List<String> result = new ArrayList<String>();
			for(String word : words)
			{
				result.add(word);
			}
			Collections.sort(result);
			return result;
		}
	}

	private static final class WordsPanel extends AddDeleteListPanel<String> implements Disposable
	{
		private final SpellCheckerManager manager;

		private WordsPanel(SpellCheckerManager manager)
		{
			super(null, new WordDescriber(manager.getUserDictionary()).process());
			this.manager = manager;
			getEmptyText().setText(SpellCheckerBundle.message("no.words"));
		}

		@Override
		protected String findItemToAdd()
		{
			String word = Messages.showInputDialog(SpellCheckerBundle.message("enter.simple.word"), SpellCheckerBundle.message("add.new.word"),
					null);
			if(word == null)
			{
				return null;
			}
			else
			{
				word = word.trim();
			}

			if(Strings.isMixedCase(word))
			{
				Messages.showWarningDialog(SpellCheckerBundle.message("entered.word.0.is.mixed.cased.you.must.enter.simple.word", word),
						SpellCheckerBundle.message("add.new.word"));
				return null;
			}
			if(!manager.hasProblem(word))
			{
				Messages.showWarningDialog(SpellCheckerBundle.message("entered.word.0.is.correct.you.no.need.to.add.this.in.list", word),
						SpellCheckerBundle.message("add.new.word"));
				return null;
			}
			return word;
		}

		@Override
		public void dispose()
		{
			myListModel.removeAllElements();
		}

		@Nullable
		public List<String> getWords()
		{
			Object[] pairs = getListItems();
			if(pairs == null)
			{
				return null;
			}
			List<String> words = new ArrayList<String>();
			for(Object pair : pairs)
			{
				words.add(pair.toString());
			}
			return words;
		}

		public boolean isModified()
		{
			List<String> newWords = getWords();
			Set<String> words = manager.getUserDictionary().getEditableWords();
			if(words == null && newWords == null)
			{
				return false;
			}
			if(words == null || newWords == null || newWords.size() != words.size())
			{
				return true;
			}
			return !(words.containsAll(newWords) && newWords.containsAll(words));
		}
	}

}


text:
<?xml version="1.0"?>

<resource xmlns="http://www.wyona.org/yanel/1.0"
  name="redirect"
  namespace="http://www.wyona.org/yanel/resource/1.0.2"
  class="org.wyona.yanel.impl.resources.redirect.RedirectResourceV102"
  >
<description>
Redirect resource, whereas redirects can also be based on user profile
</description>

<rtd>
  <!-- INFO: Default redirect, which is mandatory! Without leading slash it will be a relative redirect and with leading slash an absolute redirect. Also see http://en.wikipedia.org/wiki/HTTP_location -->
  <property name="href"/>

  <!-- INFO: Optional, whereas default is 307 (instead 301), such that the redirect is always checked, in case the redirect location should change in the future  -->
  <property name="status-code"/>

<!-- INFO: The element 'personalized' is optional and was introduced with version 1.0.2, whereas the domain will be read from the realms configuration attribute 'user-tracking-domain-id' or when not set, then the realm id will be used -->
<!--
  <yanel:custom-config xmlns:rd="http://www.wyona.org/yanel/resource/redirect-resource/1.0">
    <rd:personalized boost-service-url="http://localhost:9080/boost/api" boost-api-key="28b1e2ccc6804582208360370c73d4ad1da4b5f0ab8faf322dc65296fe8b68a5" href="@LANG/index.html" language-prefix-position="3" connection-timeout="500" socket-timeout="1000" limit="50"/>

    <rd:user name="bob" href="bob/index.html"/>
    <rd:user name="alice" href="alice/index.html"/>

    <rd:language code="de" device="web.xml:mobile-devices" href="de/index_m.html"/>
    <rd:language code="de" if-logged-in="true" href="de/willkommen.html"/>
    <rd:language code="de" href="de/index.html"/>

    <rd:language code="*" if-logged-in="true" href="en/welcome.html"/>
  </yanel:custom-config>
-->
</rtd>
</resource>

redpajama_set_name: RedPajamaGithub


text:
import { default as AdvisersTypeahead } from './RoutedAdvisersTypeahead/Filter'
import { default as CheckboxGroup } from './RoutedCheckboxGroupField'
import { default as Date } from './RoutedDateField/Filter'
import { default as Input } from './RoutedInputField/Filter'
import { default as NumericRange } from './RoutedNumericRangeField/Filter'
import { default as Typeahead } from './RoutedTypeahead/Filter'
import { default as TeamsTypeahead } from './RoutedTeamsTypeahead/Filter'
import { default as AventriId } from './RoutedAventriIdField/Filter'

export default {
  AdvisersTypeahead,
  CheckboxGroup,
  Date,
  Input,
  NumericRange,
  Typeahead,
  TeamsTypeahead,
  AventriId,
}


text:
package org.spongepowered.api.event.entity.item;

import com.google.common.base.Predicate;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.Item;
import org.spongepowered.api.event.entity.AffectEntityEvent;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;

import java.util.List;

public interface AffectItemEvent extends AffectEntityEvent {

    @Override
    List<Item> getEntities();

    @Override
    List<Item> filterEntityLocations(Predicate<Location<World>> predicate);

    @Override
    List<Item> filterEntities(Predicate<Entity> predicate);
}


text:
package com.shard.session.app;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ModelController {

	@RequestMapping(value = "loginView")
	public ModelAndView customer() {
		return new ModelAndView("login", null);
	}
}


text:
namespace ppapi {
namespace host {
namespace {

base::WaitableEvent g_handler_completion(
    base::WaitableEvent::ResetPolicy::MANUAL,
    base::WaitableEvent::InitialState::NOT_SIGNALED);

enum TestMessageTypes {
  MSG1_TYPE = 1,
  MSG2_TYPE,
  MSG3_TYPE,
  REPLY_MSG1_TYPE,
  REPLY_MSG2_TYPE,
  REPLY_MSG3_TYPE,
};

// Dummy resource host which simply stores a copy of messages it handles.
// |SendReply| is overridden to store a copy of the outgoing message and the
// message loop on which it was sent.
class MyResourceHost : public ResourceHost {
 public:
  // Messages of type |msg_type| will be handled (simply by replying with a
  // message of type |reply_msg_type|).
  MyResourceHost(PpapiHost* host,
                 PP_Instance instance,
                 PP_Resource resource,
                 uint32_t msg_type,
                 uint32_t reply_msg_type)
      : ResourceHost(host, instance, resource),
        msg_type_(msg_type),
        reply_msg_type_(reply_msg_type),
        last_reply_task_runner_(nullptr) {}

  const IPC::Message& last_handled_msg() const { return last_handled_msg_; }
  const IPC::Message& last_reply_msg() const { return last_reply_msg_; }
  scoped_refptr<base::SingleThreadTaskRunner> last_reply_task_runner() const {
    return last_reply_task_runner_;
  }

  void AddMessageFilter(scoped_refptr<ResourceMessageFilter> filter) {
    AddFilter(filter);
  }

  int32_t OnResourceMessageReceived(const IPC::Message& msg,
                                    HostMessageContext* context) override {
    last_handled_msg_ = msg;
    if (msg.type() == msg_type_) {
      context->reply_msg = IPC::Message(0, reply_msg_type_,
                                        IPC::Message::PRIORITY_NORMAL);
      return PP_OK;
    }
    return PP_ERROR_FAILED;
  }

  void SendReply(const ReplyMessageContext& context,
                 const IPC::Message& msg) override {
    last_reply_msg_ = msg;
    last_reply_task_runner_ = base::ThreadTaskRunnerHandle::Get();
    g_handler_completion.Signal();
  }

 private:
  uint32_t msg_type_;
  uint32_t reply_msg_type_;

  IPC::Message last_handled_msg_;
  IPC::Message last_reply_msg_;
  scoped_refptr<base::SingleThreadTaskRunner> last_reply_task_runner_;
};

// Dummy message filter which simply stores a copy of messages it handles.
// The message loop on which the message is handled is also stored for checking
// later.
class MyResourceFilter : public ResourceMessageFilter {
 public:
  // Messages of type |msg_type| will be handled (simply by replying with a
  // message of type |reply_msg_type|). |io_thread| is the thread on which
  // replies should be sent. |bg_thread| is the thread on which the message
  // should be handled.
  MyResourceFilter(const base::Thread& io_thread,
                   const base::Thread& bg_thread,
                   uint32_t msg_type,
                   uint32_t reply_msg_type)
      : ResourceMessageFilter(io_thread.task_runner()),
        task_runner_(bg_thread.task_runner()),
        msg_type_(msg_type),
        reply_msg_type_(reply_msg_type) {}

  const IPC::Message& last_handled_msg() const { return last_handled_msg_; }
  scoped_refptr<base::SingleThreadTaskRunner> last_task_runner() const {
    return last_task_runner_;
  }

  scoped_refptr<base::SequencedTaskRunner> OverrideTaskRunnerForMessage(
      const IPC::Message& msg) override {
    if (msg.type() == msg_type_)
      return task_runner_;
    return nullptr;
  }

  int32_t OnResourceMessageReceived(
      const IPC::Message& msg,
      HostMessageContext* context) override {
    last_handled_msg_ = msg;
    last_task_runner_ = base::ThreadTaskRunnerHandle::Get();
    if (msg.type() == msg_type_) {
      context->reply_msg = IPC::Message(0, reply_msg_type_,
                                        IPC::Message::PRIORITY_NORMAL);
      return PP_OK;
    }
    return PP_ERROR_FAILED;
  }

 private:
  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  uint32_t msg_type_;
  uint32_t reply_msg_type_;

  IPC::Message last_handled_msg_;
  scoped_refptr<base::SingleThreadTaskRunner> last_task_runner_;
};

}  // namespace

class ResourceMessageFilterTest : public testing::Test {
 public:
  void TestHandleMessageImpl() {
    base::Thread io_thread("test_io_thread");
    ASSERT_TRUE(io_thread.Start());

    base::Thread bg_thread1("test_background_thread1");
    ASSERT_TRUE(bg_thread1.Start());
    scoped_refptr<MyResourceFilter> filter1 =
        new MyResourceFilter(io_thread, bg_thread1, MSG1_TYPE, REPLY_MSG1_TYPE);

    base::Thread bg_thread2("test_background_thread2");
    ASSERT_TRUE(bg_thread2.Start());
    scoped_refptr<MyResourceFilter> filter2 =
        new MyResourceFilter(io_thread, bg_thread2, MSG2_TYPE, REPLY_MSG2_TYPE);

    PP_Instance instance = 12345;
    PP_Resource resource = 67890;
    MyResourceHost host(nullptr, instance, resource, MSG3_TYPE,
                        REPLY_MSG3_TYPE);
    host.AddMessageFilter(filter1);
    host.AddMessageFilter(filter2);

    proxy::ResourceMessageCallParams params(resource, 1);
    params.set_has_callback();
    HostMessageContext context(params);
    IPC::Message message1(0, MSG1_TYPE, IPC::Message::PRIORITY_NORMAL);
    IPC::Message message2(0, MSG2_TYPE, IPC::Message::PRIORITY_NORMAL);
    IPC::Message message3(0, MSG3_TYPE, IPC::Message::PRIORITY_NORMAL);

    // Message 1 handled by the first filter.
    host.HandleMessage(message1, &context);
    g_handler_completion.Wait();
    EXPECT_EQ(filter1->last_handled_msg().type(), message1.type());
    EXPECT_EQ(filter1->last_task_runner(), bg_thread1.task_runner());
    EXPECT_EQ(host.last_reply_msg().type(),
              static_cast<uint32_t>(REPLY_MSG1_TYPE));
    EXPECT_EQ(host.last_reply_task_runner(), io_thread.task_runner());
    g_handler_completion.Reset();

    // Message 2 handled by the second filter.
    host.HandleMessage(message2, &context);
    g_handler_completion.Wait();
    EXPECT_EQ(filter2->last_handled_msg().type(), message2.type());
    EXPECT_EQ(filter2->last_task_runner(), bg_thread2.task_runner());
    EXPECT_EQ(host.last_reply_msg().type(),
              static_cast<uint32_t>(REPLY_MSG2_TYPE));
    EXPECT_EQ(host.last_reply_task_runner(), io_thread.task_runner());
    g_handler_completion.Reset();

    // Message 3 handled by the resource host.
    host.HandleMessage(message3, &context);
    EXPECT_EQ(host.last_handled_msg().type(), message3.type());
    EXPECT_EQ(host.last_reply_msg().type(),
              static_cast<uint32_t>(REPLY_MSG3_TYPE));

    io_thread.Stop();
    bg_thread1.Stop();
    bg_thread2.Stop();
  }
};

// Test that messages are filtered correctly and handlers are run on the correct
// threads.
TEST_F(ResourceMessageFilterTest, TestHandleMessage) {
  // ResourceMessageFilter instances need to be created on a thread with message
  // loop. Therefore, we create a message loop and run the testing logic as a
  // task on it.
  base::test::SingleThreadTaskEnvironment task_environment;

  // It should be safe to use base::Unretained() because the object won't be
  // destroyed before the task is run.
  task_environment.GetMainThreadTaskRunner()->PostTask(
      FROM_HERE,
      base::BindOnce(&ResourceMessageFilterTest::TestHandleMessageImpl,
                     base::Unretained(this)));

  base::RunLoop().RunUntilIdle();
}

}  // namespace proxy
}  // namespace ppapi


text:
package com.github.izhangzhihao.SpringMVCSeedProject.Model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "logging_event")

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Log implements Serializable {
    private static final long serialVersionUID = 468468487400228L;
    @Id
    @GeneratedValue(generator = "generator")
    @GenericGenerator(name = "generator", strategy = "increment")
    private Integer event_id;
    @Column(columnDefinition="MEDIUMTEXT")
    private String timestmp;
    @Column(columnDefinition="TEXT")
    private String formatted_message;
    private String logger_name;
    private String level_string;
    private String thread_name;
    private Short reference_flag;
    private String caller_filename;
    private String arg0;
    private String arg1;
    private String arg2;
    private String arg3;
    private String caller_class;
    private String caller_method;
    private String caller_line;
}


text:
from __future__ import absolute_import, unicode_literals

from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView

from django.contrib.auth.mixins import LoginRequiredMixin

from py_fitness.workout.forms import WorkoutForm
from py_fitness.workout.models import Workout

from .models import User

class UserDetailView(LoginRequiredMixin, DetailView):
    model = User
    # These next two lines tell the view to index lookups by username
    slug_field = 'username'
    slug_url_kwarg = 'username'

    def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data(**kwargs)

        if self.request.method == 'GET':
            context['form'] = WorkoutForm()

        return context

class UserRedirectView(LoginRequiredMixin, RedirectView):
    permanent = False

    def get_redirect_url(self):
        if self.request.user.is_authenticated:
            return reverse('workout:dashboard')
        else:
            return reverse('home')

class UserUpdateView(LoginRequiredMixin, UpdateView):

    fields = ['name', ]

    # we already imported User in the view code above, remember?
    model = User

    # send the user back to their own page after a successful update
    def get_success_url(self):
        return reverse('users:detail',
                       kwargs={'username': self.request.user.username})

    def get_object(self):
        # Only get the User record for the user making the request
        return User.objects.get(username=self.request.user.username)

class UserListView(LoginRequiredMixin, ListView):
    model = User
    # These next two lines tell the view to index lookups by username
    slug_field = 'username'
    slug_url_kwarg = 'username'


text:
window.onload = initAll;

function initAll()
{
    Clock();
}

function Clock()
{
	if (!document.layers && !document.all && !document.getElementById)
	return

	var Tiempo = new Date()

	var hora = Tiempo.getHours()
	var minutos = Tiempo.getMinutes()
	var segundos = Tiempo.getSeconds()
	var message = "Buenas noches, "

	var meridiano = "P.M."

	if (hora == 12)
	{
	    //message = "Buenas tardes, "
	}

	if (hora < 12)
	{
	    meridiano = "A.M."
	    //message = "Buenos dias, "
	}

	if (hora > 12)
	{
	    hora = hora - 12

	    if(hora < 7)
	    {
	        //message = "Buenas tardes, "
	    }
	}
	else
	{
	    if(hora == 12)
	    {
	        //message = "Buenas tardes, "
	    }
	}

	if (hora <= 9)
	hora = "0" + hora

	if (hora == 0)
	hora = 12

	if (minutos <= 9)
	minutos = "0" + minutos

	if (segundos <= 9)
	segundos = "0" + segundos

	var hora_digital = hora + ":" + minutos + ":" + segundos + " " + meridiano

	mostrar = "" + hora_digital + ""

	if (document.layers)
	{
		document.layers.reloj_digital.document.write(mostrar)
		document.layers.reloj_digital.document.close()

		//document.layers.saludos.document.write(message)
		//document.layers.saludos.document.close()
	}
	else
		if (document.all)
		{
			reloj_digital.innerHTML=mostrar
			//saludos.innerHTML=message
		}
		else
			if (document.getElementById)
				document.getElementById("reloj_digital").innerHTML=mostrar
				setTimeout("Clock()",1000)
}


text:
package anchorReward

import (
	"context"
	"testing"

	"github.com/smartystreets/goconvey/convey"
)

func TestAnchorRewardRewardConf(t *testing.T) {
	convey.Convey("RewardConf", t, func(ctx convey.C) {
		var (
			c  = context.Background()
			id = int64(0)
		)
		ctx.Convey("When everything gose positive", func(ctx convey.C) {
			res, err := d.RewardConf(c, id)
			ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
				ctx.So(err, convey.ShouldBeNil)
				ctx.So(res, convey.ShouldNotBeNil)
			})
		})
	})
}


text:
"""Tests for WorkerPreemptionHandler."""
import os
import random
import re
import signal
import sys
import time

from absl.testing import parameterized

# pylint:disable=g-direct-tensorflow-import

from tensorflow.python.distribute import collective_all_reduce_strategy
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.distribute import multi_process_runner
from tensorflow.python.distribute import multi_worker_test_base
from tensorflow.python.distribute import multi_worker_util
from tensorflow.python.distribute import test_util
from tensorflow.python.distribute.failure_handling import failure_handling
from tensorflow.python.distribute.failure_handling import gce_util
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import errors_impl
from tensorflow.python.module import module
from tensorflow.python.ops import variables as variables_lib
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training.tracking import util as tracking_util

mock = test.mock

CLUSTER_SIZE = 4
EPOCHS_TO_RUN = 15
STEPS_PER_EPOCH = 15

def _is_oss():
  """Returns whether the test is run under OSS."""
  return len(sys.argv) >= 1 and 'bazel' in sys.argv[0]

def _enable_coordination_service(cluster_spec):

  if context.context().coordination_service is None:
    coordination_service = 'standalone'
    coordinated_jobs = ['chief', 'worker']
    context.context().configure_coordination_service(
        service_type=coordination_service,
        service_leader=multi_worker_util.coordination_leader(
            cluster_spec),
        coordinated_jobs=coordinated_jobs)

class PreemptionCheckpointTest(test.TestCase, parameterized.TestCase):
  """Integration test for WorkerPreemptionHandler."""

  def _mwms_write_checkpoint_dir(self, checkpoint_dir, cluster_spec, task_type,
                                 task_id):
    dirpath = os.path.dirname(checkpoint_dir)
    base = os.path.basename(checkpoint_dir)
    if not multi_worker_util.is_chief(
        cluster_spec=cluster_spec, task_type=task_type, task_id=task_id):
      base_dirpath = 'workertemp_' + str(task_id)
      dirpath = os.path.join(dirpath, base_dirpath)
      gfile.MakeDirs(dirpath)
    return os.path.join(dirpath, base)

  def _maybe_trigger_a_preemption(self, training_started_event,
                                  trigger_it=False):
    if not training_started_event:
      return
    clear_events = [
        event for event in training_started_event if not event.is_set()
    ]
    if clear_events:
      if trigger_it:
        logging.info('Set preemption signal')
        clear_events[0].set()
      elif random.randrange(0, 9) > 6:
        clear_events[0].set()

  def worker_fn(self,
                checkpoint_dir,
                cluster_spec,
                training_started_event=None,
                raise_app_error_on_worker=None,
                termination_config=failure_handling.TerminationConfig()):

    _enable_coordination_service(cluster_spec)
    strategy = collective_all_reduce_strategy.CollectiveAllReduceStrategy()

    class Model(module.Module):

      def __init__(self):
        self.v = variables_lib.Variable(
            0.,
            synchronization=variables_lib.VariableSynchronization.ON_WRITE,
            aggregation=variables_lib.VariableAggregation.SUM)

      @def_function.function(input_signature=[])
      def __call__(self):
        return self.v.read_value()

    with mock.patch.object(gce_util, 'on_gcp', lambda: False):

      with strategy.scope():
        model = Model()
        # Named it fh_ckpt because it'd be better that the user have their
        # regular checkpoint separate from the checkpoint for
        # WorkerPreemptionHandler, since we will create CheckpointManager
        # to manage the checkpoint and only one CheckpointManager should be
        # active in a particular directory at a time.
        fh_ckpt = tracking_util.Checkpoint(model=model)

        worker_preemption_watcher = failure_handling.WorkerPreemptionHandler(
            strategy.cluster_resolver, fh_ckpt, checkpoint_dir,
            termination_config)

      def distributed_train_step(current_epoch, current_step):

        @def_function.function
        def train_step():
          if distribution_strategy_context.get_distribution_strategy(
          ).cluster_resolver.task_id == raise_app_error_on_worker:
            raise errors_impl.ResourceExhaustedError(
                node_def=None, op=None, message='Running out of resources')

          model.v.assign_add(constant_op.constant(1.))

        strategy.run(train_step)

        if current_step == STEPS_PER_EPOCH - 1:
          logging.info('epoch %d finished', current_epoch)

      logging.info('Restored training at %d',
                   worker_preemption_watcher.total_runs)
      for epoch in range(
          worker_preemption_watcher.total_runs // STEPS_PER_EPOCH,
          EPOCHS_TO_RUN):

        for step in range(
            worker_preemption_watcher.total_runs % STEPS_PER_EPOCH,
            STEPS_PER_EPOCH):
          worker_preemption_watcher.run(distributed_train_step, epoch, step)
        # Add some randomness to when preemption actually happens. We should
        # trigger it for sure if the training is coming to an end and it hasn't
        # been triggered yet.
        if epoch >= EPOCHS_TO_RUN - 2:
          trigger_it = True
        else:
          trigger_it = False

        self._maybe_trigger_a_preemption(training_started_event, trigger_it)

      logging.info('Training finished.')

      self.assertEqual(
          model.v.numpy(),
          strategy.num_replicas_in_sync * EPOCHS_TO_RUN * STEPS_PER_EPOCH)

  def test_preemption_checkpointing(self):
    has_chief = False
    cluster_spec = multi_worker_test_base.create_cluster_spec(
        has_chief=has_chief,
        num_workers=CLUSTER_SIZE)
    training_started_event = multi_process_runner.manager().Event()

    checkpoint_dir = os.path.join(self.get_temp_dir(), 'fh_ckpt')

    if _is_oss():
      rpc_layer = 'grpc'
    else:
      rpc_layer = 'grpc+loas'

    mpr = multi_process_runner.MultiProcessRunner(
        self.worker_fn,
        cluster_spec,
        args=(checkpoint_dir, cluster_spec, [training_started_event]),
        rpc_layer=rpc_layer,
        return_output=True,
        dependence_on_chief=has_chief)

    logging.info('Cluster starting.')
    mpr.start()
    while not training_started_event.is_set():
      time.sleep(1)

    logging.info('sending sigterm')
    killed_worker = random.randrange(0, CLUSTER_SIZE)
    os.kill(mpr.get_process_id('worker', killed_worker), signal.SIGTERM)

    logging.info('sigterm sent')
    time.sleep(5)

    logging.info('restarting workers')
    for worker_id in range(CLUSTER_SIZE):
      mpr.start_single_process('worker', worker_id, cluster_spec)
    logging.info('workers restarted')

    stdout = mpr.join(timeout=270).stdout
    all_start_point = []
    for msg in stdout:
      matched_group = re.search(r'.*Restored training at (\d+)', msg)

      if matched_group:
        all_start_point.append(int(matched_group.group(1)))

    # remove duplicate logs created due to presence of multiple workers
    start_points = all_start_point[::CLUSTER_SIZE]

    # assert that after restarting, we don't repeat previous training steps
    self.assertNotEqual(start_points[-1], 0)

  def test_error_propagation(self):
    error_worker = random.randint(0, CLUSTER_SIZE)
    cluster_spec = multi_worker_test_base.create_cluster_spec(
        has_chief=False, num_workers=CLUSTER_SIZE)
    checkpoint_dir = self.get_temp_dir()

    def assert_raise_error():
      # Asserts that an error raised during a training step on one of the worker
      # is caught on all workers.
      with self.assertRaises(errors_impl.ResourceExhaustedError) as error:
        self.worker_fn(
            checkpoint_dir,
            cluster_spec,
            raise_app_error_on_worker=error_worker)
      self.assertIn('Running out of resources', str(error.exception))

    if _is_oss():
      rpc_layer = 'grpc'
    else:
      rpc_layer = 'grpc+loas'

    mpr = multi_process_runner.MultiProcessRunner(
        assert_raise_error,
        cluster_spec,
        rpc_layer=rpc_layer,
        return_output=True,
        dependence_on_chief=False)

    logging.info('Cluster starting.')
    mpr.start()
    mpr.join(timeout=250)

  def test_grace_period_continue_training(self):
    grace_period = 5
    has_chief = False
    cluster_spec = multi_worker_test_base.create_cluster_spec(
        has_chief=has_chief,
        num_workers=CLUSTER_SIZE)
    training_started_event = multi_process_runner.manager().Event()

    checkpoint_dir = os.path.join(self.get_temp_dir(), 'fh_ckpt')

    if _is_oss():
      rpc_layer = 'grpc'
    else:
      rpc_layer = 'grpc+loas'

    termination_config = failure_handling.TerminationConfig(
        time_till_termination=grace_period)
    mpr = multi_process_runner.MultiProcessRunner(
        self.worker_fn,
        cluster_spec,
        args=(checkpoint_dir, cluster_spec, [training_started_event], None,
              termination_config),
        rpc_layer=rpc_layer,
        return_output=True,
        dependence_on_chief=has_chief)

    logging.info('Cluster starting.')
    mpr.start()
    while not training_started_event.is_set():
      time.sleep(1)

    killed_worker = random.randrange(0, CLUSTER_SIZE)
    logging.info('sending SIGTERM')
    os.kill(mpr.get_process_id('worker', killed_worker), signal.SIGTERM)
    logging.info('SIGTERM sent')

    # wait for all cluster within the given grace period (plus a buffer since
    # our per-step time here is too small)
    waiting_time = 0
    exit_process_count = 0
    while exit_process_count != CLUSTER_SIZE and waiting_time < grace_period + 10:
      exit_process_count = 0
      for worker_id in range(CLUSTER_SIZE):
        if not mpr.process_exists('worker', worker_id):
          exit_process_count += 1
      waiting_time += 1
      time.sleep(1)

    if waiting_time == grace_period + 10:
      raise RuntimeError('Waited exceeding grace period. ')

    logging.info('restarting workers')
    for worker_id in range(CLUSTER_SIZE):
      mpr.start_single_process('worker', worker_id, cluster_spec)
    logging.info('workers restarted')

    stdout = mpr.join(timeout=250).stdout
    all_start_point = []
    checkpoint_count = []
    for msg in stdout:
      # TODO(wxinyi): remove the string matching and assert checkpoint number.
      matched_group = re.search(r'.*Restored training at (\d+)', msg)
      checkpoint_group = re.search(r'.*RUN_TO_CHECKPOINT set to (\d+)', msg)

      if matched_group:
        all_start_point.append(int(matched_group.group(1)))

      if checkpoint_group:
        checkpoint_count.append(int(checkpoint_group.group(1)))

    # remove duplicate logs created due to presence of multiple workers
    start_points = all_start_point[::CLUSTER_SIZE]

    # assert that after restarting, we don't repeat previous training steps
    self.assertNotEqual(start_points[-1], 0)

    # One for timing, another for final call.
    self.assertLen(set(checkpoint_count), 2)

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


text:
#include "core/hw/gfxip/gfx9/gfx9Chip.h"
#include "core/hw/gfxip/gfx9/gfx9CmdStream.h"
#include "core/hw/gfxip/gfx9/gfx9Device.h"
#include "core/hw/gfxip/gfx9/gfx9Pm4Optimizer.h"
#include "core/hw/gfxip/gfx9/gfx9UniversalCmdBuffer.h"
#include "palIterator.h"
#include "palLinearAllocator.h"

using namespace Util;

namespace Pal
{
namespace Gfx9
{

// =====================================================================================================================
CmdStream::CmdStream(
    const Device&  device,
    ICmdAllocator* pCmdAllocator,
    EngineType     engineType,
    SubEngineType  subEngineType,
    CmdStreamUsage cmdStreamUsage,
    bool           isNested)
    :
    Pm4::CmdStream(device,
                   pCmdAllocator,
                   engineType,
                   subEngineType,
                   cmdStreamUsage,
                   GetChainSizeInDwords(device, engineType, isNested),
                   CmdUtil::MinNopSizeInDwords,
                   CmdUtil::CondIndirectBufferSize,
                   isNested),
    m_cmdUtil(device.CmdUtil()),
    m_pPm4Optimizer(nullptr),
    m_pChunkPreamble(nullptr),
    m_contextRollDetected(false)
{
}

// =====================================================================================================================
Result CmdStream::Begin(
    CmdStreamBeginFlags     flags,
    VirtualLinearAllocator* pMemAllocator)
{
    // Note that we don't support command optimization or command prefetch for CE.
    if (m_subEngineType == SubEngineType::ConstantEngine)
    {
        flags.optimizeCommands = false;
        flags.prefetchCommands = false;
    }
    else
    {
        // We can't enable PM4 optimization without an allocator because we need to dynamically allocate a Pm4Optimizer.
        flags.optimizeCommands &= (pMemAllocator != nullptr);

        // We may want to modify prefetchCommands based on this setting.
        switch (GetGfx9Settings(*m_device.Parent()).prefetchCommandBuffers)
        {
        case Gfx9PrefetchCommandsDisabled:
            flags.prefetchCommands = false;
            break;

        case Gfx9PrefetchCommandsBuildInfo:
            // The prefetchCommands flag was set according to the client's command buffer build info.
            // However, we really should force prefetching off if the command data is in local memory because:
            // 1. Local memory is fast enough that cold reads are no problem. Prefetching the whole command chunk
            //    ahead of time might evict things from the L2 cache that we need right now, hurting performance.
            // 2. We try to use the uncached MTYPE when allocating local memory for command data. This avoids any
            //    L2 cache pollution but also makes prefetching completely useless because it only prefetches to L2.
            if (m_pCmdAllocator->LocalCommandData())
            {
                flags.prefetchCommands = false;
            }
            break;

        case Gfx9PrefetchCommandsForceAllDe:
            flags.prefetchCommands = (GetEngineType() == EngineTypeUniversal);
            break;

        case Gfx9PrefetchCommandsForceAllDeAce:
            flags.prefetchCommands = true;
            break;

        default:
            PAL_ASSERT_ALWAYS();
            break;
        }
    }

    Result result = Pm4::CmdStream::Begin(flags, pMemAllocator);

    if ((result == Result::Success) && (m_flags.optimizeCommands == 1))
    {
        // Allocate a temporary PM4 optimizer to use during command building.
        m_pPm4Optimizer = PAL_NEW(Pm4Optimizer, m_pMemAllocator, AllocInternal)(static_cast<const Device&>(m_device));

        if (m_pPm4Optimizer == nullptr)
        {
            result = Result::ErrorOutOfMemory;
        }
    }

    return result;
}

// =====================================================================================================================
void CmdStream::Reset(
    CmdAllocator* pNewAllocator,
    bool          returnGpuMemory)
{
    // Reset all tracked state.
    m_pChunkPreamble      = nullptr;
    m_contextRollDetected = false;

    Pm4::CmdStream::Reset(pNewAllocator, returnGpuMemory);
}

// =====================================================================================================================
// Helper function for determining the command buffer chain size (in DWORD's). Early versions of the CP microcode did
// not properly support IB2 chaining, so we need to check the ucode version before enabling chaining for IB2's.
uint32 CmdStream::GetChainSizeInDwords(
    const Device& device,
    EngineType    engineType,
    bool          isNested) const
{
    const Pal::Device* pPalDevice = device.Parent();
    uint32              chainSize = CmdUtil::ChainSizeInDwords(engineType);

    constexpr uint32 UcodeVersionWithIb2ChainingFix = 31;
    if (isNested &&
        (pPalDevice->ChipProperties().gfxLevel == GfxIpLevel::GfxIp9) &&
        (pPalDevice->EngineProperties().cpUcodeVersion < UcodeVersionWithIb2ChainingFix))
    {
        // Disable chaining for nested command buffers if the microcode version does not support the IB2 chaining fix.
        chainSize = 0;
    }

    return chainSize;
}

// =====================================================================================================================
void CmdStream::CleanupTempObjects()
{
    // Clean up the temporary PM4 optimizer object.
    if (m_pMemAllocator != nullptr)
    {
        PAL_SAFE_DELETE(m_pPm4Optimizer, m_pMemAllocator);
    }
}

// =====================================================================================================================
// Builds a PM4 packet to modify the given register unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
template <bool Pm4OptEnabled>
uint32* CmdStream::WriteContextRegRmw(
    uint32  regAddr,
    uint32  regMask,
    uint32  regData,
    uint32* pCmdSpace)
{
    PAL_ASSERT(m_flags.optimizeCommands == Pm4OptEnabled);

    if ((Pm4OptEnabled == false) || m_pPm4Optimizer->MustKeepContextRegRmw(regAddr, regMask, regData))
    {
        pCmdSpace += m_cmdUtil.BuildContextRegRmw(regAddr, regMask, regData, pCmdSpace);
        m_contextRollDetected = true;
    }

    return pCmdSpace;
}

template
uint32* CmdStream::WriteContextRegRmw<true>(
    uint32  regAddr,
    uint32  regMask,
    uint32  regData,
    uint32* pCmdSpace);
template
uint32* CmdStream::WriteContextRegRmw<false>(
    uint32  regAddr,
    uint32  regMask,
    uint32  regData,
    uint32* pCmdSpace);

// =====================================================================================================================
// Wrapper for real WriteContextRegRmw() when it isn't known whether the immediate pm4 optimizer is enabled.
uint32* CmdStream::WriteContextRegRmw(
    uint32  regAddr,
    uint32  regMask,
    uint32  regData,
    uint32* pCmdSpace)
{
    if (m_flags.optimizeCommands)
    {
        pCmdSpace = WriteContextRegRmw<true>(regAddr, regMask, regData, pCmdSpace);
    }
    else
    {
        pCmdSpace = WriteContextRegRmw<false>(regAddr, regMask, regData, pCmdSpace);
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to set the given register unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
template <bool Pm4OptEnabled>
uint32* CmdStream::WriteSetVgtLsHsConfig(
    regVGT_LS_HS_CONFIG vgtLsHsConfig,
    uint32*             pCmdSpace)
{
    PAL_ASSERT(m_flags.optimizeCommands == Pm4OptEnabled);

    if ((Pm4OptEnabled == false) || m_pPm4Optimizer->MustKeepSetContextReg(mmVGT_LS_HS_CONFIG, vgtLsHsConfig.u32All))
    {
        const size_t totalDwords = m_cmdUtil.BuildSetOneContextReg(
                                        mmVGT_LS_HS_CONFIG,
                                        pCmdSpace,
                                        index__pfp_set_context_reg_index__vgt_ls_hs_config__GFX09);
        m_contextRollDetected = true;
        pCmdSpace[CmdUtil::ContextRegSizeDwords] = vgtLsHsConfig.u32All;
        pCmdSpace += totalDwords;
    }

    return pCmdSpace;
}

template
uint32* CmdStream::WriteSetVgtLsHsConfig<true>(
    regVGT_LS_HS_CONFIG vgtLsHsConfig,
    uint32*             pCmdSpace);
template
uint32* CmdStream::WriteSetVgtLsHsConfig<false>(
    regVGT_LS_HS_CONFIG vgtLsHsConfig,
    uint32*             pCmdSpace);

// =====================================================================================================================
// Builds a PM4 packet to set the given register unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
//
// Note that we must be very careful when setting registers on gfx10. The CP's register filter CAM isn't smart enough
// to track GRBM_GFX_INDEX so it can filter out packets that set the same register value for different instances.
// The caller must set isPerfCtr = true when they could write any register to multiple instances.
template <bool isPerfCtr>
uint32* CmdStream::WriteSetOneConfigReg(
    uint32                               regAddr,
    uint32                               regData,
    uint32*                              pCmdSpace,
    PFP_SET_UCONFIG_REG_INDEX_index_enum index)
{
    const size_t totalDwords = m_cmdUtil.BuildSetOneConfigReg<isPerfCtr>(regAddr, pCmdSpace, index);
    pCmdSpace[CmdUtil::ConfigRegSizeDwords] = regData;

    return pCmdSpace + totalDwords;
}

template
uint32* CmdStream::WriteSetOneConfigReg<true>(
    uint32                               regAddr,
    uint32                               regData,
    uint32*                              pCmdSpace,
    PFP_SET_UCONFIG_REG_INDEX_index_enum index);
template
uint32* CmdStream::WriteSetOneConfigReg<false>(
    uint32                               regAddr,
    uint32                               regData,
    uint32*                              pCmdSpace,
    PFP_SET_UCONFIG_REG_INDEX_index_enum index);

// =====================================================================================================================
// Builds a PM4 packet to set the given set of sequential config registers.  Returns a pointer to the next unused DWORD
// in pCmdSpace.
//
// Note that we must be very careful when setting registers on gfx10. The CP's register filter CAM isn't smart enough
// to track GRBM_GFX_INDEX so it can filter out packets that set the same register value for different instances.
// The caller must set isPerfCtr = true when they could write any register to multiple instances.
template <bool isPerfCtr>
uint32* CmdStream::WriteSetSeqConfigRegs(
    uint32      startRegAddr,
    uint32      endRegAddr,
    const void* pData,
    uint32*     pCmdSpace)
{
    const size_t totalDwords = m_cmdUtil.BuildSetSeqConfigRegs<isPerfCtr>(startRegAddr, endRegAddr, pCmdSpace);

    memcpy(&pCmdSpace[CmdUtil::ConfigRegSizeDwords],
           pData,
           (totalDwords - CmdUtil::ConfigRegSizeDwords) * sizeof(uint32));

    return (pCmdSpace + totalDwords);
}
template
uint32* CmdStream::WriteSetSeqConfigRegs<true>(
    uint32      startRegAddr,
    uint32      endRegAddr,
    const void* pData,
    uint32*     pCmdSpace);
template
uint32* CmdStream::WriteSetSeqConfigRegs<false>(
    uint32      startRegAddr,
    uint32      endRegAddr,
    const void* pData,
    uint32*     pCmdSpace);

// =====================================================================================================================
// Builds a PM4 packet to set the given set of sequential config registers to 0.  Returns a pointer to the next unused
// DWORD in pCmdSpace.
//
// Note that we must be very careful when setting registers on gfx10. The CP's register filter CAM isn't smart enough
// to track GRBM_GFX_INDEX so it can filter out packets that set the same register value for different instances.
// The caller must set isPerfCtr = true when they could write any register to multiple instances.
template <bool isPerfCtr>
uint32* CmdStream::WriteSetZeroSeqConfigRegs(
    uint32      startRegAddr,
    uint32      endRegAddr,
    uint32* pCmdSpace)
{
    const size_t totalDwords = m_cmdUtil.BuildSetSeqConfigRegs<isPerfCtr>(startRegAddr, endRegAddr, pCmdSpace);

    memset(&pCmdSpace[CmdUtil::ConfigRegSizeDwords], 0, (totalDwords - CmdUtil::ConfigRegSizeDwords) * sizeof(uint32));

    return (pCmdSpace + totalDwords);
}
template
uint32* CmdStream::WriteSetZeroSeqConfigRegs<true>(
    uint32      startRegAddr,
    uint32      endRegAddr,
    uint32* pCmdSpace);
template
uint32* CmdStream::WriteSetZeroSeqConfigRegs<false>(
    uint32      startRegAddr,
    uint32      endRegAddr,
    uint32* pCmdSpace);

// =====================================================================================================================
// Builds a PM4 packet to set the given register unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
template <bool Pm4OptEnabled>
uint32* CmdStream::WriteSetOneContextReg(
    uint32  regAddr,
    uint32  regData,
    uint32* pCmdSpace)
{
    PAL_ASSERT(m_flags.optimizeCommands == Pm4OptEnabled);

    if ((Pm4OptEnabled == false) || m_pPm4Optimizer->MustKeepSetContextReg(regAddr, regData))
    {
        const size_t totalDwords = m_cmdUtil.BuildSetOneContextReg(regAddr, pCmdSpace);

        pCmdSpace[CmdUtil::ContextRegSizeDwords] = regData;
        pCmdSpace += totalDwords;
        m_contextRollDetected = true;

    }

    return pCmdSpace;
}

template
uint32* CmdStream::WriteSetOneContextReg<true>(
    uint32  regAddr,
    uint32  regData,
    uint32* pCmdSpace);
template
uint32* CmdStream::WriteSetOneContextReg<false>(
    uint32  regAddr,
    uint32  regData,
    uint32* pCmdSpace);

// =====================================================================================================================
// Wrapper for the real WriteSetOneContextReg() when it isn't known whether the immediate pm4 optimizer is enabled.
uint32* CmdStream::WriteSetOneContextReg(
    uint32  regAddr,
    uint32  regData,
    uint32* pCmdSpace)
{
    if (m_flags.optimizeCommands)
    {
        pCmdSpace = WriteSetOneContextReg<true>(regAddr, regData, pCmdSpace);
    }
    else
    {
        pCmdSpace = WriteSetOneContextReg<false>(regAddr, regData, pCmdSpace);
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to set the given register when the caller already guarantees that the write is not redundant. The
// caller should be careful not to mix this function with the regular WriteSetOneContextReg() for the same register(s).
// Returns a pointer to the next unused DWORD in pCmdSpace.
uint32* CmdStream::WriteSetOneContextRegNoOpt(
    uint32  regAddr,
    uint32  regData,
    uint32* pCmdSpace)
{
    const size_t totalDwords = m_cmdUtil.BuildSetOneContextReg(regAddr, pCmdSpace);

    pCmdSpace[CmdUtil::ContextRegSizeDwords] = regData;
    pCmdSpace += totalDwords;
    m_contextRollDetected = true;

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to set the given register unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
template <Pm4ShaderType shaderType, bool Pm4OptEnabled>
uint32* CmdStream::WriteSetOneShReg(
    uint32        regAddr,
    uint32        regData,
    uint32*       pCmdSpace)
{
    PAL_ASSERT(m_flags.optimizeCommands == Pm4OptEnabled);

    if ((Pm4OptEnabled == false) || m_pPm4Optimizer->MustKeepSetShReg(regAddr, regData))
    {
        const size_t totalDwords = m_cmdUtil.BuildSetOneShReg(regAddr, shaderType, pCmdSpace);

        pCmdSpace[CmdUtil::ShRegSizeDwords] = regData;
        pCmdSpace += totalDwords;
    }

    return pCmdSpace;
}

template
uint32* CmdStream::WriteSetOneShReg<ShaderGraphics, true>(
    uint32        regAddr,
    uint32        regData,
    uint32*       pCmdSpace);
template
uint32* CmdStream::WriteSetOneShReg<ShaderGraphics, false>(
    uint32        regAddr,
    uint32        regData,
    uint32*       pCmdSpace);
template
uint32* CmdStream::WriteSetOneShReg<ShaderCompute, true>(
    uint32        regAddr,
    uint32        regData,
    uint32*       pCmdSpace);
template
uint32* CmdStream::WriteSetOneShReg<ShaderCompute, false>(
    uint32        regAddr,
    uint32        regData,
    uint32*       pCmdSpace);

// =====================================================================================================================
// Wrapper for the real WriteSetOneShReg() for when the caller doesn't know if the immediate pm4 optimizer is enabled.
template <Pm4ShaderType shaderType>
uint32* CmdStream::WriteSetOneShReg(
    uint32        regAddr,
    uint32        regData,
    uint32*       pCmdSpace)
{
    if (m_flags.optimizeCommands)
    {
        pCmdSpace = WriteSetOneShReg<shaderType, true>(regAddr, regData, pCmdSpace);
    }
    else
    {
        pCmdSpace = WriteSetOneShReg<shaderType, false>(regAddr, regData, pCmdSpace);
    }

    return pCmdSpace;
}

// Instantiate the template for the linker.
template
uint32* CmdStream::WriteSetOneShReg<ShaderGraphics>(
    uint32        regAddr,
    uint32        regData,
    uint32*       pCmdSpace);
template
uint32* CmdStream::WriteSetOneShReg<ShaderCompute>(
    uint32        regAddr,
    uint32        regData,
    uint32*       pCmdSpace);

// =====================================================================================================================
// Builds a PM4 packet to set the given register unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
uint32* CmdStream::WriteSetOneShRegIndex(
    uint32                          regAddr,
    uint32                          regData,
    Pm4ShaderType                   shaderType,
    PFP_SET_SH_REG_INDEX_index_enum index,
    uint32*                         pCmdSpace)
{
    if ((m_flags.optimizeCommands == 0) || m_pPm4Optimizer->MustKeepSetShReg(regAddr, regData))
    {
        const size_t totalDwords = m_cmdUtil.BuildSetOneShRegIndex(regAddr, shaderType, index, pCmdSpace);

        pCmdSpace[CmdUtil::ShRegSizeDwords] = regData;
        pCmdSpace += totalDwords;
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to set the given registers unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
uint32* CmdStream::WriteSetSeqShRegs(
    uint32        startRegAddr,
    uint32        endRegAddr,
    Pm4ShaderType shaderType,
    const void*   pData,
    uint32*       pCmdSpace)
{
    if (m_flags.optimizeCommands == 1)
    {
        PM4_ME_SET_SH_REG setData;
        m_cmdUtil.BuildSetSeqShRegs(startRegAddr, endRegAddr, shaderType, &setData);

        pCmdSpace = m_pPm4Optimizer->WriteOptimizedSetSeqShRegs(setData,
                                                                static_cast<const uint32*>(pData),
                                                                pCmdSpace);
    }
    else
    {
        const size_t totalDwords = m_cmdUtil.BuildSetSeqShRegs(startRegAddr, endRegAddr, shaderType, pCmdSpace);

        memcpy(&pCmdSpace[CmdUtil::ShRegSizeDwords],
               pData,
               (totalDwords - CmdUtil::ShRegSizeDwords) * sizeof(uint32));
        pCmdSpace += totalDwords;
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to set the given registers to 0 unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
uint32* CmdStream::WriteSetZeroSeqShRegs(
    uint32        startRegAddr,
    uint32        endRegAddr,
    Pm4ShaderType shaderType,
    uint32*       pCmdSpace)
{
    // Only m_shadowInitCmdStream will call this function, and m_flags.optimizeCommands of 0 in m_shadowInitCmdStream.
    PAL_ASSERT(m_flags.optimizeCommands == 0);
    const size_t totalDwords = m_cmdUtil.BuildSetSeqShRegs(startRegAddr, endRegAddr, shaderType, pCmdSpace);
    memset(&pCmdSpace[CmdUtil::ShRegSizeDwords], 0, (totalDwords - CmdUtil::ShRegSizeDwords) * sizeof(uint32));
    pCmdSpace += totalDwords;

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to set the given registers unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
uint32* CmdStream::WriteSetSeqShRegsIndex(
    uint32                          startRegAddr,
    uint32                          endRegAddr,
    Pm4ShaderType                   shaderType,
    const void*                     pData,
    PFP_SET_SH_REG_INDEX_index_enum index,
    uint32*                         pCmdSpace)
{
    if (m_flags.optimizeCommands == 1)
    {
        PM4_ME_SET_SH_REG setData;
        m_cmdUtil.BuildSetSeqShRegsIndex(startRegAddr, endRegAddr, shaderType, index, &setData);

        pCmdSpace = m_pPm4Optimizer->WriteOptimizedSetSeqShRegs(setData,
                                                                static_cast<const uint32*>(pData),
                                                                pCmdSpace);
    }
    else
    {
        const size_t totalDwords =
            m_cmdUtil.BuildSetSeqShRegsIndex(startRegAddr, endRegAddr, shaderType, index, pCmdSpace);

        memcpy(&pCmdSpace[CmdUtil::ShRegSizeDwords],
               pData,
               (totalDwords - CmdUtil::ShRegSizeDwords) * sizeof(uint32));
        pCmdSpace += totalDwords;
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Helper function for writing user-SGPRs mapped to user-data entries for a graphics or compute shader stage.
template <bool IgnoreDirtyFlags, Pm4ShaderType shaderType>
uint32* CmdStream::WriteUserDataEntriesToSgprs(
    const UserDataEntryMap& entryMap,
    const UserDataEntries&  entries,
    uint32*                 pCmdSpace)
{
    if (m_flags.optimizeCommands != 0)
    {
        pCmdSpace = WriteUserDataEntriesToSgprs<IgnoreDirtyFlags, shaderType, true>(entryMap, entries, pCmdSpace);
    }
    else
    {
        pCmdSpace = WriteUserDataEntriesToSgprs<IgnoreDirtyFlags, shaderType, false>(entryMap, entries, pCmdSpace);
    }

    return pCmdSpace;
}

// Instantiate template for linker.
template
uint32* CmdStream::WriteUserDataEntriesToSgprs<false, ShaderGraphics>(
    const UserDataEntryMap& entryMap,
    const UserDataEntries&  entries,
    uint32*                 pCmdSpace);
template
uint32* CmdStream::WriteUserDataEntriesToSgprs<false, ShaderCompute>(
    const UserDataEntryMap& entryMap,
    const UserDataEntries&  entries,
    uint32*                 pCmdSpace);
template
uint32* CmdStream::WriteUserDataEntriesToSgprs<true, ShaderGraphics>(
    const UserDataEntryMap& entryMap,
    const UserDataEntries& entries,
    uint32* pCmdSpace);
template
uint32* CmdStream::WriteUserDataEntriesToSgprs<true, ShaderCompute>(
    const UserDataEntryMap& entryMap,
    const UserDataEntries& entries,
    uint32* pCmdSpace);

// =====================================================================================================================
// Helper function for writing user-SGPRs mapped to user-data entries for a graphics or compute shader stage.
template <bool IgnoreDirtyFlags, Pm4ShaderType shaderType, bool Pm4OptEnabled>
uint32* CmdStream::WriteUserDataEntriesToSgprs(
    const UserDataEntryMap& entryMap,
    const UserDataEntries&  entries,
    uint32*                 pCmdSpace)
{
    // Virtualized user-data entries are always remapped to a consecutive sequence of user-SGPR's. Because of this
    // mapping, we can always assume that this operation will result in a series of zero or more consecutive registers
    // being written, except in the case where we skip entries which aren't dirty (i.e., IgnoreDirtyFlags is false).
    const uint16 firstUserSgpr = entryMap.firstUserSgprRegAddr;
    const uint16 userSgprCount = entryMap.userSgprCount;

    uint32 scratchMem[NumUserDataRegisters - FastUserDataStartReg];
    uint32* pCmdPayload = Pm4OptEnabled ? scratchMem : (pCmdSpace + CmdUtil::ShRegSizeDwords);

    if (IgnoreDirtyFlags)
    {
        if (userSgprCount != 0)
        {
            for (uint16 sgpr = 0; sgpr < userSgprCount; ++sgpr)
            {
                pCmdPayload[sgpr] = entries.entries[entryMap.mappedEntry[sgpr]];
            }

            if (Pm4OptEnabled)
            {
                PM4_ME_SET_SH_REG setShReg;
                m_cmdUtil.BuildSetSeqShRegs(firstUserSgpr,
                                            (firstUserSgpr + userSgprCount - 1),
                                            shaderType,
                                            &setShReg);

                pCmdSpace = m_pPm4Optimizer->WriteOptimizedSetSeqShRegs(setShReg, pCmdPayload, pCmdSpace);
            }
            else
            {
                const size_t totalDwords = m_cmdUtil.BuildSetSeqShRegs(firstUserSgpr,
                                                                       (firstUserSgpr + userSgprCount - 1),
                                                                       shaderType,
                                                                       pCmdSpace);
                // The packet is complete and will not be optimized, fix-up pCmdSpace and we're done.
                PAL_ASSERT(totalDwords == (userSgprCount + CmdUtil::ShRegSizeDwords));
                pCmdSpace += totalDwords;
            }
        }
    }
    else
    {
        // If we are honoring the dirty flags, then there may be multiple packets because skipping dirty entries
        // can break the assumption about only writing consecutive registers.
        for (uint16 sgpr = 0; sgpr < userSgprCount; ++sgpr)
        {
            const uint16 packetFirstSgpr = (firstUserSgpr + sgpr);
            uint16       packetSgprCount = 0;

            uint16 entry = entryMap.mappedEntry[sgpr];
            while ((sgpr < userSgprCount) && WideBitfieldIsSet(entries.dirty, entry))
            {
                pCmdPayload[packetSgprCount] = entries.entries[entry];
                ++packetSgprCount;
                ++sgpr;
                entry = entryMap.mappedEntry[sgpr];
            }

            if (packetSgprCount > 0)
            {
                if (Pm4OptEnabled)
                {
                    PM4_ME_SET_SH_REG setShReg;
                    m_cmdUtil.BuildSetSeqShRegs(packetFirstSgpr,
                                                (packetFirstSgpr + packetSgprCount - 1),
                                                shaderType,
                                                &setShReg);

                    pCmdSpace = m_pPm4Optimizer->WriteOptimizedSetSeqShRegs(setShReg, pCmdPayload, pCmdSpace);
                }
                else
                {
                    const size_t totalDwords = m_cmdUtil.BuildSetSeqShRegs(packetFirstSgpr,
                                                                           (packetFirstSgpr + packetSgprCount - 1),
                                                                           shaderType,
                                                                           pCmdSpace);
                    // The packet is complete and will not be optimized, fix-up pCmdSpace and we're done.
                    PAL_ASSERT(totalDwords == (packetSgprCount + CmdUtil::ShRegSizeDwords));
                    pCmdSpace   += totalDwords;
                    pCmdPayload += totalDwords;
                }
            }
        } // for each mapped user-SGPR
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to load a single group of consecutive context registers from an indirect video memory offset.
// Returns a pointer to the next unused DWORD in pCmdSpace.
template <bool Pm4OptEnabled>
uint32* CmdStream::WriteLoadSeqContextRegs(
    uint32      startRegAddr,
    uint32      regCount,
    gpusize     dataVirtAddr,
    uint32*     pCmdSpace)
{
    PAL_ASSERT(m_flags.optimizeCommands == Pm4OptEnabled);

    // In gfx9+, PM4_PFP_LOAD_CONTEXT_REG_INDEX is always supported.
    const size_t packetSizeDwords = m_cmdUtil.BuildLoadContextRegsIndex<true>(
                                    dataVirtAddr,
                                    startRegAddr,
                                    regCount,
                                    pCmdSpace);
    if (Pm4OptEnabled)
    {
        m_pPm4Optimizer->HandleLoadContextRegsIndex(
                reinterpret_cast<const PM4_PFP_LOAD_CONTEXT_REG_INDEX&>(*pCmdSpace));
    }
    pCmdSpace += packetSizeDwords;

    return pCmdSpace;
}

template
uint32* CmdStream::WriteLoadSeqContextRegs<true>(
    uint32      startRegAddr,
    uint32      regCount,
    gpusize     dataVirtAddr,
    uint32*     pCmdSpace);
template
uint32* CmdStream::WriteLoadSeqContextRegs<false>(
    uint32      startRegAddr,
    uint32      regCount,
    gpusize     dataVirtAddr,
    uint32*     pCmdSpace);

// =====================================================================================================================
// Wrapper for the real WriteLoadSeqContextRegs() for when the caller doesn't know if the immediate mode pm4 optimizer
// is enabled.
uint32* CmdStream::WriteLoadSeqContextRegs(
    uint32      startRegAddr,
    uint32      regCount,
    gpusize     dataVirtAddr,
    uint32*     pCmdSpace)
{
    if (m_flags.optimizeCommands == 1)
    {
        pCmdSpace = WriteLoadSeqContextRegs<true>(startRegAddr, regCount, dataVirtAddr, pCmdSpace);
    }
    else
    {
        pCmdSpace = WriteLoadSeqContextRegs<false>(startRegAddr, regCount, dataVirtAddr, pCmdSpace);
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to set the given registers unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
template <bool Pm4OptEnabled>
uint32* CmdStream::WriteSetSeqContextRegs(
    uint32      startRegAddr,
    uint32      endRegAddr,
    const void* pData,
    uint32*     pCmdSpace)
{
    PAL_ASSERT(m_flags.optimizeCommands == Pm4OptEnabled);

    if (Pm4OptEnabled)
    {
        PM4_PFP_SET_CONTEXT_REG setData;
        m_cmdUtil.BuildSetSeqContextRegs(startRegAddr, endRegAddr, &setData);

        pCmdSpace = m_pPm4Optimizer->WriteOptimizedSetSeqContextRegs(setData,
                                                                     &m_contextRollDetected,
                                                                     static_cast<const uint32*>(pData),
                                                                     pCmdSpace);
    }
    else
    {
        // NOTE: We'll use other state tracking to determine whether a context roll occurred for non-immediate-mode
        //       optimizations.
        const size_t totalDwords = m_cmdUtil.BuildSetSeqContextRegs(startRegAddr, endRegAddr, pCmdSpace);

        memcpy(&pCmdSpace[CmdUtil::ContextRegSizeDwords],
               pData,
               (totalDwords - CmdUtil::ContextRegSizeDwords) * sizeof(uint32));
        pCmdSpace += totalDwords;
    }

    return pCmdSpace;
}

template
uint32* CmdStream::WriteSetSeqContextRegs<true>(
    uint32      startRegAddr,
    uint32      endRegAddr,
    const void* pData,
    uint32*     pCmdSpace);
template
uint32* CmdStream::WriteSetSeqContextRegs<false>(
    uint32      startRegAddr,
    uint32      endRegAddr,
    const void* pData,
    uint32*     pCmdSpace);

// =====================================================================================================================
// Wrapper for the real WriteSetSeqContextRegs() for when the caller doesn't know if the immediate mode pm4 optimizer
// is enabled.
uint32* CmdStream::WriteSetSeqContextRegs(
    uint32      startRegAddr,
    uint32      endRegAddr,
    const void* pData,
    uint32*     pCmdSpace)
{
    if (m_flags.optimizeCommands)
    {
        pCmdSpace = WriteSetSeqContextRegs<true>(startRegAddr, endRegAddr, pData, pCmdSpace);
    }
    else
    {
        pCmdSpace = WriteSetSeqContextRegs<false>(startRegAddr, endRegAddr, pData, pCmdSpace);
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Builds a PM4 packet to set the given base unless the PM4 optimizer indicates that it is redundant.
// Returns a pointer to the next unused DWORD in pCmdSpace.
template <bool Pm4OptEnabled>
uint32* CmdStream::WriteSetBase(
    gpusize                         address,
    PFP_SET_BASE_base_index_enum    baseIndex,
    Pm4ShaderType                   shaderType,
    uint32*                         pCmdSpace)
{
    PAL_ASSERT(m_flags.optimizeCommands == Pm4OptEnabled);

    if ((Pm4OptEnabled == false) || m_pPm4Optimizer->MustKeepSetBase(address, baseIndex, shaderType))
    {
        pCmdSpace += m_cmdUtil.BuildSetBase(address, baseIndex, shaderType, pCmdSpace);
    }

    return pCmdSpace;
}

template
uint32* CmdStream::WriteSetBase<true>(
    gpusize                         address,
    PFP_SET_BASE_base_index_enum    baseIndex,
    Pm4ShaderType                   shaderType,
    uint32*                         pCmdSpace);
template
uint32* CmdStream::WriteSetBase<false>(
    gpusize                         address,
    PFP_SET_BASE_base_index_enum    baseIndex,
    Pm4ShaderType                   shaderType,
    uint32*                         pCmdSpace);

// =====================================================================================================================
// Wrapper for the real WriteSetBase() for when the caller doesn't know if the immediate mode pm4 optimizer
// is enabled.
uint32* CmdStream::WriteSetBase(
    gpusize                         address,
    PFP_SET_BASE_base_index_enum    baseIndex,
    Pm4ShaderType                   shaderType,
    uint32*                         pCmdSpace)
{
    if (m_flags.optimizeCommands)
    {
        pCmdSpace = WriteSetBase<true>(address, baseIndex, shaderType, pCmdSpace);
    }
    else
    {
        pCmdSpace = WriteSetBase<false>(address, baseIndex, shaderType, pCmdSpace);
    }

    return pCmdSpace;
}

// =====================================================================================================================
// If immediate mode optimizations are active, tell the optimizer to invalidate its copy of this particular SH register.
void CmdStream::NotifyIndirectShRegWrite(
    uint32 regAddr)
{
    if (m_flags.optimizeCommands == 1)
    {
        m_pPm4Optimizer->SetShRegInvalid(regAddr);
    }
}

// =====================================================================================================================
size_t CmdStream::BuildCondIndirectBuffer(
    CompareFunc compareFunc,
    gpusize     compareGpuAddr,
    uint64      data,
    uint64      mask,
    uint32*     pPacket
    ) const
{
    return m_cmdUtil.BuildCondIndirectBuffer(
        compareFunc, compareGpuAddr, data, mask, (m_subEngineType == SubEngineType::ConstantEngine), pPacket);
}

// =====================================================================================================================
size_t CmdStream::BuildIndirectBuffer(
    gpusize  ibAddr,
    uint32   ibSize,
    bool     preemptionEnabled,
    bool     chain,
    uint32*  pPacket
    ) const
{
    return m_cmdUtil.BuildIndirectBuffer(GetEngineType(),
                                         ibAddr,
                                         ibSize,
                                         chain,
                                         (m_subEngineType == SubEngineType::ConstantEngine),
                                         preemptionEnabled,
                                         pPacket);
}

// =====================================================================================================================
// Update the address contained within indirect buffer packets associated with the current command block
void CmdStream::PatchCondIndirectBuffer(
    ChainPatch*  pPatch,
    gpusize      address,
    uint32       ibSizeDwords
    ) const
{
    PM4_PFP_COND_INDIRECT_BUFFER* pPacket = static_cast<PM4_PFP_COND_INDIRECT_BUFFER*>(pPatch->pPacket);

    switch (pPatch->type)
    {
    case ChainPatchType::CondIndirectBufferPass:
        // The PM4 spec says that the first IB base/size are used if the conditional passes.
        pPacket->ordinal9.u32All       = LowPart(address);
        pPacket->ordinal10.ib_base1_hi = HighPart(address);
        PAL_ASSERT(pPacket->ordinal9.bitfields.reserved1 == 0);

        pPacket->ordinal11.bitfields.ib_size1 = ibSizeDwords;
        break;

    case ChainPatchType::CondIndirectBufferFail:
        // The PM4 spec says that the second IB base/size are used if the conditional fails.
        pPacket->ordinal12.u32All      = LowPart(address);
        pPacket->ordinal13.ib_base2_hi = HighPart(address);
        PAL_ASSERT(pPacket->ordinal12.bitfields.reserved1 == 0);

        pPacket->ordinal14.bitfields.ib_size2 = ibSizeDwords;
        break;

    default:
        // Other patch types should be handled by the base class
        PAL_ASSERT_ALWAYS();
        break;
    } // end switch
}

// =====================================================================================================================
void CmdStream::BeginCurrentChunk()
{
    // Allocate a preamble with enough space for a DMA_DATA packet. We will patch it to DMA the stream contents into
    // the gfxL2 to improve command fetch performance.
    if (m_flags.prefetchCommands)
    {
        m_pChunkPreamble = AllocCommandSpace(CmdUtil::DmaDataSizeDwords);
        m_cmdUtil.BuildNop(CmdUtil::DmaDataSizeDwords, m_pChunkPreamble);
    }
}

// =====================================================================================================================
// Ends the final command block in the current chunk and inserts a chaining packet to chain that block to so other
// command block (perhaps in an external command stream at submit time).
void CmdStream::EndCurrentChunk(
    bool atEndOfStream)
{
    // The body of the old command block is complete so we can end it. Our block postamble is a basic chaining packet.
    uint32*const pChainPacket = EndCommandBlock(m_chainIbSpaceInDwords, true);

    if (m_chainIbSpaceInDwords > 0)
    {
        if (atEndOfStream)
        {
            // Let the GfxCmdStream handle the special chain at the end of each command stream.
            UpdateTailChainLocation(pChainPacket);
        }
        else
        {
            // Fill the chain packet with a NOP and ask for it to be replaced with a real chain to the new chunk.
            m_cmdUtil.BuildNop(m_chainIbSpaceInDwords, pChainPacket);
            AddChainPatch(ChainPatchType::IndirectBuffer, pChainPacket);
        }
    }

    // Patch the preamble to DMA the command data into L2. We need to do this after EndCommandBlock to make sure the
    // postamble is included in the DMA range.
    if (m_pChunkPreamble != nullptr)
    {
        DmaDataInfo dmaInfo = {};
        dmaInfo.srcAddr      = m_chunkList.Back()->GpuVirtAddr();
        dmaInfo.srcAddrSpace = sas__pfp_dma_data__memory;
        dmaInfo.srcSel       = src_sel__pfp_dma_data__src_addr_using_l2;
        dmaInfo.dstSel       = dst_sel__pfp_dma_data__dst_nowhere;
        dmaInfo.numBytes     = m_chunkList.Back()->DwordsAllocated() * sizeof(uint32);
        dmaInfo.usePfp       = true;

        m_cmdUtil.BuildDmaData<false>(dmaInfo, m_pChunkPreamble);
        m_pChunkPreamble = nullptr;
    }
}

// =====================================================================================================================
// Writes a register for performance counters. (Some performance counter reg's are protected and others aren't). Returns
// the size of the PM4 command written, in DWORDs.
uint32* CmdStream::WriteSetOnePerfCtrReg(
    uint32  regAddr,
    uint32  value,
    uint32* pCmdSpace) // [out] Build the PM4 packet in this buffer.
{
    uint32* pReturnVal = nullptr;

    if (m_cmdUtil.IsUserConfigReg(regAddr) == false)
    {
        // Protected register: use our COPY_DATA backdoor to write the register.
        pReturnVal = WriteSetOnePrivilegedConfigReg(regAddr, value, pCmdSpace);
    }
    else
    {
        // Non-protected register: use a normal SET_DATA command.
        if (m_device.Parent()->ChipProperties().gfxLevel != GfxIpLevel::GfxIp9)
        {
            const auto engineType = GetEngineType();

            // The resetFilterCam bit is not valid for the Compute Micro Engine. Setting this bit would cause a hang in
            // compute-only engines.
            if (engineType == EngineTypeUniversal)
            {
                pReturnVal = WriteSetOneConfigReg<true>(regAddr, value, pCmdSpace);
            }
            else
            {
                pReturnVal = WriteSetOneConfigReg<false>(regAddr, value, pCmdSpace);
            }
        }
        else
        {
            pReturnVal = WriteSetOneConfigReg<false>(regAddr, value, pCmdSpace);
        }
    }

    return pReturnVal;
}

// =====================================================================================================================
// Writes a config register using a COPY_DATA packet. This is a back-door we have to write privileged registers which
// cannot be set using a SET_DATA packet. Returns the size of the PM4 command written, in DWORDs.
uint32* CmdStream::WriteSetOnePrivilegedConfigReg(
    uint32     regAddr,
    uint32     value,
    uint32*    pCmdSpace) // [out] Build the PM4 packet in this buffer.
{
    // We must use the perfcounters select if the target isn't a user config register.
    const ME_COPY_DATA_dst_sel_enum dstSelect = (m_cmdUtil.IsUserConfigReg(regAddr)
                                                 ? dst_sel__me_copy_data__mem_mapped_register
                                                 : dst_sel__me_copy_data__perfcounters);

    // Assert that our register address will fit in the COPY_DATA packet.
    PAL_ASSERT(CmdUtil::CanUseCopyDataRegOffset(regAddr));

    return pCmdSpace + m_cmdUtil.BuildCopyData(GetEngineType(),
                                               engine_sel__me_copy_data__micro_engine,
                                               dstSelect,
                                               regAddr,
                                               src_sel__me_copy_data__immediate_data,
                                               value,
                                               count_sel__me_copy_data__32_bits_of_data,
                                               wr_confirm__me_copy_data__do_not_wait_for_confirmation,
                                               pCmdSpace);
}

// =====================================================================================================================
// Writes a clear state packet and updates the PM4 optimizer if the clear-state packet restored state (i.e., blew
// away everything the PM4 optimizer thought was true).
uint32* CmdStream::WriteClearState(
    PFP_CLEAR_STATE_cmd_enum  clearMode,
    uint32*                   pCmdSpace)
{
    pCmdSpace += m_cmdUtil.BuildClearState(clearMode, pCmdSpace);

    if ((clearMode == cmd__pfp_clear_state__pop_state__HASCLEARSTATE) && (m_pPm4Optimizer != nullptr))
    {
        // We just destroyed all the state, reset the pm4 optimizer
        m_pPm4Optimizer->Reset();
    }

    return pCmdSpace;
}

// =====================================================================================================================
// Marks current PM4 optimizer state as invalid. This is expected to be called after nested command buffer execute.
void CmdStream::NotifyNestedCmdBufferExecute()
{
    if (m_flags.optimizeCommands == 1)
    {
        // The command buffer PM4 optimizer has no knowledge of nested command buffer state.
        // Reset PM4 optimizer state so that subsequent PM4 state does not get incorrectly optimized out.
        m_pPm4Optimizer->Reset();
    }
}

// =====================================================================================================================
// Resets any draw time state in the CmdStream or the Pm4Optimizer.
void CmdStream::ResetDrawTimeState()
{
    m_contextRollDetected = false;

    if (m_flags.optimizeCommands == 1)
    {
        m_pPm4Optimizer->ResetContextRollState();
    }
}

// =====================================================================================================================
// Sets context roll detected state to true if a context roll occurred
template <bool canBeOptimized>
void CmdStream::SetContextRollDetected()
{
    // If the context roll is due to a context register write, the PM4 optimizer may eliminate it. If the context roll
    // is due to an ACQUIRE_MEM, it should not be affected by the PM4 optimizer.
    if ((m_flags.optimizeCommands == 1) && canBeOptimized)
    {
        m_contextRollDetected |= m_pPm4Optimizer->GetContextRollState();
    }
    else
    {
        m_contextRollDetected = true;
    }
}

template
void CmdStream::SetContextRollDetected<true>();
template
void CmdStream::SetContextRollDetected<false>();

#if PAL_DEVELOPER_BUILD
// =====================================================================================================================
// Calls the PAL developer callback to issue a report on how many times SET packets to each SH and context register were
// seen by the optimizer and kept after redundancy checking.
void CmdStream::IssueHotRegisterReport(
    Pm4CmdBuffer* pCmdBuf
    ) const
{
    if (m_pPm4Optimizer != nullptr)
    {
        m_pPm4Optimizer->IssueHotRegisterReport(pCmdBuf);
    }
}
#endif

// =====================================================================================================================
// Allows the caller to temporarily disable the PM4 optimizer if some PM4 must be written.
void CmdStream::TempSetPm4OptimizerMode(
    bool isEnabled)
{
    if (m_pPm4Optimizer != nullptr)
    {
        m_pPm4Optimizer->TempSetPm4OptimizerMode(isEnabled);
    }
}

// =====================================================================================================================
uint32* CmdStream::WriteDynamicLaunchDesc(
    gpusize     launchDescGpuVa,
    uint32*     pCmdSpace)
{
    if (m_cmdUtil.HasEnhancedLoadShRegIndex())
    {
        pCmdSpace += m_cmdUtil.BuildLoadShRegsIndex(index__pfp_load_sh_reg_index__indirect_addr__GFX103COREPLUS,
                                                    data_format__pfp_load_sh_reg_index__offset_and_data,
                                                    launchDescGpuVa,
                                                    0,
                                                    DynamicCsLaunchDescRegCount,
                                                    Pm4ShaderType::ShaderCompute,
                                                    pCmdSpace);
    }
    else
    {
        PAL_ASSERT_ALWAYS();
    }

    if (m_pPm4Optimizer != nullptr)
    {
        m_pPm4Optimizer->HandleDynamicLaunchDesc();
    }

    return pCmdSpace;
}

} // Gfx9
} // Pal


text:
'use strict';

angular.module('myApp').
    config(['$routeProvider', function ($routeProvider) {
        $routeProvider
            .when('/home', {
                templateUrl: '/app/home/homeTemplate.html',
                controller: 'HomeController'
            })
            .when('/about', {
                templateUrl: '/app/about/aboutTemplate.html',
                controller: 'AboutController'
            })
            .otherwise({redirectTo: '/home'});
    }]);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using WebDAVSharp.Server.Adapters;
using WebDAVSharp.Server.Exceptions;
using WebDAVSharp.Server.Stores;

namespace WebDAVSharp.Server.MethodHandlers
{
    /// <summary>
    /// This class implements the <c>MKCOL</c> HTTP method for WebDAV#.
    /// </summary>
    internal class WebDavMkColMethodHandler : WebDavMethodHandlerBase, IWebDavMethodHandler
    {
        /// <summary>
        /// Gets the collection of the names of the HTTP methods handled by this instance.
        /// </summary>
        /// <value>
        /// The names.
        /// </value>
        public IEnumerable<string> Names
        {
            get
            {
                return new[]
                {
                    "MKCOL"
                };
            }
        }

        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param>
        /// <param name="context">The
        /// <see cref="IHttpListenerContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnsupportedMediaTypeException"></exception>
        /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException"></exception>
        public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store)
        {
            if (context.Request.ContentLength64 > 0)
                throw new WebDavUnsupportedMediaTypeException();

            IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url);

            string collectionName = Uri.UnescapeDataString(
                context.Request.Url.Segments.Last().TrimEnd('/', '\\')
                );
            if (collection.GetItemByName(collectionName) != null)
                throw new WebDavMethodNotAllowedException();

            collection.CreateCollection(collectionName);

            context.SendSimpleResponse(HttpStatusCode.Created);
        }
    }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="climb">
        <roleset framnet="" id="climb.01" name="intentional climber" source="verb-climb.01" vncls="51.3.2 51.1">
            <roles>

                <role descr="climber" f="" n="0">
                    <vnrole vncls="51.3.2" vntheta="theme"/>
                    <vnrole vncls="51.1" vntheta="theme"/>
                </role>

                <role descr="thing climbed (clomb" f="" n="1">
                    <vnrole vncls="51.3.2" vntheta="location"/>
                    <vnrole vncls="51.1" vntheta="location"/>
                </role>

                <note/>
            </roles>

            <example name="All arguments" src="ON sense 2" type="">
                <text>Their climb up the north face took nine hours.</text>

                <note>Hopefully  "up the north face" is one constituent, if "up" is separate, it should be ArgM-DIR.</note>
                <arg f="" n="0">Their</arg>
                <rel f="">cimb</rel>
                <arg f="" n="1">up the north face</arg>
            </example>

            <example name="All argument + MNR, metaphorical climb" src="ON sense 2" type="">
                <text>His slow climb out of poverty took years.</text>

                <note>Again, if "out" is separate constituent, it should be ArgM-DIR.</note>
                <arg f="" n="0">His</arg>
                <arg f="mnr" n="m">slow</arg>
                <rel f="">climb</rel>
                <arg f="" n="1">out of poverty</arg>
            </example>

            <note>Roleset based on verb entry climb.01, OntoNotes grouping climb-n senses 2 & 3; maps to VerbNet classes escape-51.1 & run-51.3.2.  Framed by Claire.</note>
        </roleset>
        <roleset framnet="" id="climb.02" name="non-intentional climber; cf rise" source="verb-climb.02" vncls="47.7 45.6-1">
            <roles>

                <role descr="climber" f="" n="1">
                    <vnrole vncls="47.7" vntheta="theme"/>
                    <vnrole vncls="45.6-1" vntheta="patient"/>
                </role>

                <role descr="ext, amount risen" f="" n="2">
                    <vnrole vncls="45.6-1" vntheta="extent"/>
                </role>

                <role descr="start point" f="" n="3"/>

                <role descr="end point" f="" n="4"/>

                <role descr="attribute, when attribute of item is climbing rather than the whole" f="" n="5">
                    <vnrole vncls="45.6-1" vntheta="attribute"/>
                </role>

                <note/>
            </roles>

            <example name="NP only, Args 1 & 4" src="" type="">
                <text>its steady climb back to health</text>
                <arg f="" n="1">its</arg>
                <arg f="mnr" n="m">steady</arg>
                <rel f="">climb</rel>
                <arg f="" n="4">back to health</arg>
                <note/>
            </example>

            <example name="NP only, Arg1" src="" type="">
                <text>the climb in oil prices last month</text>
                <rel f="">climb</rel>
                <arg f="" n="1">in oil prices</arg>
                <arg f="tmp" n="m">last month</arg>
                <note/>
            </example>

            <note>Roleset based on verb entry climb.02, OntoNotes grouping climb-n sense 4; maps to VN classes calibratable_cos-45.6-1 & meander-47.7.  Framed by Claire.</note>
            <example name="" src="web" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>Oil's sudden climb in price halted summer travel plans for many.</text>
                <note>Compare to previous example for better understanding of "attribute" argument, here oil is separate argument from "price."</note>
                <arg f="" n="1">Oil's</arg>
                <arg f="tmp" n="m">sudden</arg>
                <rel f="">climb</rel>
                <arg f="" n="5">in price</arg>
            </example>
            <example name="Arg 1 as "in" PP" src="ON sense 4" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>There are several causes for the recent climb in traffic fatalities.</text>
                <note/>
                <arg f="tmp" n="m">recent</arg>
                <rel f="">climb</rel>
                <arg f="" n="1">in traffic fatalities</arg>
            </example>
            <example name="Args 1, 3 & 4" src="web" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>The "LC," as the company was popularly known, began its climb from modest ranch to cattle empire, and its holdings at the turn of the century stretched from Silver City west to Arizona and from Mule Creek south to Animas - more, it was said, than five hundred thousand acres.</text>
                <note/>
                <arg f="" n="1">its</arg>
                <rel f="">climb</rel>
                <arg f="" n="3">from modest ranch</arg>
                <arg f="" n="4">tp cattle empire</arg>
            </example>
        </roleset>
        <note/>
    </predicate>
    <note/>
</frameset>


text:
const fs = require('fs');
const path = require('path');
var electron_notarize = require('electron-notarize');

const pkg = require('../package.json')

const appleId = process.env.APPLEID;
const appleIdPassword = process.env.APPLEIDPASSWD;
const ascProvider = process.env.TEAM_SHORT_NAME;
const ELECTRON_SKIP_NOTARIZATION = process.env.ELECTRON_SKIP_NOTARIZATION

module.exports = async function (params) {
    // Only notarize the app on Mac OS only.
    if (process.platform !== 'darwin' || ELECTRON_SKIP_NOTARIZATION === 'true') {
      return;
    }
    console.log('afterSign hook triggered', params);
    if(!appleId) throw new Error("no $APPLEID environment variable set");
    if(!appleIdPassword) throw new Error("no $APLEIDPASSWD environment variable set");
    if(!ascProvider) throw new Error("No $TEAM_SHORT_NAME environment variable set");

    const appId = pkg.build.appId
    if (!appId) throw new Error('no appId found in package.json')
    const appPath = path.join(
      params.appOutDir,
      `${params.packager.appInfo.productFilename}.app`
    )
    if (!fs.existsSync(appPath)) {
      throw new Error(`Cannot find application at: ${appPath}`)
    }

    console.log(`Notarizing ${appId} found at ${appPath} with appleId ${appleId}`);

    try {
        await electron_notarize.notarize({
            appBundleId: appId,
            appPath: appPath,
            appleId: appleId,
            appleIdPassword: appleIdPassword,
            ascProvider: ascProvider
        });
    } catch (error) {
        console.error(error);
    }

    console.log(`Done notarizing ${appId}`);
};


text:
<?php

namespace Oro\Bundle\EntityMergeBundle\EventListener\DataGrid;

use Oro\Bundle\DataGridBundle\Event\BuildBefore;
use Oro\Bundle\EntityMergeBundle\Metadata\MetadataRegistry;

class MergeMassActionListener
{
    /**
     * @var MetadataRegistry
     */
    protected $metadataRegistry;

    /**
     * @param MetadataRegistry $metadataRegistry
     */
    public function __construct(MetadataRegistry $metadataRegistry)
    {
        $this->metadataRegistry = $metadataRegistry;
    }

    /**
     * Remove mass action if entity config mass action disabled
     *
     * @param BuildBefore $event
     */
    public function onBuildBefore(BuildBefore $event)
    {
        $config = $event->getConfig();

        $massActions = isset($config['mass_actions']) ? $config['mass_actions'] : array();

        if (empty($massActions['merge']['entity_name'])) {
            return;
        }

        $entityName = $massActions['merge']['entity_name'];

        $entityMergeEnable = $this->metadataRegistry->getEntityMetadata($entityName)->is('enable', true);

        if (!$entityMergeEnable) {
            $config->offsetUnsetByPath('[mass_actions][merge]');
        }
    }
}


text:
#include <boost/multiprecision/mpfr.hpp>

using namespace boost::multiprecision;

mpfr_float a;


text:
require_relative '../../api2000/synergy/scope'

module OneviewSDK
  module API2200
    module Synergy
      # Scope resource implementation for API2200 Synergy
      class Scope < OneviewSDK::API2000::Synergy::Scope
      end
    end
  end
end


text:
package ru.atott.combiq.rest.request;

public class MarkdownRequest {

    private String markdown;

    private static MarkdownRequest EXAMPLE;

    static {
        EXAMPLE = new MarkdownRequest();
        EXAMPLE.setMarkdown("Пример запроса");
    }

    public MarkdownRequest() { }

    public String getMarkdown() {
        return markdown;
    }

    public void setMarkdown(String markdown) {
        this.markdown = markdown;
    }
}


text:
menta
=====

Menta es un paquete NPM para extraer y compartir contenido a través de sockets.