text:
package org.netomi.codec;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

import org.apache.commons.codec.CharEncoding;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.StringEncoder;

public class DMSoundex implements StringEncoder {

    private static final String RESOURCE_FILE = "org/netomi/codec/dmrules.txt";

    private static final String COMMENT = "//";
    private static final String DOUBLE_QUOTE = "\"";

    private static final String MULTILINE_COMMENT_END = "*/";
    private static final String MULTILINE_COMMENT_START = "/*";

    private static final Map<Character, List<Rule>> RULES = new HashMap<Character, List<Rule>>();
    private static final Map<Character, Character> FOLDINGS = new HashMap<Character, Character>();

    static {
        final InputStream rulesIS =
                DMSoundex.class.getClassLoader().getResourceAsStream(RESOURCE_FILE);

        if (rulesIS == null) {
            throw new IllegalArgumentException("Unable to load resource: " + RESOURCE_FILE);
        }

        final Scanner scanner = new Scanner(rulesIS, CharEncoding.UTF_8);
        try {
            parseRules(scanner, RESOURCE_FILE, RULES, FOLDINGS);
        } finally {
            scanner.close();
        }

        // sort RULES by pattern length in descending order
        for (Map.Entry<Character, List<Rule>> rule : RULES.entrySet()) {
            List<Rule> ruleList = rule.getValue();
            Collections.sort(ruleList, new Comparator<Rule>() {
                @Override
                public int compare(Rule rule1, Rule rule2) {
                    return rule2.getPatternLength() - rule1.getPatternLength();
                }
            });
        }
    }

    private static void parseRules(final Scanner scanner, final String location,
            final Map<Character, List<Rule>> ruleMapping, final Map<Character, Character> asciiFoldings) {
        int currentLine = 0;
        boolean inMultilineComment = false;

        while (scanner.hasNextLine()) {
            currentLine++;
            final String rawLine = scanner.nextLine();
            String line = rawLine;

            if (inMultilineComment) {
                if (line.endsWith(MULTILINE_COMMENT_END)) {
                    inMultilineComment = false;
                }
                continue;
            }

            if (line.startsWith(MULTILINE_COMMENT_START)) {
                inMultilineComment = true;
            } else {
                // discard comments
                final int cmtI = line.indexOf(COMMENT);
                if (cmtI >= 0) {
                    line = line.substring(0, cmtI);
                }

                // trim leading-trailing whitespace
                line = line.trim();

                if (line.length() == 0) {
                    continue; // empty lines can be safely skipped
                }

                if (line.contains("=")) {
                    // folding
                    final String[] parts = line.split("=");
                    if (parts.length != 2) {
                        throw new IllegalArgumentException("Malformed folding statement split into " + parts.length +
                                " parts: " + rawLine + " in " + location);
                    }
                    final String leftCharacter = parts[0];
                    final String rightCharacter = parts[1];

                    if (leftCharacter.length() != 1 || rightCharacter.length() != 1) {
                        throw new IllegalArgumentException("Malformed folding statement - " +
                                "patterns are not single characters: " + rawLine + " in " + location);
                    }

                    asciiFoldings.put(leftCharacter.charAt(0), rightCharacter.charAt(0));
                } else {
                    // rule
                    final String[] parts = line.split("\\s+");
                    if (parts.length != 4) {
                        throw new IllegalArgumentException("Malformed rule statement split into " + parts.length +
                                " parts: " + rawLine + " in " + location);
                    }
                    try {
                        final String pattern = stripQuotes(parts[0]);
                        final String replacement1 = stripQuotes(parts[1]);
                        final String replacement2 = stripQuotes(parts[2]);
                        final String replacement3 = stripQuotes(parts[3]);

                        final Rule r = new Rule(pattern, replacement1, replacement2, replacement3);
                        final char patternKey = r.pattern.charAt(0);
                        List<Rule> rules = ruleMapping.get(patternKey);
                        if (rules == null) {
                            rules = new ArrayList<Rule>();
                            ruleMapping.put(patternKey, rules);
                        }
                        rules.add(r);
                    } catch (final IllegalArgumentException e) {
                        throw new IllegalStateException(
                                "Problem parsing line '" + currentLine + "' in " + location, e);
                    }
                }
            }
        }
    }

    private static String stripQuotes(String str) {
        if (str.startsWith(DOUBLE_QUOTE)) {
            str = str.substring(1);
        }

        if (str.endsWith(DOUBLE_QUOTE)) {
            str = str.substring(0, str.length() - 1);
        }

        return str;
    }

    @Override
    public Object encode(final Object obj) throws EncoderException {
        if (!(obj instanceof String)) {
            throw new EncoderException(
                    "Parameter supplied to DaitchMokotoffSoundex encode is not of type java.lang.String");
        }
        return encode((String) obj);
    }

    @Override
    public String encode(String source) {
        if (source == null) {
            return null;
        }
        return soundex(source).split("\\|")[0];
    }

    private String cleanup(String input) {
        StringBuilder sb = new StringBuilder();
        for (char ch : input.toCharArray()) {
            if (Character.isWhitespace(ch)) {
                continue;
            }

            ch = Character.toLowerCase(ch);
            if (FOLDINGS.containsKey(ch)) {
                ch = FOLDINGS.get(ch);
            }
            sb.append(ch);
        }
        return sb.toString();
    }

    public String soundex(String source) {
        if (source == null) {
            return null;
        }

        final String input = cleanup(source);

        Set<SoundexContext> branches = new LinkedHashSet<SoundexContext>();
        branches.add(new SoundexContext());

        char lastChar = '\0';
        for (int index = 0; index < input.length(); index++) {
            final char ch = input.charAt(index);

            // ignore whitespace inside a name
            if (Character.isWhitespace(ch)) {
                continue;
            }

            final String inputContext = input.substring(index);

            List<Rule> rules = RULES.get(ch);
            if (rules == null) {
                continue;
            }
            for (Rule rule : rules) {
                if (rule.matches(inputContext)) {
                    String replacements = rule.getReplacement(inputContext, lastChar == '\0');
                    String[] replacementsArray = replacements.split("\\|");

                    Set<SoundexContext> newSet = new LinkedHashSet<SoundexContext>();
                    for (SoundexContext branch : branches) {
                        SoundexContext originalBranch = replacementsArray.length > 1 ? branch.createBranch() : branch;
                        int replacementIndex = 0;
                        for (String nextReplacement : replacementsArray) {
                            if (replacementIndex > 0) {
                                branch = originalBranch.createBranch();
                            }

                            boolean addReplacement =
                                    branch.lastReplacement == null ||
                                    !branch.lastReplacement.endsWith(nextReplacement) ||
                                    //(!nextReplacement.equals(branch.lastReplacement)) ||
                                    (lastChar == 'm' && ch == 'n') ||
                                    (lastChar == 'n' && ch == 'm');

                            if (addReplacement) {
                                branch.sb.append(nextReplacement);
                            }

                            branch.lastReplacement = nextReplacement;
                            if (branch.sb.length() > 6) {
                                branch.sb.delete(6, branch.sb.length());
                            }
                            newSet.add(branch);
                            replacementIndex++;
                        }
                    }

                    branches = newSet;
                    index += rule.getPatternLength() - 1;
                    break;
                }
            }

            lastChar = ch;
        }

        StringBuilder result = new StringBuilder();
        for (SoundexContext branch : branches) {
            while (branch.sb.length() < 6) {
                branch.sb.append('0');
            }
            if (result.length() > 0) {
                result.append('|');
            }
            result.append(branch.sb.substring(0, 6).toString());
        }

        return result.toString();
    }

    private static final class SoundexContext {
        private StringBuilder sb;
        private String lastReplacement;

        protected SoundexContext() {
            sb = new StringBuilder();
            lastReplacement = null;
        }

        public SoundexContext createBranch() {
            SoundexContext context = new SoundexContext();
            context.sb.append(sb.toString());
            context.lastReplacement = this.lastReplacement;
            return context;
        }

        public int hashCode() {
            return sb.toString().hashCode();
        }

        public boolean equals(Object other) {
            if (this == other) {
                return true;
            }
            if (! (other instanceof SoundexContext)) {
                return false;
            }

            return sb.toString().equals(((SoundexContext) other).sb.toString());
        }

        public String toString() {
            return sb.toString();
        }
    }

    public String toString() {
        return RULES.toString();
    }

    private static final class Rule {
        private final String pattern;
        private final String replacementAtStart;
        private final String replacementBeforeVowel;
        private final String replacementDefault;

        protected Rule(final String pattern, final String replacementAtStart,
                       final String replacementBeforeVowel, final String replacementDefault) {
            this.pattern = pattern;
            this.replacementAtStart = replacementAtStart;
            this.replacementBeforeVowel = replacementBeforeVowel;
            this.replacementDefault = replacementDefault;
        }

        public int getPatternLength() {
            return pattern.length();
        }

        public boolean matches(final String context) {
            return context.startsWith(pattern);
        }

        public String getReplacement(final String context, final boolean atStart) {
            if (atStart) {
                return replacementAtStart;
            }

            int nextIndex = getPatternLength();
            boolean nextCharIsVowel = nextIndex < context.length() ? isVowel(context.charAt(nextIndex)) : false;
            if (nextCharIsVowel) {
                return replacementBeforeVowel;
            }

            return replacementDefault;
        }

        private boolean isVowel(final char ch) {
            return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
        }

        public String toString() {
            return String.format("%s=(%s,%s,%s)", pattern, replacementAtStart,
                                 replacementBeforeVowel, replacementDefault);
        }
    }
}


text:
* A simple polynomial calculator in Common Lisp

* Polynomials are in the form:

        '(((SYMBOL EXPONENT) MULTIPLIER) ((SYMBOL EXPONENT) MULTIPLIER))

* For example this:

        '(((x 2) 5) ((((x y) (2 3)) 5))) = 5x^2 + 5x^2y^3

* The functions that exist are poly+ poly- poly*, all three take two inputs,
  polynomials in the form described above, and output polynomials in the same
  format. They perform the respective operations addition, subtraction and
  multiplication.

Below you can see an example of the test output:

    [25]> (load "tests.cl")
    ;; Loading file tests.cl ...
    ;;  Loading file poly.cl ...
    ;;  Loaded file poly.cl
    ;; Loaded file tests.cl
    T
    [26]> (run-tests)
    5x^2 + 3x^2 ... passed - simple addition
    5x^2+6y^2 + 3x^2+3y^2+4z^3 ... passed - complex addition
    5x^2 - 3x^2 ... passed - simple subtraction
    5x^2+6y^2 - 3x^2+3y^2+4z^3 ... passed - complex subtraction
    5x^2 * 5x^2 ... passed - simple multiplication
    (5x^2+y^2) * (3x + y) ... passed - complex multiplication
    T
    [27]>

redpajama_set_name: RedPajamaGithub


text:
namespace v8 {
namespace internal {

BUILTIN(MapPrototypeClear) {
  HandleScope scope(isolate);
  const char* const kMethodName = "Map.prototype.clear";
  CHECK_RECEIVER(JSMap, map, kMethodName);
  JSMap::Clear(isolate, map);
  return ReadOnlyRoots(isolate).undefined_value();
}

BUILTIN(SetPrototypeClear) {
  HandleScope scope(isolate);
  const char* const kMethodName = "Set.prototype.clear";
  CHECK_RECEIVER(JSSet, set, kMethodName);
  JSSet::Clear(isolate, set);
  return ReadOnlyRoots(isolate).undefined_value();
}

}  // namespace internal
}  // namespace v8


text:
require 'test_helper'

class RailsenginetestTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, Railsenginetest
  end
end


text:
#include "DepotsView.h"

#include <stdlib.h>
#include <Alert.h>
#include <Button.h>
#include <Catalog.h>
#include <ColumnTypes.h>
#include <LayoutBuilder.h>
#include <MessageRunner.h>
#include <ScrollBar.h>
#include <SeparatorView.h>
#include <package/PackageRoster.h>
#include <package/RepositoryConfig.h>

#include "constants.h"

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "DepotsView"

static const BString kTitleEnabled = B_TRANSLATE_COMMENT("Enabled",
	"Column title");
static const BString kTitleName = B_TRANSLATE_COMMENT("Name", "Column title");
static const BString kTitleUrl = B_TRANSLATE_COMMENT("URL", "Column title");
static const BString kLabelRemove = B_TRANSLATE_COMMENT("Remove",
	"Button label");
static const BString kLabelRemoveAll = B_TRANSLATE_COMMENT("Remove All",
	"Button label");
static const BString kLabelEnable = B_TRANSLATE_COMMENT("Enable",
	"Button label");
static const BString kLabelEnableAll = B_TRANSLATE_COMMENT("Enable All",
	"Button label");
static const BString kLabelDisable = B_TRANSLATE_COMMENT("Disable",
	"Button label");
static const BString kLabelDisableAll = B_TRANSLATE_COMMENT("Disable All",
	"Button label");
static const BString kStatusViewText = B_TRANSLATE_COMMENT("Changes pending:",
	"Status view text");
static const BString kStatusCompletedText = B_TRANSLATE_COMMENT("Changes completed",
	"Status view text");

DepotsListView::DepotsListView(const char* name)
	:
	BColumnListView(name, B_NAVIGABLE, B_PLAIN_BORDER)
{
}

void
DepotsListView::KeyDown (const char *bytes, int32 numBytes)
{
	switch(bytes[0]) {
		case B_DELETE:
		{
			Window()->PostMessage(DELETE_KEY_PRESSED);
			break;
		}
		default:
			BColumnListView::KeyDown(bytes, numBytes);
	}
}

DepotsView::DepotsView()
	:
	BView("depotsview", B_SUPPORTS_LAYOUT),
	fTaskLooper(NULL),
	fShowCompletedStatus(false),
	fRunningTaskCount(0),
	fLastCompletedTimerId(0)
{
	// Column list view with 3 columns
	fListView = new DepotsListView("list");
	fListView->SetSelectionMessage(new BMessage(LIST_SELECTION_CHANGED));
	float col0width = be_plain_font->StringWidth(kTitleEnabled) + 15;
	float col1width = be_plain_font->StringWidth(kTitleName) + 15;
	float col2width = be_plain_font->StringWidth(kTitleUrl) + 15;
	fListView->AddColumn(new BStringColumn(kTitleEnabled, col0width, col0width,
		col0width, B_TRUNCATE_END, B_ALIGN_CENTER), kEnabledColumn);
	fListView->AddColumn(new BStringColumn(kTitleName, 90, col1width, 300,
		B_TRUNCATE_END), kNameColumn);
	fListView->AddColumn(new BStringColumn(kTitleUrl, 500, col2width, 5000,
		B_TRUNCATE_END), kUrlColumn);
	fListView->SetInvocationMessage(new BMessage(ITEM_INVOKED));

	// Depot list status view
	fStatusContainerView = new BView("status", B_SUPPORTS_LAYOUT);
	BString templateText(kStatusViewText);
	templateText.Append(" 88");
		// Simulate a status text with two digit queue count
	fListStatusView = new BStringView("status", templateText);

	// Set a smaller fixed font size and slightly lighten text color
	BFont font(be_plain_font);
	font.SetSize(10.0f);
	fListStatusView->SetFont(&font, B_FONT_SIZE);
	fListStatusView->SetHighUIColor(fListStatusView->HighUIColor(), .9f);

	// Set appropriate explicit view sizes
	float viewWidth = max_c(fListStatusView->StringWidth(templateText),
		fListStatusView->StringWidth(kStatusCompletedText));
	BSize statusViewSize(viewWidth + 3, B_H_SCROLL_BAR_HEIGHT - 2);
	fListStatusView->SetExplicitSize(statusViewSize);
	statusViewSize.height += 1;
	fStatusContainerView->SetExplicitSize(statusViewSize);
	BLayoutBuilder::Group<>(fStatusContainerView, B_HORIZONTAL, 0)
		.Add(new BSeparatorView(B_VERTICAL))
		.AddGroup(B_VERTICAL, 0)
			.AddGlue()
			.AddGroup(B_HORIZONTAL, 0)
				.SetInsets(2,0,0,0)
				.Add(fListStatusView)
				.AddGlue()
			.End()
			.Add(new BSeparatorView(B_HORIZONTAL))
		.End();
	fListView->AddStatusView(fStatusContainerView);

	// Standard buttons
	fEnableButton = new BButton(kLabelEnable,
		new BMessage(ENABLE_BUTTON_PRESSED));
	fDisableButton = new BButton(kLabelDisable,
		new BMessage(DISABLE_BUTTON_PRESSED));

	// Create buttons with fixed size
	font_height fontHeight;
	GetFontHeight(&fontHeight);
	int16 buttonHeight = int16(fontHeight.ascent + fontHeight.descent + 12);
		// button size determined by font size
	BSize btnSize(buttonHeight,buttonHeight);

	fAddButton = new BButton("plus", "+", new BMessage(ADD_REPO_WINDOW));
	fAddButton->SetExplicitSize(btnSize);
	fRemoveButton = new BButton("minus", "-", new BMessage(REMOVE_REPOS));
	fRemoveButton->SetExplicitSize(btnSize);
	fAboutButton = new BButton("about", "?", new BMessage(SHOW_ABOUT));
	fAboutButton->SetExplicitSize(btnSize);

	// Layout
	int16 buttonSpacing = 1;
	BLayoutBuilder::Group<>(this, B_VERTICAL, 0)
		.SetInsets(B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING,
			B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING)
		.AddGroup(B_HORIZONTAL, 0, 0.0)
			.Add(new BStringView("instruction",
				B_TRANSLATE_COMMENT("Select depots to use with Haiku package "\
					"management:", "Label text")), 0.0)
			.AddGlue()
			.Add(fAboutButton, 0.0)
		.End()
		.AddStrut(3)
		.Add(fListView, 1)
		.AddGroup(B_HORIZONTAL, 0, 0.0)
			// Add and Remove buttons
			.AddGroup(B_VERTICAL, 0, 0.0)
				.AddGroup(B_HORIZONTAL, 0, 0.0)
					.Add(new BSeparatorView(B_VERTICAL))
					.AddGroup(B_VERTICAL, 0, 0.0)
						.AddGroup(B_HORIZONTAL, buttonSpacing, 0.0)
							.SetInsets(buttonSpacing)
							.Add(fAddButton)
							.Add(fRemoveButton)
						.End()
						.Add(new BSeparatorView(B_HORIZONTAL))
					.End()
					.Add(new BSeparatorView(B_VERTICAL))
				.End()
				.AddGlue()
			.End()
			// Enable and Disable buttons
			.AddGroup(B_HORIZONTAL)
				.SetInsets(B_USE_DEFAULT_SPACING, B_USE_DEFAULT_SPACING,
					B_USE_DEFAULT_SPACING, 0)
				.AddGlue()
				.Add(fEnableButton)
				.Add(fDisableButton)
			.End()
		.End();
}

DepotsView::~DepotsView()
{
	if(fTaskLooper) {
		fTaskLooper->Lock();
		fTaskLooper->Quit();
	}
	_EmptyList();
}

void
DepotsView::AllAttached()
{
	BView::AllAttached();
	fRemoveButton->SetTarget(this);
	fEnableButton->SetTarget(this);
	fDisableButton->SetTarget(this);
	fListView->SetTarget(this);
	fRemoveButton->SetEnabled(false);
	fEnableButton->SetEnabled(false);
	fDisableButton->SetEnabled(false);
	_UpdateStatusView();
	_InitList();
}

void
DepotsView::AttachedToWindow()
{
	fTaskLooper = new TaskLooper(Window());
}

void
DepotsView::MessageReceived(BMessage* message)
{
	switch(message->what)
	{
		case REMOVE_REPOS :{
			RepoRow *rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection());
			if(!rowItem || !fRemoveButton->IsEnabled())
				break;

			BString text;
			// More than one selected row
			if(fListView->CurrentSelection(rowItem)) {
				text.SetTo(B_TRANSLATE_COMMENT("Remove these depots?",
					"Removal alert confirmation message"));
				text.Append("\n");
			}
			// Only one selected row
			else {
				text.SetTo(B_TRANSLATE_COMMENT("Remove this depot?",
					"Removal alert confirmation message"));
				text.Append("\n");
			}
			float minWidth = 0;
			while(rowItem)
			{
				BString repoText;
				repoText.Append("\n").Append(rowItem->Name())
					.Append(" (").Append(rowItem->Url()).Append(")");
				minWidth = max_c(minWidth, StringWidth(repoText.String()));
				text.Append(repoText);
				rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection(rowItem));
			}
			minWidth = min_c(minWidth, Frame().Width());
				// Ensure alert window isn't much larger than the main window
			BAlert *alert = new BAlert("confirm", text, kRemoveLabel,
				kCancelLabel, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT);
			alert->TextView()->SetExplicitMinSize(BSize(minWidth, B_SIZE_UNSET));
			alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
			int32 answer = alert->Go();
			// User presses Cancel button
			if(answer)
				break;

			rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection());
			while(rowItem)
			{
				RepoRow *oldRow = rowItem;
				rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection(rowItem));
				fListView->RemoveRow(oldRow);
				delete oldRow;
			}
			_SaveList();
			break;
		}
		case LIST_SELECTION_CHANGED: {
			_UpdateButtons();
			break;
		}
		case ITEM_INVOKED: {
			// Simulates pressing whichever is the enabled button
			if(fEnableButton->IsEnabled())
			{
				BMessage invokeMessage(ENABLE_BUTTON_PRESSED);
				MessageReceived(&invokeMessage);
			}
			else if(fDisableButton->IsEnabled())
			{
				BMessage invokeMessage(DISABLE_BUTTON_PRESSED);
				MessageReceived(&invokeMessage);
			}
			break;
		}
		case ENABLE_BUTTON_PRESSED: {
			BStringList names;
			bool paramsOK = true;
			// Check if there are multiple selections of the same depot,
			// pkgman won't like that
			RepoRow* rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection());
			while(rowItem)
			{
				if(names.HasString(rowItem->Name())
					&& kNewRepoDefaultName.Compare(rowItem->Name()) != 0) {
					(new BAlert("duplicate",
						B_TRANSLATE_COMMENT("Only one URL for each depot can "
							"be enabled.  Please change your selections.",
							"Error message"),
						kOKLabel, NULL, NULL,
						B_WIDTH_AS_USUAL, B_STOP_ALERT))->Go(NULL);
					paramsOK = false;
					break;
				}
				else
					names.Add(rowItem->Name());
				rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection(rowItem));
			}
			if(paramsOK) {
				_AddSelectedRowsToQueue();
				_UpdateButtons();
			}
			break;
		}
		case DISABLE_BUTTON_PRESSED: {
			_AddSelectedRowsToQueue();
			_UpdateButtons();
			break;
		}
		case TASK_STARTED: {
			int16 count;
			status_t result1 = message->FindInt16(key_count, &count);
			RepoRow *rowItem;
			status_t result2 = message->FindPointer(key_rowptr, (void**)&rowItem);
			if(result1 == B_OK && result2 == B_OK)
				_TaskStarted(rowItem, count);
			break;
		}
		case TASK_COMPLETED_WITH_ERRORS: {
			BString errorDetails;
			status_t result = message->FindString(key_details, &errorDetails);
			if(result == B_OK) {
				// TODO seperate details view?
				(new BAlert("error", errorDetails, kOKLabel, NULL, NULL,
					B_WIDTH_AS_USUAL, B_STOP_ALERT))->Go(NULL);
			}
			BString repoName = message->GetString(key_name,
				kNewRepoDefaultName.String());
			int16 count;
			status_t result1 = message->FindInt16(key_count, &count);
			RepoRow *rowItem;
			status_t result2 = message->FindPointer(key_rowptr, (void**)&rowItem);
			if(result1 == B_OK && result2 == B_OK) {
				_TaskCompleted(rowItem, count, repoName);
				// Refresh the enabled status of each row since it is unsure what
				// caused the error
				_RefreshList();
			}
			_UpdateButtons();
			break;
		}
		case TASK_COMPLETED: {
			BString repoName = message->GetString(key_name,
				kNewRepoDefaultName.String());
			int16 count;
			status_t result1 = message->FindInt16(key_count, &count);
			RepoRow *rowItem;
			status_t result2 = message->FindPointer(key_rowptr, (void**)&rowItem);
			if(result1 == B_OK && result2 == B_OK) {
				_TaskCompleted(rowItem, count, repoName);
				// If the completed row has siblings then enabling this row may
				// have disabled one of the other siblings, do full refresh.
				if(rowItem->HasSiblings() && rowItem->IsEnabled())
					_RefreshList();
			}
			_UpdateButtons();
			break;
		}
		case TASK_CANCELED: {
			int16 count;
			status_t result1 = message->FindInt16(key_count, &count);
			RepoRow *rowItem;
			status_t result2 = message->FindPointer(key_rowptr, (void**)&rowItem);
			if(result1 == B_OK && result2 == B_OK)
				_TaskCanceled(rowItem, count);
			// Refresh the enabled status of each row since it is unsure what
			// caused the cancelation
			_RefreshList();
			_UpdateButtons();
			break;
		}
		case UPDATE_LIST: {
			_RefreshList();
			_UpdateButtons();
			break;
		}
		case STATUS_VIEW_COMPLETED_TIMEOUT: {
			int32 timerID;
			status_t result = message->FindInt32(key_ID, &timerID);
			if(result == B_OK && timerID == fLastCompletedTimerId)
				_UpdateStatusView();
			break;
		}
		default:
			BView::MessageReceived(message);
	}
}

void
DepotsView::_AddSelectedRowsToQueue()
{
	RepoRow* rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection());
	while(rowItem)
	{
		rowItem->SetTaskState(STATE_IN_QUEUE_WAITING);
		BMessage taskMessage(DO_TASK);
		taskMessage.AddPointer(key_rowptr, rowItem);
		fTaskLooper->PostMessage(&taskMessage);
		rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection(rowItem));
	}
}

void
DepotsView::_TaskStarted(RepoRow *rowItem, int16 count)
{
	fRunningTaskCount = count;
	rowItem->SetTaskState(STATE_IN_QUEUE_RUNNING);
	// Only present a status count if there is more than one task in queue
	if(count > 1)
	{
		_UpdateStatusView();
		fShowCompletedStatus = true;
	}
}

void
DepotsView::_TaskCompleted(RepoRow *rowItem, int16 count, BString& newName)
{
	fRunningTaskCount = count;
	_ShowCompletedStatusIfDone();

	// Update row state and values
	rowItem->SetTaskState(STATE_NOT_IN_QUEUE);
	if(kNewRepoDefaultName.Compare(rowItem->Name()) == 0
		&& newName.Compare("") != 0)
		rowItem->SetName(newName.String());
	_UpdateFromRepoConfig(rowItem);
}

void
DepotsView::_TaskCanceled(RepoRow *rowItem, int16 count)
{
	fRunningTaskCount = count;
	_ShowCompletedStatusIfDone();

	// Update row state and values
	rowItem->SetTaskState(STATE_NOT_IN_QUEUE);
	_UpdateFromRepoConfig(rowItem);
}

void
DepotsView::_ShowCompletedStatusIfDone()
{
	// If this is the last task show completed status text for 3 seconds
	if(fRunningTaskCount==0 && fShowCompletedStatus)
	{
		fListStatusView->SetText(kStatusCompletedText);
		fLastCompletedTimerId = rand();
		BMessage timerMessage(STATUS_VIEW_COMPLETED_TIMEOUT);
		timerMessage.AddInt32(key_ID, fLastCompletedTimerId);
		new BMessageRunner(this, &timerMessage, 3000000, 1);
		fShowCompletedStatus = false;
	}
	else
		_UpdateStatusView();
}

void
DepotsView::_UpdateFromRepoConfig(RepoRow *rowItem)
{
	BPackageKit::BPackageRoster pRoster;
	BPackageKit::BRepositoryConfig repoConfig;
	BString repoName(rowItem->Name());
	status_t result = pRoster.GetRepositoryConfig(repoName, &repoConfig);
	// Repo name was found and the URL matches
	if(result == B_OK && repoConfig.BaseURL().Compare(rowItem->Url())==0)
		rowItem->SetEnabled(true);
	else
		rowItem->SetEnabled(false);
}

void
DepotsView::AddManualRepository(BString url)
{
	BString name(kNewRepoDefaultName);
	BString rootUrl = _GetRootUrl(url);
	bool foundRoot = false;
	int32 index;
	int32 listCount = fListView->CountRows();
	for(index=0; index < listCount; index++)
	{
		RepoRow *repoItem = dynamic_cast<RepoRow*>((fListView->RowAt(index)));
		const char *urlPtr = repoItem->Url();
		// Find an already existing URL
		if(url.ICompare(urlPtr) == 0)
		{
			(new BAlert("duplicate",
				B_TRANSLATE_COMMENT("This depot URL already exists.",
					"Error message"),
				kOKLabel))->Go(NULL);
			return;
		}
		// Use the same name from another repo with the same root url
		if(foundRoot == false && rootUrl.ICompare(urlPtr,
			rootUrl.Length()) == 0) {
			foundRoot = true;
			name = repoItem->Name();
		}
	}
	RepoRow *newRepo = _AddRepo(name, url, false);
	_FindSiblings();
	fListView->DeselectAll();
	fListView->AddToSelection(newRepo);
	_UpdateButtons();
	_SaveList();
}

BString
DepotsView::_GetRootUrl(BString url)
{
	// Find the protocol if it exists
	int32 ww = url.FindFirst("://");
	if(ww == B_ERROR)
		ww = 0;
	else
		ww += 3;
	// Find second /
	int32 rootEnd = url.FindFirst("/", ww+1);
	if(rootEnd == B_ERROR)
		return url;
	rootEnd = url.FindFirst("/", rootEnd+1);
	if(rootEnd == B_ERROR)
		return url;
	else
		return url.Truncate(rootEnd);
}

status_t
DepotsView::_EmptyList()
{
	BRow* row;
	while ((row = fListView->RowAt((int32)0, NULL)) != NULL) {
		fListView->RemoveRow(row);
		delete row;
	}
	return B_OK;
}

void
DepotsView::_InitList()
{
	// Get list of known repositories from the settings file
	int32 index, repoCount;
	BStringList nameList, urlList;
	status_t result = fSettings.GetRepositories(repoCount, nameList, urlList);
	if(result == B_OK) {
		BString name, url;
		for(index=0; index < repoCount; index++)
		{
			name = nameList.StringAt(index);
			url = urlList.StringAt(index);
			_AddRepo(name, url, false);
		}
	}
	_UpdateListFromRoster();
	fListView->SetSortColumn(fListView->ColumnAt(kUrlColumn), false, true);
	fListView->ResizeAllColumnsToPreferred();
}

void
DepotsView::_RefreshList()
{
	// Clear enabled status on all rows
	int32 index, listCount = fListView->CountRows();
	for(index=0; index < listCount; index++)
	{
		RepoRow *repoItem = dynamic_cast<RepoRow*>((fListView->RowAt(index)));
		if(repoItem->TaskState() == STATE_NOT_IN_QUEUE)
			repoItem->SetEnabled(false);
	}
	// Get current list of enabled repositories
	_UpdateListFromRoster();
}

void
DepotsView::_UpdateListFromRoster()
{
	// Get list of currently enabled repositories
	BStringList repositoryNames;
	BPackageKit::BPackageRoster pRoster;
	status_t result = pRoster.GetRepositoryNames(repositoryNames);
	if(result != B_OK) {
		(new BAlert("error",
			B_TRANSLATE_COMMENT("Depots could not retrieve the names of the "
				"currently enabled depots.", "Alert error message"),
			"OK", NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT))->Go(NULL);
		return;
	}
	BPackageKit::BRepositoryConfig repoConfig;
	int16 index, count = repositoryNames.CountStrings();
	for(index=0; index < count; index++) {
		const BString& repoName = repositoryNames.StringAt(index);
		result = pRoster.GetRepositoryConfig(repoName, &repoConfig);
		if(result == B_OK)
			_AddRepo(repoName, repoConfig.BaseURL(), true);
//		else
//			(new BAlert("error", "Error getting repo config", "OK"))->Go(NULL);
	}
	_FindSiblings();
	_SaveList();
}

void
DepotsView::_SaveList()
{
	BStringList nameList, urlList;
	int32 index;
	int32 listCount = fListView->CountRows();
	for(index=0; index < listCount; index++) {
		RepoRow *repoItem = dynamic_cast<RepoRow*>((fListView->RowAt(index)));
		nameList.Add(repoItem->Name());
		urlList.Add(repoItem->Url());
	}
	fSettings.SetRepositories(nameList, urlList);
}

RepoRow*
DepotsView::_AddRepo(BString name, BString url, bool enabled)
{
	// URL must have a protocol
	if(url.FindFirst("://") == B_ERROR)
		return NULL;
	RepoRow *addedRow=NULL;
	int32 index;
	int32 listCount = fListView->CountRows();
	// Find if the repo already exists in list
	for(index=0; index < listCount; index++) {
		RepoRow *repoItem = dynamic_cast<RepoRow*>((fListView->RowAt(index)));
		if(url.ICompare(repoItem->Url()) == 0) {
			// update name and enabled values
			if(name.Compare(repoItem->Name()) != 0)
				repoItem->SetName(name.String());
			repoItem->SetEnabled(enabled);
			addedRow = repoItem;
		}
	}
	if(addedRow == NULL) {
		addedRow = new RepoRow(name, url, enabled);
		fListView->AddRow(addedRow);
	}
	return addedRow;
}

void
DepotsView::_FindSiblings()
{
	BStringList namesFound, namesWithSiblings;
	int32 index, listCount = fListView->CountRows();
	// Find depots names that are duplicated
	for(index=0; index < listCount; index++) {
		RepoRow *repoItem = dynamic_cast<RepoRow*>((fListView->RowAt(index)));
		BString name = repoItem->Name();
		// Ignore newly added repos since we don't know the real name yet
		if(name.Compare(kNewRepoDefaultName)==0)
			continue;
		// First time a name is found- no sibling (yet)
		if(!namesFound.HasString(name))
			namesFound.Add(name);
		// Name was already found once so this name has 2 or more siblings
		else if(!namesWithSiblings.HasString(name))
			namesWithSiblings.Add(name);
	}
	// Set sibling values for each row
	for(index=0; index < listCount; index++) {
		RepoRow *repoItem = dynamic_cast<RepoRow*>((fListView->RowAt(index)));
		BString name = repoItem->Name();
		repoItem->SetHasSiblings(namesWithSiblings.HasString(name));
	}
}

void
DepotsView::_UpdateButtons()
{
	RepoRow *rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection());
	// At least one row is selected
	if(rowItem) {
		bool someAreEnabled = false,
			someAreDisabled = false,
			someAreInQueue = false;
		int32 selectedCount=0;
		RepoRow *rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection());
		while(rowItem) {
			selectedCount++;
			switch(rowItem->TaskState())
			{
				case STATE_IN_QUEUE_WAITING:
				case STATE_IN_QUEUE_RUNNING: {
					someAreInQueue = true;
					break;
				}
			}
			if(rowItem->IsEnabled())
				someAreEnabled = true;
			else
				someAreDisabled = true;
			rowItem = dynamic_cast<RepoRow*>(fListView->CurrentSelection(rowItem));
		}
		// Change button labels depending on which rows are selected
		if(selectedCount>1) {
			fEnableButton->SetLabel(kLabelEnableAll);
			fDisableButton->SetLabel(kLabelDisableAll);
		}
		else {
			fEnableButton->SetLabel(kLabelEnable);
			fDisableButton->SetLabel(kLabelDisable);
		}
		// Set which buttons should be enabled
		fRemoveButton->SetEnabled(!someAreEnabled && !someAreInQueue);
		if((someAreEnabled && someAreDisabled) || someAreInQueue) {
			// there are a mix of enabled and disabled depots selected
			fEnableButton->SetEnabled(false);
			fDisableButton->SetEnabled(false);
		}
		else {
			fEnableButton->SetEnabled(someAreDisabled);
			fDisableButton->SetEnabled(someAreEnabled);
		}

	}
	// No selected rows
	else {
		fEnableButton->SetLabel(kLabelEnable);
		fDisableButton->SetLabel(kLabelDisable);
		fEnableButton->SetEnabled(false);
		fDisableButton->SetEnabled(false);
		fRemoveButton->SetEnabled(false);
	}
}

void
DepotsView::_UpdateStatusView()
{
	if(fRunningTaskCount) {
		BString text(kStatusViewText);
		text.Append(" ");
		text<<fRunningTaskCount;
		fListStatusView->SetText(text);
	}
	else
		fListStatusView->SetText("");
}


text:
import itertools
import sys

num_tests = int(raw_input())

for i in range(num_tests):
    x, y, z = raw_input().split()
    a = int(x)
    b = int(y)
    q = int(z)

    q_list = [int(i) for i in raw_input().split()]

    add = a + b
    sub = max(a,b) - min(a,b)
    adder_list = [a,b,add,sub]

    for query in q_list:
        if query < min(a,b):
            sys.stdout.write('0')
        elif query in adder_list:
            sys.stdout.write('1')
        else:
            two_list = list(itertools.combinations_with_replacement(adder_list,2))
            sum_two_list = []
            for i in range(len(two_list)):
                sum_two_list.append(sum(two_list[i]))
            if query in sum_two_list:
                sys.stdout.write('1')
            else:
                three_list = list(itertools.combinations_with_replacement(adder_list,3))
                sum_three_list = []
                for i in range(len(three_list)):
                    sum_three_list.append(sum(three_list[i]))
                if query in sum_three_list:
                    sys.stdout.write('1')
                else:
                    four_list = list(itertools.combinations_with_replacement(adder_list,4))
                    sum_four_list = []
                    for i in range(len(four_list)):
                        sum_four_list.append(sum(four_list[i]))
                    if query in sum_four_list:
                        sys.stdout.write('1')
                    else:
                        five_list = list(itertools.combinations_with_replacement(adder_list,5))
                        sum_five_list = []
                        for i in range(len(five_list)):
                            sum_five_list.append(sum(five_list[i]))
                        if query in sum_five_list:
                            sys.stdout.write('1')
                        else:
                            six_list = list(itertools.combinations_with_replacement(adder_list,6))
                            sum_six_list = []
                            for i in range(len(six_list)):
                                sum_six_list.append(sum(six_list[i]))
                            if query in sum_six_list:
                                sys.stdout.write('1')
                            else:
                                sys.stdout.write('0')
    print ""


text:
function Shader(gl, vertexSource, fragmentSource){
    this.gl = gl;
    this.program = buildProgram(gl, vertexSource, fragmentSource);
    this.uniformInfos = reflectUniformInformation(gl, this.program);
    this.uniformValues = Object.create(null);
    this.uniformTypes = Object.create(null);
    this.attributeLocations = Object.create(null);
}
module.exports = Shader;
Shader.prototype = {
    use: function() {
        this.gl.useProgram(this.program);
    },
    // does not check for hasOwnProperty on values
    // allows for prototypical inheritance
    uniforms: function (values) {
        for(var name in values) {
            this.setUniform(name, values[name]);
        }
    },
    setUniform: function(name, value){
        var info = this.uniformInfos[name];
        if(!info) {
            console.warn('shader missing uniform', name);
            return;
        }
        var type = info.type;
        if(isUniformTypeScalar(this.gl, type)){
            if(value === this.uniformValues[name]){
                return;
            }
            else {
                this.uniformValues[name] = value;
            }
        }
        else {
            var oldValue = this.uniformValues[name];
            if(oldValue !== undefined) {
                if(compareAndSet(oldValue, value)) return;
            }
            else {
                this.uniformValues[name] = new Float32Array(value);
            }
        }
        setUniform(this.gl, info.location, type, value);
    },
    getUniformLocation: function(name) {
        if(!(name in this.uniformLocations)){
            var location = this.gl.getUniformLocation(this.program, name);
            if(location < 0){
                console.warn('shader missing uniform', name);
            }
            this.uniformLocations[name] = location;
        }
        return this.uniformLocations[name];
    },
    getAttribLocation: function(name) {
        if(!(name in this.attributeLocations)){
            var location = this.gl.getAttribLocation(this.program, name);
            if(location < 0){
                console.warn('shader missing attribute', name);
            }
            this.attributeLocations[name] = location;
        }
        return this.attributeLocations[name];
    }
};

function isUniformTypeScalar(gl, type){
    switch(type){
        case gl.FLOAT:
        case gl.INT:
        case gl.UNSIGNED_INT:
        case gl.SAMPLER_2D:
        case gl.SAMPLER_CUBE:
        case gl.BOOL:
            return true;
        default:
            return false;
    }
}

function setUniform(gl, location, type, value){
    switch(type) {
        case gl.FLOAT:
            gl.uniform1f(location, value);
            break;
        case gl.INT:
        case gl.UNSIGNED_INT:
        case gl.SAMPLER_2D:
        case gl.SAMPLER_CUBE:
        case gl.BOOL:
            gl.uniform1i(location, value);
            break;
        case gl.FLOAT_VEC3:
            gl.uniform3fv(location, value);
            break;
        case gl.FLOAT_VEC2:
            gl.uniform2fv(location, value);
            break;
        case gl.FLOAT_VEC4:
            gl.uniform4fv(location, value);
            break;
        case gl.FLOAT_MAT4:
            gl.uniformMatrix4fv(location, value);
            break;
        case gl.FLOAT_MAT3:
            gl.uniformMatrix3fv(location, value);
            break;
        case gl.FLOAT_MAT2:
            gl.uniformMatrix2fv(location, value);
            break;
        case gl.INT_VEC3:
            gl.uniform3iv(location, value);
            break;
        case gl.INT_VEC2:
            gl.uniform2iv(location, value);
            break;
        case gl.INT_VEC4:
            gl.uniform4iv(location, value);
            break;
        default:
            console.warn('Unknown uniform type', name, type);
    }

}

function reflectUniformInformation(gl, program){
    var uniforms = Object.create(null);
    var nActiveUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
    for(var i = 0; i < nActiveUniforms; i++){
        var uniform = gl.getActiveUniform(program, i);
        uniforms[uniform.name] = {
            type: uniform.type,
            size: uniform.size,
            location: gl.getUniformLocation(program, uniform.name)
        };
    }
    return uniforms;
}

function compileShader(gl, type, source){
    var shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)){
        throw new Error('Shader compiler error: "' + gl.getShaderInfoLog(shader) + '"');
    }
    return shader;
}

function buildProgram(gl, vertexShaderSource, fragmentShaderSource){
    var fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
    var vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
    var program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.bindAttribLocation(program, 0, "aPosition");
    gl.linkProgram(program);
    if(!gl.getProgramParameter(program, gl.LINK_STATUS)){
        throw new Error('Shader linker error: ' + gl.getProgramInfoLog(program));
    }
    return program;
}

// sets a to b
// returns true if a was equal to b already
function compareAndSet(a, b){
    var equal = true;
    for(var i = 0; i < a.length; i++){
        if(a[i] !== b[i]){
            a[i] = b[i];
            equal = false;
        }
    }
    return equal;
}


text:
<?php
$TRANSLATIONS = array(
"Cannot write into \"config\" directory!" => "\"config\" ディレクトリに書き込みができません!",
"This can usually be fixed by giving the webserver write access to the config directory" => "多くの場合、これはWEBサーバーに config ディレクトリへの書き込み権限を付与することで解決が可能です。",
"See %s" => "%s を閲覧",
"This can usually be fixed by %sgiving the webserver write access to the config directory%s." => "多くの場合、これは %sWEBサーバーに config ディレクトリへの書き込み権限を付与%s することで解決が可能です。",
"You are accessing the server from an untrusted domain." => "信頼されていないドメインからサーバーにアクセスしています。",
"Please contact your administrator. If you are an administrator of this instance, configure the \"trusted_domain\" setting in config/config.php. An example configuration is provided in config/config.sample.php." => "管理者に連絡してください。このサーバーの管理者の場合は、\"trusted_domain\" の設定を config/config.php に設定してください。config/config.sample.php にサンプルの設定方法が記載してあります。",
"Help" => "ヘルプ",
"Personal" => "個人",
"Settings" => "設定",
"Users" => "ユーザー",
"Admin" => "管理",
"Failed to upgrade \"%s\"." => "\"%s\" へのアップグレードに失敗しました。",
"App \\\"%s\\\" can't be installed because it is not compatible with this version of ownCloud." => "アプリ \\\"%s\\\" をインストールできません。現在の owncloud のバージョンと互換性がありません。",
"No app name specified" => "アプリ名が未指定",
"Unknown filetype" => "不明なファイルタイプ",
"Invalid image" => "無効な画像",
"web services under your control" => "管理下のウェブサービス",
"App directory already exists" => "アプリディレクトリはすでに存在します",
"Can't create app folder. Please fix permissions. %s" => "アプリフォルダーを作成できませんでした。%s のパーミッションを修正してください。",
"No source specified when installing app" => "アプリインストール時のソースが未指定",
"No href specified when installing app from http" => "アプリインストール時のhttpの URL が未指定",
"No path specified when installing app from local file" => "アプリインストール時のローカルファイルのパスが未指定",
"Archives of type %s are not supported" => "\"%s\"タイプのアーカイブ形式は未サポート",
"Failed to open archive when installing app" => "アプリをインストール中にアーカイブファイルを開けませんでした。",
"App does not provide an info.xml file" => "アプリにinfo.xmlファイルが入っていません",
"App can't be installed because of not allowed code in the App" => "アプリで許可されないコードが入っているのが原因でアプリがインストールできません",
"App can't be installed because it is not compatible with this version of ownCloud" => "アプリは、このバージョンのownCloudと互換性がないためインストールできません。",
"App can't be installed because it contains the <shipped>true</shipped> tag which is not allowed for non shipped apps" => "非shippedアプリには許可されない<shipped>true</shipped>タグが含まれているためにアプリをインストールできません。",
"App can't be installed because the version in info.xml/version is not the same as the version reported from the app store" => "info.xml/versionのバージョンがアプリストアのバージョンと合っていないため、アプリはインストールされません",
"Application is not enabled" => "アプリケーションは無効です",
"Authentication error" => "認証エラー",
"Token expired. Please reload page." => "トークンが無効になりました。ページを再読込してください。",
"Unknown user" => "不明なユーザー",
"%s enter the database username." => "%s のデータベースのユーザー名を入力してください。",
"%s enter the database name." => "%s のデータベース名を入力してください。",
"%s you may not use dots in the database name" => "%s ではデータベース名にドットを利用できないかもしれません。",
"MS SQL username and/or password not valid: %s" => "MS SQL サーバーのユーザー名/パスワードが正しくありません: %s",
"You need to enter either an existing account or the administrator." => "既存のアカウントもしくは管理者のどちらかを入力する必要があります。",
"MySQL/MariaDB username and/or password not valid" => "MySQL/MariaDB のユーザー名及び/またはパスワードが無効",
"DB Error: \"%s\"" => "DBエラー: \"%s\"",
"Offending command was: \"%s\"" => "違反コマンド: \"%s\"",
"MySQL/MariaDB user '%s'@'localhost' exists already." => "MySQL/MariaDB のユーザー '%s'@'localhost' はすでに存在します。",
"Drop this user from MySQL/MariaDB" => "MySQL/MariaDB からこのユーザーを削除",
"MySQL/MariaDB user '%s'@'%%' already exists" => "MySQL/MariaDB のユーザー '%s'@'%%' はすでに存在します",
"Drop this user from MySQL/MariaDB." => "MySQL/MariaDB からこのユーザーを削除。",
"Oracle connection could not be established" => "Oracleへの接続が確立できませんでした。",
"Oracle username and/or password not valid" => "Oracleのユーザー名もしくはパスワードは有効ではありません",
"Offending command was: \"%s\", name: %s, password: %s" => "違反コマンド: \"%s\"、名前: %s、パスワード: %s",
"PostgreSQL username and/or password not valid" => "PostgreSQLのユーザー名もしくはパスワードは有効ではありません",
"Set an admin username." => "管理者のユーザー名を設定",
"Set an admin password." => "管理者のパスワードを設定。",
"Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken." => "WebDAVインターフェースに問題があると思われるため、WEBサーバーはまだファイルの同期を許可するよう適切に設定されていません。",
"Please double check the installation guides." => "インストールガイドをよく確認してください。",
"%s shared »%s« with you" => "%sが あなたと »%s«を共有しました",
"Sharing %s failed, because the file does not exist" => "%s の共有に失敗しました。そのようなファイルは存在しないからです。",
"You are not allowed to share %s" => "%s を共有することを許可されていません。",
"Sharing %s failed, because the user %s is the item owner" => "%s の共有に失敗しました。ユーザー %s がアイテム所有者です。",
"Sharing %s failed, because the user %s does not exist" => "%s の共有に失敗しました。ユーザー %s が存在しません。",
"Sharing %s failed, because the user %s is not a member of any groups that %s is a member of" => "%s の共有に失敗しました。ユーザー %s はどのグループにも属していません。%s は、??のメンバーです。",
"Sharing %s failed, because this item is already shared with %s" => "%s の共有に失敗しました。このアイテムは既に %s で共有されています。",
"Sharing %s failed, because the group %s does not exist" => "%s の共有に失敗しました。グループ %s は存在しません。",
"Sharing %s failed, because %s is not a member of the group %s" => "%s の共有に失敗しました。%s は、グループ %s のメンバーではありません。",
"You need to provide a password to create a public link, only protected links are allowed" => "公開用リンクの作成にはパスワードの設定が必要です",
"Sharing %s failed, because sharing with links is not allowed" => "%s の共有に失敗しました。リンクでの共有は許可されていません。",
"Share type %s is not valid for %s" => "%s の共有方法は、%s には適用できません。",
"Setting permissions for %s failed, because the permissions exceed permissions granted to %s" => "%s の権限設定に失敗しました。%s に許可されている権限を越えています。",
"Setting permissions for %s failed, because the item was not found" => "%s の権限設定に失敗しました。アイテムが存在しません。",
"Sharing backend %s must implement the interface OCP\\Share_Backend" => "%s のバックエンドの共有には、OCP\\Share_Backend インターフェースを実装しなければなりません。",
"Sharing backend %s not found" => "共有バックエンド %s が見つかりません",
"Sharing backend for %s not found" => "%s のための共有バックエンドが見つかりません",
"Sharing %s failed, because the user %s is the original sharer" => "%s の共有に失敗しました。ユーザー %s が元々の共有者であるからです。",
"Sharing %s failed, because the permissions exceed permissions granted to %s" => "%s の共有に失敗しました。%s に付与されている許可を超えているからです。",
"Sharing %s failed, because resharing is not allowed" => "%s の共有に失敗しました。再共有が許されていないからです。",
"Sharing %s failed, because the sharing backend for %s could not find its source" => "%s の共有に失敗しました。%s のバックエンド共有に必要なソースが見つかりませんでした。",
"Sharing %s failed, because the file could not be found in the file cache" => "%s の共有に失敗しました。ファイルキャッシュにファイルがありませんでした。",
"Could not find category \"%s\"" => "カテゴリ \"%s\" が見つかりませんでした",
"seconds ago" => "数秒前",
"_%n minute ago_::_%n minutes ago_" => array("%n 分前"),
"_%n hour ago_::_%n hours ago_" => array("%n 時間前"),
"today" => "今日",
"yesterday" => "1日前",
"_%n day go_::_%n days ago_" => array("%n日前"),
"last month" => "1ヶ月前",
"_%n month ago_::_%n months ago_" => array("%nヶ月前"),
"last year" => "1年前",
"years ago" => "年前",
"Only the following characters are allowed in a username: \"a-z\", \"A-Z\", \"0-9\", and \"_.@-\"" => "ユーザー名で利用できる文字列は、次のものです: \"a-z\", \"A-Z\", \"0-9\", and \"_.@-\"",
"A valid username must be provided" => "有効なユーザー名を指定する必要があります",
"A valid password must be provided" => "有効なパスワードを指定する必要があります",
"The username is already being used" => "ユーザー名はすでに使われています",
"No database drivers (sqlite, mysql, or postgresql) installed." => "データベースドライバー (sqlite, mysql, postgresql) がインストールされていません。",
"Permissions can usually be fixed by %sgiving the webserver write access to the root directory%s." => "多くの場合、パーミッションは %sWEBサーバーにルートディレクトリへの書き込み権限を付与%s することで解決が可能です。",
"Cannot write into \"config\" directory" => "\"config\" ディレクトリに書き込みができません",
"Cannot write into \"apps\" directory" => "\"apps\" ディレクトリに書き込みができません",
"This can usually be fixed by %sgiving the webserver write access to the apps directory%s or disabling the appstore in the config file." => "多くの場合、これは %sWEBサーバーに apps ディレクトリへの書き込み権限を付与%s するか、設定ファイルでアプリストアを無効化することで解決が可能です。",
"Cannot create \"data\" directory (%s)" => "\"data\" ディレクトリ (%s) を作成できません",
"This can usually be fixed by giving the webserver write access to the root directory." => "多くの場合、これはWEBサーバーにルートディレクトリへの書き込み権限を付与することで解決が可能です。",
"Setting locale to %s failed" => "ロケールを %s に設定できませんでした",
"Please install one of theses locales on your system and restart your webserver." => "これらのロケールのいずれかをシステムにインストールし、WEBサーバーを再起動してください。",
"Please ask your server administrator to install the module." => "サーバー管理者にモジュールのインストールを依頼してください。",
"PHP module %s not installed." => "PHP のモジュール %s がインストールされていません。",
"PHP %s or higher is required." => "PHP %s 以上が必要です。",
"Please ask your server administrator to update PHP to the latest version. Your PHP version is no longer supported by ownCloud and the PHP community." => "PHPを最新バージョンに更新するようサーバー管理者に依頼してください。現在のPHPのバージョンは、ownCloud および PHP コミュニティでサポートされていません。",
"PHP Safe Mode is enabled. ownCloud requires that it is disabled to work properly." => "PHPセーフモードは有効です。ownCloud を適切に動作させるには無効化する必要があります。",
"PHP Safe Mode is a deprecated and mostly useless setting that should be disabled. Please ask your server administrator to disable it in php.ini or in your webserver config." => "PHPセーフモードは多くの場合において役に立たない設定のため、無効化すべきです。サーバー管理者に php.ini もしくはWEBサーバー設定で無効化するよう依頼してください。",
"Magic Quotes is enabled. ownCloud requires that it is disabled to work properly." => "マジッククォートは有効です。ownCloud を適切に動作させるには無効化する必要があります。",
"Magic Quotes is a deprecated and mostly useless setting that should be disabled. Please ask your server administrator to disable it in php.ini or in your webserver config." => "マジッククォートは多くの場合において役に立たない設定のため、無効化すべきです。サーバー管理者に php.ini もしくはWEBサーバー設定で無効化するよう依頼してください。",
"PHP modules have been installed, but they are still listed as missing?" => "PHP モジュールはインストールされていますが、まだ一覧に表示されていますか?",
"Please ask your server administrator to restart the web server." => "サーバー管理者にWEBサーバーを再起動するよう依頼してください。",
"PostgreSQL >= 9 required" => "PostgreSQL >= 9 が必要です",
"Please upgrade your database version" => "新しいバージョンのデータベースにアップグレードしてください",
"Error occurred while checking PostgreSQL version" => "PostgreSQL のバージョンチェック中にエラーが発生しました",
"Please make sure you have PostgreSQL >= 9 or check the logs for more information about the error" => "PostgreSQL >= 9 がインストールされているかどうか確認して下さい。もしくは、ログからエラーに関する詳細な情報を確認して下さい。",
"Please change the permissions to 0770 so that the directory cannot be listed by other users." => "ディレクトリが他のユーザーから見えないように、パーミッションを 0770 に変更してください。",
"Data directory (%s) is readable by other users" => "データディレクトリ (%s) は他のユーザーも閲覧することができます",
"Data directory (%s) is invalid" => "データディレクトリ (%s) は無効です",
"Please check that the data directory contains a file \".ocdata\" in its root." => "データディレクトリに \".ocdata\" ファイルが含まれていることを確認して下さい。",
"Could not obtain lock type %d on \"%s\"." => "\"%s\" で %d タイプのロックを取得できませんでした。"
);
$PLURAL_FORMS = "nplurals=1; plural=0;";


text:
/**
 * Utility methods used by the mapper
 */
package com.github.dozermapper.core.util;


text:
@interface UIApplication (LoadXIBDynamically)

-(BOOL)lx_setupWebDAVServer;
-(BOOL)lx_setupWebDAVServerWithPort:(NSUInteger)port;
-(BOOL)lx_setupWebDAVServerWithBasePath:(NSString*)path port:(NSUInteger)port;
-(NSString*)lx_path;

@end


text:
namespace Banana_Chess
{
    internal abstract class Figure : IFigure
    {
        protected TypesOfFigures figureType;
        protected ColorsOfFigures figureColor;
        protected bool onTable;  //Shows if figure is alive
        protected bool imBlocked;   //Set when the figure cannot move in any position/cell
        protected int positionX = 0;
        protected int positionY = 0;

        public abstract void getPossibleCells(bool[,] outArr);

        protected Figure(TypesOfFigures type, ColorsOfFigures color)
        {
            figureType = type;
            figureColor = color;
            onTable = true;
            imBlocked = false; //Initialize this to avoid errors due to weird case of somebody reading this property uninitialized
        }

        protected static bool testIfNextCellIsEmptyAndSetRegard(int i, int j, bool[,] arr, ColorsOfFigures color) //Not used for pawn
        {
            if (i >= 0 && i < 8 && j >= 0 && j < 8)
            {
                if (ChessBoard.Cells[i, j].Empty)
                {
                    arr[i, j] = true; //It is possible
                    return true; //Don't interrupt the iterator inside the caller
                }
                else
                {
                    if (ChessBoard.Cells[i, j].MyFigure.Color != color)
                    {
                        arr[i, j] = true; //It is possible
                    }
                    //Cell was occupied by other color figure and caller needs to stop iteration in this path/direction
                    //regardless of color, because previous cell is always possible so it shouldn't give a problem
                    return false;
                }
            }
            //Position is not inside the board
            return false;
        }

        public TypesOfFigures Type
        {
            get { return figureType; }
        }

        public ColorsOfFigures Color
        {
            get { return figureColor; }
        }

        public bool OnTable
        {
            get { return onTable; }
            set { onTable = value; }
        }

        public bool Blocked
        {
            get { return imBlocked; }
        }

        public int PositionX
        {
            get { return positionX; }
            set { positionX = value; }
        }

        public int PositionY
        {
            get { return positionY; }
            set { positionY = value; }
        }
    }
}


text:
<?php

namespace Jaroska\Grades;

use Jaroska\Parser;
use Symfony\Component\DomCrawler\Crawler;

class GradesParser extends Parser
{
    protected static $url = 'https://is.jaroska.cz/index.php?akce=650';

    /**
     * @param string $html
     * @return Subject[]
     */
    public function parse($html)
    {
        $crawler = new Crawler($html);
        $h3s = $crawler->filter('h3');
        $gradesInSubjectElements = $crawler->filter('.znamkyzpredmetu');
        $subjects = array();
        for ($i = 0; $i <= ((count($h3s) / 2) - 1); $i++) {
            $gradesElement = $gradesInSubjectElements->eq($i);
            $subjectName = $this->parseSubjectName($h3s->eq($i * 2)->text());
            $teachersInfo = $h3s->eq(($i * 2) + 1);
            $subject = new Subject();
            $subject->teacher = new Teacher();
            $subject->teacher->name = $this->parseTeachersName($teachersInfo);
            $subject->teacher->email = $this->parseTeachersEmail($teachersInfo);
            $subject->grades = $this->parseGrades($gradesElement);
            $subjects[$subjectName] = $subject;
        }
        return $subjects;
    }

    /**
     * @param Crawler $crawler
     * @return Grade[]
     */
    private function parseGrades(Crawler $crawler)
    {
        $grades = $crawler->filter("span")
            ->each(function (Crawler $gradeElement) {
                $grade = new Grade;
                $grade->grade = $gradeElement->text();
                $title = $gradeElement->attr('title');
                $parts = explode(' - ', $title, 2);
                $grade->date = strtotime($parts[0]);
                $grade->description = $parts[1];
                $grade->description = str_replace(
                    " - komentář učitele neuveden",
                    '',
                    $grade->description
                );
                $grade->description = trim($grade->description);
                return $grade;
            });
        return $grades;
    }

    /**
     * @param string $str
     * @return string
     */
    private function parseSubjectName($str)
    {
        return str_replace('Předmět: ', '', $str);
    }

    /**
     * @param Crawler $crawler
     * @return string
     */
    private function parseTeachersName(Crawler $crawler)
    {
        $str = $crawler->text();
        $str = str_replace('Vyučující: ', '', $str);
        $str = str_replace('(email)', '', $str);
        return trim($str);
    }

    /**
     * @param Crawler $crawler
     * @return string
     */
    private function parseTeachersEmail(Crawler $crawler)
    {
        $str = $crawler->filter('a')->attr("href");
        return str_replace('mailto:', '', $str);
    }
}


text:
<resources>
    <string name="app_name">common</string>

    <!--volley-->
    <string name="voller_error_no_internet">无网络连接!</string>
    <string name="voller_error_generic_server_down">连接服务器失败!</string>
    <string name="voller_error_generic_error">网络异常,请稍后再试!</string>
    <string name="voller_error_not_found">没有找到请求连接!</string>

    <!--UpdateManage-->
    <string name="soft_update_no">已经是最新版本</string>
    <string name="soft_update_title">软件更新</string>
    <string name="soft_update_info">检测到新版本,立即更新吗</string>
    <string name="soft_update_updatebtn">更新</string>
    <string name="soft_update_later">稍后更新</string>
    <string name="soft_updating">正在更新</string>
    <string name="soft_update_cancel">取消</string>
</resources>


text:
package com.cloud.engine.datacenter.entity.api;

import com.cloud.hypervisor.Hypervisor.HypervisorType;

public interface HostEntity extends DataCenterResourceEntity {

    /**
     * @return # of cores in a machine.  Note two cpus with two cores each returns 4.
     */
    Integer getCpus();

    /**
     * @return speed of each cpu in mhz.
     */
    Long getSpeed();

    /**
     * @return the pod.
     */
    Long getPodId();

    /**
     * @return availability zone.
     */
    long getDataCenterId();

    /**
     * @return type of hypervisor
     */
    HypervisorType getHypervisorType();

    /**
     * @return the mac address of the host.
     */
    String getGuid();

    Long getClusterId();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Account.Models;

namespace Account.Data
{
    public class AccountDbContext : IdentityDbContext<AccountUser>
    {
        public AccountDbContext(DbContextOptions<AccountDbContext> options)
            : base(options)
        {

        }
        public DbSet<Organization> Organizations { get; set; }
    }
}


text:
int positive(const int number);

TEST(PositiveTest,Positive)
{
    EXPECT_EQ(1,positive(2));
}

TEST(PositiveTest,NotPositive)
{
    EXPECT_EQ(0,positive(-1));
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
class PointerStringConverter
{
public:
	template<class T>
	static std::string value_to_string(const T& value)
	{
		using namespace std;

		void *ptr_var = (void*)&value;

		string str;
		str.resize(sizeof(T));
		memcpy((void*)str.c_str(), ptr_var, sizeof(T));
		//sprintf(&str[0], (char*)&ptr_var);

		return str;
	}

	template<class T>
	static T string_to_value(const std::string& str)
	{
		using namespace std;

		T value;

		memcpy((void*)&value, (void*)str.c_str(), sizeof(T));

		//sprintf((char*)&value, str.c_str());

		// cast void pointer to int pointer again
		return value;
	}

	template<class T>
	static std::string pointer_to_string(const T* var_ptr)
	{
		using namespace std;

		// cast to void pointer
		void *ptr_var = (void*)var_ptr;

		// save void pointer as string
		string ptr_str;
		ptr_str.resize(sizeof(void*));
		sprintf(&ptr_str[0], (char*)&ptr_var);

		return ptr_str;
	}

	template<class T>
	static T* string_to_pointer(const std::string& ptr_str)
	{
		using namespace std;

		void *ptr_back = nullptr;
		sprintf((char*)&ptr_back, ptr_str.c_str());

		// cast void pointer to int pointer again
		return (T*)ptr_back;
	}
};


text:
<?xml version="1.0" encoding="utf-8"?>
<!--  -->
<resources>
  <string name="app_name">StarterApplication_ionic</string>
  <string name="push_notification_title">StarterApplication_ionic</string>

  <!-- General purpose strings -->
  <string name="error">Ошибка</string>
  <string name="close">Закрыть</string>
  <string name="cancel">Отмена</string>

  <!--  Settings Screen strings -->
  <string name="worklightSettingsTitle">Настройки Worklight</string>
  <string name="summaryWLServerUrl">Измените URL-адрес сервера: http[s]://домен или IP-адрес[:порт][/корневой контекст]</string>
  <string name="titleWLServerUrl">URL сервера</string>
  <string name="networkSettingsTitleWLServerUrl">Параметры сети</string>
  <string name="OKTitleWLServerUrl">OK</string>
  <string name="titleInvalidWLServerUrl">Недопустимый URL</string>
  <string name="errorInvalidWLServerUrl">%1$s не является допустимым URL-адресом. Допустимым форматом является следующий: http[s]://домен или IP-адрес[:порт][/корневой контекст]</string>
  <string name="serverAddress">Адрес сервера</string>
  <string name="changeServerAddress">Измените URL-адрес сервера</string>

  <!--  Settings Screen: Web Resources category -->
  <string name="wlWebResourcesCategory">Веб-ресурсы</string>
  <string name="wlAppIdTitle">ИД приложения</string>
  <string name="wlAppVersionTitle">Версия приложения</string>
  <string name="downloadingWebResourcesMessage">Загрузка ресурсов приложения (загружено килобайт)</string>

  <!-- Direct Update -->
  <string name="directUpdateDownloadingMessage">Загрузка обновления приложения (загружено килобайт)</string>
  <string name="kb">%1$d/%2$d Кб</string>

  <!-- IBM MobileFirst Platform initialization errors -->
  <string name="worklightInitInternalError">Во время выполнения приложения произошла внутренняя ошибка. Повторно установите приложение и повторите попытку.</string>
  <string name="worklightInitNotEnoughSpace">Не удалось установить приложение из-за нехватки памяти. Освободите %1$s Мб и перезапустите приложение.</string>
</resources>


text:
import sys; sys.path += ['/zoto/aztk/', '/zoto/aztk/lib']
import aztk_config
import psycopg, socket

DB_NAME = aztk_config.services.get('api.database', 'main_db')
DB_USER = aztk_config.services.get('api.database', 'username')
DB_PSWD = aztk_config.services.get('api.database', 'password')

DB_HOSTS = aztk_config.setup.items('interfaces')

image_tables = [
	'activity_log',
	'featured_media',
	'gallery_xref_images',
	'media_binaries',
	'media_binaries_history',
	'modified_image_binaries',
	'storage_assignments',
	'user_image_tags',
	'user_images'
]

def delete_image(host_ip, image):
	con = psycopg.connect("host=%s dbname=%s user=%s password=%s" % (host_ip, DB_NAME, DB_USER, DB_PSWD))
	cur = con.cursor()

	for table in image_tables:
		query = "delete from %s where media_id = '%s'" % (table, image)
		cur.execute(query)

	con.commit()
	cur.close()
	con.close()

if __name__ == "__main__":
	if len(sys.argv) < 2:
		print "Insufficient arguments"

	image_id = sys.argv[1]
	if len(image_id) < 32:
		print "Invalid image id: %s" % image_id
		sys.exit(-1)

	for host, ip in DB_HOSTS:
		print "deleting from %s" % host
		delete_image(ip, image_id)


text:
// -*-Mode: C++;-*- // technically C99

// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *

#ifndef __OMPT_PLACEHOLDERS_H__
#define __OMPT_PLACEHOLDERS_H__

//***************************************************************************
// local include files
//***************************************************************************

#include <hpcrun/utilities/ip-normalized.h>

#include "ompt-types.h"

//***************************************************************************
// macros
//***************************************************************************

#define FOREACH_OMPT_PLACEHOLDER_FN(macro)		\
  /**** OpenMP state placeholders ****/			\
  macro (ompt_idle_state)				\
  macro (ompt_overhead_state)				\
  macro (ompt_barrier_wait_state)			\
  macro (ompt_task_wait_state)				\
  macro (ompt_mutex_wait_state)				\
							\
  /**** OpenMP target operation placeholders ****/	\
  macro (ompt_tgt_alloc)				\
  macro (ompt_tgt_delete)				\
  macro (ompt_tgt_copyin)				\
  macro (ompt_tgt_copyout)				\
  macro (ompt_tgt_kernel)				\
  macro (ompt_tgt_none)					\
  							\
  /**** OpenMP unresolved parallel region ****/		\
  /* The placeholder below is used when the context */	\
  /* for a parallel region remains unresolved at    */	\
  /* the end of a program execution. This can       */	\
  /* happen if an execution is interrupted before   */	\
  /* the region is resolved.                        */	\
  macro (ompt_region_unresolved)

//***************************************************************************
// types
//***************************************************************************

typedef struct {
  void           *pc;
  ip_normalized_t pc_norm;
} ompt_placeholder_t;

typedef struct {
#define declare_ompt_ph(f) ompt_placeholder_t f;
  FOREACH_OMPT_PLACEHOLDER_FN(declare_ompt_ph);
#undef declare_ompt_ph
} ompt_placeholders_t;

//***************************************************************************
// forward declarations
//***************************************************************************

extern ompt_placeholders_t ompt_placeholders;

//***************************************************************************
// interface operations
//***************************************************************************

void
ompt_init_placeholders
(
 void
);

#endif


text:
using namespace llvm;
using namespace dwarf;
using namespace object;

static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
  OS << " (";
  do {
    uint64_t Shift = countTrailingZeros(Val);
    assert(Shift < 64 && "undefined behavior");
    uint64_t Bit = 1ULL << Shift;
    auto PropName = ApplePropertyString(Bit);
    if (!PropName.empty())
      OS << PropName;
    else
      OS << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit);
    if (!(Val ^= Bit))
      break;
    OS << ", ";
  } while (true);
  OS << ")";
}

static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
                       const DWARFAddressRangesVector &Ranges,
                       unsigned AddressSize, unsigned Indent,
                       const DIDumpOptions &DumpOpts) {
  if (!DumpOpts.ShowAddresses)
    return;

  ArrayRef<SectionName> SectionNames;
  if (DumpOpts.Verbose)
    SectionNames = Obj.getSectionNames();

  for (const DWARFAddressRange &R : Ranges) {
    OS << '\n';
    OS.indent(Indent);
    R.dump(OS, AddressSize);

    DWARFFormValue::dumpAddressSection(Obj, OS, DumpOpts, R.SectionIndex);
  }
}

static void dumpLocation(raw_ostream &OS, DWARFFormValue &FormValue,
                         DWARFUnit *U, unsigned Indent,
                         DIDumpOptions DumpOpts) {
  DWARFContext &Ctx = U->getContext();
  const DWARFObject &Obj = Ctx.getDWARFObj();
  const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
  if (FormValue.isFormClass(DWARFFormValue::FC_Block) ||
      FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) {
    ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
    DataExtractor Data(StringRef((const char *)Expr.data(), Expr.size()),
                       Ctx.isLittleEndian(), 0);
    DWARFExpression(Data, U->getVersion(), U->getAddressByteSize())
        .print(OS, MRI, U);
    return;
  }

  FormValue.dump(OS, DumpOpts);
  const auto &DumpLL = [&](auto ExpectedLL) {
    if (ExpectedLL) {
      uint64_t BaseAddr = 0;
      if (Optional<object::SectionedAddress> BA = U->getBaseAddress())
        BaseAddr = BA->Address;
      ExpectedLL->dump(OS, BaseAddr, Ctx.isLittleEndian(), Obj.getAddressSize(),
                       MRI, U, Indent);
    } else {
      OS << '\n';
      OS.indent(Indent);
      OS << formatv("error extracting location list: {0}",
                    fmt_consume(ExpectedLL.takeError()));
    }
  };
  if (FormValue.isFormClass(DWARFFormValue::FC_SectionOffset)) {
    uint64_t Offset = *FormValue.getAsSectionOffset();
    if (!U->isDWOUnit() && !U->getLocSection()->Data.empty()) {
      DWARFDebugLoc DebugLoc;
      DWARFDataExtractor Data(Obj, *U->getLocSection(), Ctx.isLittleEndian(),
                              Obj.getAddressSize());
      DumpLL(DebugLoc.parseOneLocationList(Data, &Offset));
      return;
    }

    bool UseLocLists = !U->isDWOUnit();
    StringRef LoclistsSectionData =
        UseLocLists ? Obj.getLoclistsSection().Data : U->getLocSectionData();

    if (!LoclistsSectionData.empty()) {
      DataExtractor Data(LoclistsSectionData, Ctx.isLittleEndian(),
                         Obj.getAddressSize());

      // Old-style location list were used in DWARF v4 (.debug_loc.dwo section).
      // Modern locations list (.debug_loclists) are used starting from v5.
      // Ideally we should take the version from the .debug_loclists section
      // header, but using CU's version for simplicity.
      DumpLL(DWARFDebugLoclists::parseOneLocationList(
          Data, &Offset, UseLocLists ? U->getVersion() : 4));
    }
  }
}

/// Dump the name encoded in the type tag.
static void dumpTypeTagName(raw_ostream &OS, dwarf::Tag T) {
  StringRef TagStr = TagString(T);
  if (!TagStr.startswith("DW_TAG_") || !TagStr.endswith("_type"))
    return;
  OS << TagStr.substr(7, TagStr.size() - 12) << " ";
}

static void dumpArrayType(raw_ostream &OS, const DWARFDie &D) {
  Optional<uint64_t> Bound;
  for (const DWARFDie &C : D.children())
    if (C.getTag() == DW_TAG_subrange_type) {
      Optional<uint64_t> LB;
      Optional<uint64_t> Count;
      Optional<uint64_t> UB;
      Optional<unsigned> DefaultLB;
      if (Optional<DWARFFormValue> L = C.find(DW_AT_lower_bound))
        LB = L->getAsUnsignedConstant();
      if (Optional<DWARFFormValue> CountV = C.find(DW_AT_count))
        Count = CountV->getAsUnsignedConstant();
      if (Optional<DWARFFormValue> UpperV = C.find(DW_AT_upper_bound))
        UB = UpperV->getAsUnsignedConstant();
      if (Optional<DWARFFormValue> LV =
              D.getDwarfUnit()->getUnitDIE().find(DW_AT_language))
        if (Optional<uint64_t> LC = LV->getAsUnsignedConstant())
          if ((DefaultLB =
                   LanguageLowerBound(static_cast<dwarf::SourceLanguage>(*LC))))
            if (LB && *LB == *DefaultLB)
              LB = None;
      if (!LB && !Count && !UB)
        OS << "[]";
      else if (!LB && (Count || UB) && DefaultLB)
        OS << '[' << (Count ? *Count : *UB - *DefaultLB + 1) << ']';
      else {
        OS << "[[";
        if (LB)
          OS << *LB;
        else
          OS << '?';
        OS << ", ";
        if (Count)
          if (LB)
            OS << *LB + *Count;
          else
            OS << "? + " << *Count;
        else if (UB)
          OS << *UB + 1;
        else
          OS << '?';
        OS << ")]";
      }
    }
}

/// Recursively dump the DIE type name when applicable.
static void dumpTypeName(raw_ostream &OS, const DWARFDie &D) {
  if (!D.isValid())
    return;

  if (const char *Name = D.getName(DINameKind::LinkageName)) {
    OS << Name;
    return;
  }

  // FIXME: We should have pretty printers per language. Currently we print
  // everything as if it was C++ and fall back to the TAG type name.
  const dwarf::Tag T = D.getTag();
  switch (T) {
  case DW_TAG_array_type:
  case DW_TAG_pointer_type:
  case DW_TAG_ptr_to_member_type:
  case DW_TAG_reference_type:
  case DW_TAG_rvalue_reference_type:
  case DW_TAG_subroutine_type:
    break;
  default:
    dumpTypeTagName(OS, T);
  }

  // Follow the DW_AT_type if possible.
  DWARFDie TypeDie = D.getAttributeValueAsReferencedDie(DW_AT_type);
  dumpTypeName(OS, TypeDie);

  switch (T) {
  case DW_TAG_subroutine_type: {
    if (!TypeDie)
      OS << "void";
    OS << '(';
    bool First = true;
    for (const DWARFDie &C : D.children()) {
      if (C.getTag() == DW_TAG_formal_parameter) {
        if (!First)
          OS << ", ";
        First = false;
        dumpTypeName(OS, C.getAttributeValueAsReferencedDie(DW_AT_type));
      }
    }
    OS << ')';
    break;
  }
  case DW_TAG_array_type: {
    dumpArrayType(OS, D);
    break;
  }
  case DW_TAG_pointer_type:
    OS << '*';
    break;
  case DW_TAG_ptr_to_member_type:
    if (DWARFDie Cont =
            D.getAttributeValueAsReferencedDie(DW_AT_containing_type)) {
      dumpTypeName(OS << ' ', Cont);
      OS << "::";
    }
    OS << '*';
    break;
  case DW_TAG_reference_type:
    OS << '&';
    break;
  case DW_TAG_rvalue_reference_type:
    OS << "&&";
    break;
  default:
    break;
  }
}

static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
                          uint64_t *OffsetPtr, dwarf::Attribute Attr,
                          dwarf::Form Form, unsigned Indent,
                          DIDumpOptions DumpOpts) {
  if (!Die.isValid())
    return;
  const char BaseIndent[] = "            ";
  OS << BaseIndent;
  OS.indent(Indent + 2);
  WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);

  if (DumpOpts.Verbose || DumpOpts.ShowForm)
    OS << formatv(" [{0}]", Form);

  DWARFUnit *U = Die.getDwarfUnit();
  DWARFFormValue FormValue = DWARFFormValue::createFromUnit(Form, U, OffsetPtr);

  OS << "\t(";

  StringRef Name;
  std::string File;
  auto Color = HighlightColor::Enumerator;
  if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
    Color = HighlightColor::String;
    if (const auto *LT = U->getContext().getLineTableForUnit(U))
      if (LT->getFileNameByIndex(
              FormValue.getAsUnsignedConstant().getValue(),
              U->getCompilationDir(),
              DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
        File = '"' + File + '"';
        Name = File;
      }
  } else if (Optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
    Name = AttributeValueString(Attr, *Val);

  if (!Name.empty())
    WithColor(OS, Color) << Name;
  else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line)
    OS << *FormValue.getAsUnsignedConstant();
  else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
           FormValue.getAsUnsignedConstant()) {
    if (DumpOpts.ShowAddresses) {
      // Print the actual address rather than the offset.
      uint64_t LowPC, HighPC, Index;
      if (Die.getLowAndHighPC(LowPC, HighPC, Index))
        OS << format("0x%016" PRIx64, HighPC);
      else
        FormValue.dump(OS, DumpOpts);
    }
  } else if (DWARFAttribute::mayHaveLocationDescription(Attr))
    dumpLocation(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4, DumpOpts);
  else
    FormValue.dump(OS, DumpOpts);

  std::string Space = DumpOpts.ShowAddresses ? " " : "";

  // We have dumped the attribute raw value. For some attributes
  // having both the raw value and the pretty-printed value is
  // interesting. These attributes are handled below.
  if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) {
    if (const char *Name =
            Die.getAttributeValueAsReferencedDie(FormValue).getName(
                DINameKind::LinkageName))
      OS << Space << "\"" << Name << '\"';
  } else if (Attr == DW_AT_type) {
    OS << Space << "\"";
    dumpTypeName(OS, Die.getAttributeValueAsReferencedDie(FormValue));
    OS << '"';
  } else if (Attr == DW_AT_APPLE_property_attribute) {
    if (Optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
      dumpApplePropertyAttribute(OS, *OptVal);
  } else if (Attr == DW_AT_ranges) {
    const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
    // For DW_FORM_rnglistx we need to dump the offset separately, since
    // we have only dumped the index so far.
    if (FormValue.getForm() == DW_FORM_rnglistx)
      if (auto RangeListOffset =
              U->getRnglistOffset(*FormValue.getAsSectionOffset())) {
        DWARFFormValue FV = DWARFFormValue::createFromUValue(
            dwarf::DW_FORM_sec_offset, *RangeListOffset);
        FV.dump(OS, DumpOpts);
      }
    if (auto RangesOrError = Die.getAddressRanges())
      dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
                 sizeof(BaseIndent) + Indent + 4, DumpOpts);
    else
      WithColor::error() << "decoding address ranges: "
                         << toString(RangesOrError.takeError()) << '\n';
  }

  OS << ")\n";
}

bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }

bool DWARFDie::isSubroutineDIE() const {
  auto Tag = getTag();
  return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
}

Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
  if (!isValid())
    return None;
  auto AbbrevDecl = getAbbreviationDeclarationPtr();
  if (AbbrevDecl)
    return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
  return None;
}

Optional<DWARFFormValue>
DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
  if (!isValid())
    return None;
  auto AbbrevDecl = getAbbreviationDeclarationPtr();
  if (AbbrevDecl) {
    for (auto Attr : Attrs) {
      if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
        return Value;
    }
  }
  return None;
}

Optional<DWARFFormValue>
DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
  std::vector<DWARFDie> Worklist;
  Worklist.push_back(*this);

  // Keep track if DIEs already seen to prevent infinite recursion.
  // Empirically we rarely see a depth of more than 3 when dealing with valid
  // DWARF. This corresponds to following the DW_AT_abstract_origin and
  // DW_AT_specification just once.
  SmallSet<DWARFDie, 3> Seen;
  Seen.insert(*this);

  while (!Worklist.empty()) {
    DWARFDie Die = Worklist.back();
    Worklist.pop_back();

    if (!Die.isValid())
      continue;

    if (auto Value = Die.find(Attrs))
      return Value;

    if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
      if (Seen.insert(D).second)
        Worklist.push_back(D);

    if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_specification))
      if (Seen.insert(D).second)
        Worklist.push_back(D);
  }

  return None;
}

DWARFDie
DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
  if (Optional<DWARFFormValue> F = find(Attr))
    return getAttributeValueAsReferencedDie(*F);
  return DWARFDie();
}

DWARFDie
DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
  if (auto SpecRef = V.getAsRelativeReference()) {
    if (SpecRef->Unit)
      return SpecRef->Unit->getDIEForOffset(SpecRef->Unit->getOffset() + SpecRef->Offset);
    if (auto SpecUnit = U->getUnitVector().getUnitForOffset(SpecRef->Offset))
      return SpecUnit->getDIEForOffset(SpecRef->Offset);
  }
  return DWARFDie();
}

Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
  return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
}

Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
  if (auto FormValue = find(DW_AT_high_pc)) {
    if (auto Address = FormValue->getAsAddress()) {
      // High PC is an address.
      return Address;
    }
    if (auto Offset = FormValue->getAsUnsignedConstant()) {
      // High PC is an offset from LowPC.
      return LowPC + *Offset;
    }
  }
  return None;
}

bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
                               uint64_t &SectionIndex) const {
  auto F = find(DW_AT_low_pc);
  auto LowPcAddr = toSectionedAddress(F);
  if (!LowPcAddr)
    return false;
  if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
    LowPC = LowPcAddr->Address;
    HighPC = *HighPcAddr;
    SectionIndex = LowPcAddr->SectionIndex;
    return true;
  }
  return false;
}

Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
  if (isNULL())
    return DWARFAddressRangesVector();
  // Single range specified by low/high PC.
  uint64_t LowPC, HighPC, Index;
  if (getLowAndHighPC(LowPC, HighPC, Index))
    return DWARFAddressRangesVector{{LowPC, HighPC, Index}};

  Optional<DWARFFormValue> Value = find(DW_AT_ranges);
  if (Value) {
    if (Value->getForm() == DW_FORM_rnglistx)
      return U->findRnglistFromIndex(*Value->getAsSectionOffset());
    return U->findRnglistFromOffset(*Value->getAsSectionOffset());
  }
  return DWARFAddressRangesVector();
}

void DWARFDie::collectChildrenAddressRanges(
    DWARFAddressRangesVector &Ranges) const {
  if (isNULL())
    return;
  if (isSubprogramDIE()) {
    if (auto DIERangesOrError = getAddressRanges())
      Ranges.insert(Ranges.end(), DIERangesOrError.get().begin(),
                    DIERangesOrError.get().end());
    else
      llvm::consumeError(DIERangesOrError.takeError());
  }

  for (auto Child : children())
    Child.collectChildrenAddressRanges(Ranges);
}

bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
  auto RangesOrError = getAddressRanges();
  if (!RangesOrError) {
    llvm::consumeError(RangesOrError.takeError());
    return false;
  }

  for (const auto &R : RangesOrError.get())
    if (R.LowPC <= Address && Address < R.HighPC)
      return true;
  return false;
}

const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
  if (!isSubroutineDIE())
    return nullptr;
  return getName(Kind);
}

const char *DWARFDie::getName(DINameKind Kind) const {
  if (!isValid() || Kind == DINameKind::None)
    return nullptr;
  // Try to get mangled name only if it was asked for.
  if (Kind == DINameKind::LinkageName) {
    if (auto Name = dwarf::toString(
            findRecursively({DW_AT_MIPS_linkage_name, DW_AT_linkage_name}),
            nullptr))
      return Name;
  }
  if (auto Name = dwarf::toString(findRecursively(DW_AT_name), nullptr))
    return Name;
  return nullptr;
}

uint64_t DWARFDie::getDeclLine() const {
  return toUnsigned(findRecursively(DW_AT_decl_line), 0);
}

void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
                              uint32_t &CallColumn,
                              uint32_t &CallDiscriminator) const {
  CallFile = toUnsigned(find(DW_AT_call_file), 0);
  CallLine = toUnsigned(find(DW_AT_call_line), 0);
  CallColumn = toUnsigned(find(DW_AT_call_column), 0);
  CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
}

/// Helper to dump a DIE with all of its parents, but no siblings.
static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
                                DIDumpOptions DumpOpts, unsigned Depth = 0) {
  if (!Die)
    return Indent;
  if (DumpOpts.ParentRecurseDepth > 0 && Depth >= DumpOpts.ParentRecurseDepth)
    return Indent;
  Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts, Depth + 1);
  Die.dump(OS, Indent, DumpOpts);
  return Indent + 2;
}

void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
                    DIDumpOptions DumpOpts) const {
  if (!isValid())
    return;
  DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
  const uint64_t Offset = getOffset();
  uint64_t offset = Offset;
  if (DumpOpts.ShowParents) {
    DIDumpOptions ParentDumpOpts = DumpOpts;
    ParentDumpOpts.ShowParents = false;
    ParentDumpOpts.ShowChildren = false;
    Indent = dumpParentChain(getParent(), OS, Indent, ParentDumpOpts);
  }

  if (debug_info_data.isValidOffset(offset)) {
    uint32_t abbrCode = debug_info_data.getULEB128(&offset);
    if (DumpOpts.ShowAddresses)
      WithColor(OS, HighlightColor::Address).get()
          << format("\n0x%8.8" PRIx64 ": ", Offset);

    if (abbrCode) {
      auto AbbrevDecl = getAbbreviationDeclarationPtr();
      if (AbbrevDecl) {
        WithColor(OS, HighlightColor::Tag).get().indent(Indent)
            << formatv("{0}", getTag());
        if (DumpOpts.Verbose)
          OS << format(" [%u] %c", abbrCode,
                       AbbrevDecl->hasChildren() ? '*' : ' ');
        OS << '\n';

        // Dump all data in the DIE for the attributes.
        for (const auto &AttrSpec : AbbrevDecl->attributes()) {
          if (AttrSpec.Form == DW_FORM_implicit_const) {
            // We are dumping .debug_info section ,
            // implicit_const attribute values are not really stored here,
            // but in .debug_abbrev section. So we just skip such attrs.
            continue;
          }
          dumpAttribute(OS, *this, &offset, AttrSpec.Attr, AttrSpec.Form,
                        Indent, DumpOpts);
        }

        DWARFDie child = getFirstChild();
        if (DumpOpts.ShowChildren && DumpOpts.ChildRecurseDepth > 0 && child) {
          DumpOpts.ChildRecurseDepth--;
          DIDumpOptions ChildDumpOpts = DumpOpts;
          ChildDumpOpts.ShowParents = false;
          while (child) {
            child.dump(OS, Indent + 2, ChildDumpOpts);
            child = child.getSibling();
          }
        }
      } else {
        OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
           << abbrCode << '\n';
      }
    } else {
      OS.indent(Indent) << "NULL\n";
    }
  }
}

LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); }

DWARFDie DWARFDie::getParent() const {
  if (isValid())
    return U->getParent(Die);
  return DWARFDie();
}

DWARFDie DWARFDie::getSibling() const {
  if (isValid())
    return U->getSibling(Die);
  return DWARFDie();
}

DWARFDie DWARFDie::getPreviousSibling() const {
  if (isValid())
    return U->getPreviousSibling(Die);
  return DWARFDie();
}

DWARFDie DWARFDie::getFirstChild() const {
  if (isValid())
    return U->getFirstChild(Die);
  return DWARFDie();
}

DWARFDie DWARFDie::getLastChild() const {
  if (isValid())
    return U->getLastChild(Die);
  return DWARFDie();
}

iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
  return make_range(attribute_iterator(*this, false),
                    attribute_iterator(*this, true));
}

DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
    : Die(D), Index(0) {
  auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
  assert(AbbrDecl && "Must have abbreviation declaration");
  if (End) {
    // This is the end iterator so we set the index to the attribute count.
    Index = AbbrDecl->getNumAttributes();
  } else {
    // This is the begin iterator so we extract the value for this->Index.
    AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
    updateForIndex(*AbbrDecl, 0);
  }
}

void DWARFDie::attribute_iterator::updateForIndex(
    const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
  Index = I;
  // AbbrDecl must be valid before calling this function.
  auto NumAttrs = AbbrDecl.getNumAttributes();
  if (Index < NumAttrs) {
    AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
    // Add the previous byte size of any previous attribute value.
    AttrValue.Offset += AttrValue.ByteSize;
    uint64_t ParseOffset = AttrValue.Offset;
    auto U = Die.getDwarfUnit();
    assert(U && "Die must have valid DWARF unit");
    AttrValue.Value = DWARFFormValue::createFromUnit(
        AbbrDecl.getFormByIndex(Index), U, &ParseOffset);
    AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
  } else {
    assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
    AttrValue = {};
  }
}

DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
  if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
    updateForIndex(*AbbrDecl, Index + 1);
  return *this;
}

bool DWARFAttribute::mayHaveLocationDescription(dwarf::Attribute Attr) {
  switch (Attr) {
  // From the DWARF v5 specification.
  case DW_AT_location:
  case DW_AT_byte_size:
  case DW_AT_bit_size:
  case DW_AT_string_length:
  case DW_AT_lower_bound:
  case DW_AT_return_addr:
  case DW_AT_bit_stride:
  case DW_AT_upper_bound:
  case DW_AT_count:
  case DW_AT_data_member_location:
  case DW_AT_frame_base:
  case DW_AT_segment:
  case DW_AT_static_link:
  case DW_AT_use_location:
  case DW_AT_vtable_elem_location:
  case DW_AT_allocated:
  case DW_AT_associated:
  case DW_AT_byte_stride:
  case DW_AT_rank:
  case DW_AT_call_value:
  case DW_AT_call_origin:
  case DW_AT_call_target:
  case DW_AT_call_target_clobbered:
  case DW_AT_call_data_location:
  case DW_AT_call_data_value:
  // Extensions.
  case DW_AT_GNU_call_site_value:
  case DW_AT_GNU_call_site_target:
    return true;
  default:
    return false;
  }
}