The extender attribute customizes the Monaco editor with the full client-side API: options before creation, TypeScript declarations, custom languages and more.
Set the extender attribute to run custom JavaScript with callbacks for the lifecycle of the Monaco editor, e.g. to change the options before the editor is created or to add TypeScript declaration files. The inline editor takes a JavaScript expression that evaluates to the extender object; the framed editor takes the URL of a JavaScript file that writes the extender to window.MonacoEnvironment.Extender and runs in the iframe, without access to jQuery or PrimeFaces. The default example loads the jQuery declaration files for autocomplete. Pick an example, edit the extender or the CSS and press Run.
<style>
.monacoEditorBox {
border: 1px solid var(--p-content-border-color);
min-width: 0;
}
.monacoExtenderBox {
border: 1px solid var(--p-primary-color);
min-width: 0;
}
.monacoEditorError {
border: 1px solid var(--p-red-500, #cc3333);
height: 500px;
overflow: auto;
}
.monacoEditorError pre {
word-break: break-all;
white-space: break-spaces;
}
.monacoEditorMessage.p-message {
width: 100%;
padding: 1em;
margin: 1em;
}
</style>
<h:outputScript library="js" name="monacoColorScheme.js"/>
<div class="card">
<h5>Extender</h5>
<p>
Set the <code>extender</code> attribute to run custom JavaScript with callbacks for the lifecycle of the Monaco editor, e.g. to change the options before the editor is created or to add TypeScript declaration files. The inline editor takes a JavaScript expression that evaluates to the extender object; the framed editor takes the URL of a JavaScript file that writes the extender to <code>window.MonacoEnvironment.Extender</code> and runs in the iframe, without access to jQuery or PrimeFaces. The default example loads the jQuery declaration files for autocomplete. Pick an example, edit the extender or the CSS and press <i>Run</i>.
</p>
<h:form id="formExtender">
<p:staticMessage id="extenderInfo" severity="info" styleClass="monacoEditorMessage" escape="false"
summary="#{monacoEditorController.extenderName}" detail="#{monacoEditorController.extenderInfo}" />
<h:panelGrid columns="4">
<!-- Apply the selected extender -->
<p:commandLink id="applyExtender" partialSubmit="true" styleClass="p-button p-button-text-icon-right"
actionListener="#{monacoEditorController.onMonacoExtenderRun}"
process="@this,extenderTabs:monacoExtender,extenderTabs:monacoCss,monacoEditorWrapper" update="customExtenderInline,monacoEditorWrapper">
<span class="p-button-icon-right p-c pi pi-play" style="color:white"></span>
<span class="p-button-text p-c" style="color:white">Run</span>
</p:commandLink>
<!-- Select extender example -->
<p:outputLabel for="extenderExample" value="Extender example: " />
<p:selectOneMenu id="extenderExample" value="#{monacoEditorController.extenderExample}">
<f:selectItems value="#{monacoEditorController.extenderExamples}" />
<p:ajax
process="extenderInfo,extenderTabs:monacoExtender,extenderTabs:monacoCss,monacoEditorWrapper"
listener="#{monacoEditorController.onExtenderExampleChange}"
update="customExtenderInline,extenderInfo,extenderLink,extenderTabs:monacoExtender,extenderTabs:monacoCss,monacoEditorWrapper" />
</p:selectOneMenu>
<p:link id="extenderLink" href="?example=#{monacoEditorController.extenderExample}"
target="_blank"
value="Link to this extender example"/>
</h:panelGrid>
<div style="display:flex">
<!-- Monaco editor for editing the extender -->
<p:tabView id="extenderTabs" style="flex:1">
<p:tab id="extenderCode" title="Extender">
<h:panelGroup id="monacoExtenderWrapper" layout="block" styleClass="monacoExtenderBox">
<pe:monacoEditorFramed id="monacoExtender" widgetVar="monacoExtender"
oninitialized="monacoFollowScheme.call(this)"
value="#{monacoEditorController.valueExtender}" scheme="file"
extender="#{resource['js/monacoExtender.js']}"
iframeUrlParams="{extender: 'monaco', language: 'javascript', tsCheck: true, moreDeclarationUrls: ['#{of:escapeJS(resource['primefaces-extensions:monacoeditor/primefaces-monaco-global.d.ts'])}', '#{of:escapeJS(resource['primefaces-extensions:monacoeditor/primefaces-monaco-module.d.ts'])}'], moreDeclarationNames: ['file:///src/primefaces-monaco-global.d.ts', 'file:///src/primefaces-monaco-module.d.ts']}"
editorOptions="#{monacoEditorController.editorOptionsExtender}"
width="100%" height="500px" autoResize="true"
/>
</h:panelGroup>
</p:tab>
<p:tab id="customCss" title="Custom CSS">
<h:panelGroup id="monacoCssWrapper" layout="block" styleClass="monacoExtenderBox">
<pe:monacoEditorFramed id="monacoCss" widgetVar="monacoCss"
oninitialized="monacoFollowScheme.call(this)"
value="#{monacoEditorController.valueCss}" scheme="file"
extender="#{resource['js/monacoExtender.js']}"
iframeUrlParams="{extender: 'default'}"
language="css"
editorOptions="#{monacoEditorController.editorOptionsCss}"
width="100%" height="500px" autoResize="true"/>
</h:panelGroup>
</p:tab>
</p:tabView>
<!-- Actual editor with the extender applied -->
<!-- window.createShowcaseExtender wraps the createExtender function -->
<!-- defined in the editor above to catch and display errors. -->
<h:panelGroup id="monacoEditorWrapper" layout="block" style="flex:1" styleClass="monacoEditorBox">
<pe:monacoEditor id="monacoEditor" widgetVar="monacoEditor"
oninitialized="monacoFollowScheme.call(this)"
rendered="#{empty monacoEditorController.extenderError}"
value="#{monacoEditorController.value}"
extender="window.createShowcaseExtender()"
editorOptions="#{monacoEditorController.editorOptions}"
width="100%" height="500px" autoResize="true" />
<h:panelGroup layout="block"
rendered="#{not empty monacoEditorController.extenderError}" styleClass="monacoEditorError">
<strong>Could not load custom Monaco editor extender, error was:</strong>
<pre>#{monacoEditorController.extenderError}</pre>
</h:panelGroup>
</h:panelGroup>
</div>
</h:form>
</div>
package org.primefaces.extensions.showcase.controller;
import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang3.StringUtils.abbreviate;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import java.io.Serial;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import jakarta.annotation.PostConstruct;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import jakarta.faces.model.SelectItem;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.extensions.model.monaco.MonacoDiffEditorModel;
import org.primefaces.extensions.model.monacoeditor.DiffEditorOptions;
import org.primefaces.extensions.model.monacoeditor.ELanguage;
import org.primefaces.extensions.model.monacoeditor.ETheme;
import org.primefaces.extensions.model.monacoeditor.EditorOptions;
import org.primefaces.extensions.model.monacoeditor.EditorStandaloneTheme;
import org.primefaces.extensions.showcase.util.MonacoEditorSettings;
/**
* CodeMirrorController
*
* @author Andre Wachsmuth / last modified by $Author$
* @version $Revision$
*/
@Named
@ViewScoped
public class MonacoEditorController implements Serializable {
@Serial
private static final long serialVersionUID = 20210216L;
private static final String CUSTOM_CODE_EXTENDER_CODE = "custom_code.extender.code.";
private static final String CUSTOM_CODE_EXTENDER_DIFF = "custom_code.extender.diff.";
private static final String INLINE = "inline";
private static final String CODE = "code";
private static final String MY_CUSTOM_THEME = "MyCustomTheme";
private Map<String, EditorStandaloneTheme> customThemes;
private EditorOptions editorOptions;
private EditorOptions editorOptionsFramed;
private EditorOptions editorOptionsExtender;
private EditorOptions editorOptionsCss;
private DiffEditorOptions editorOptionsDiff;
private DiffEditorOptions editorOptionsFramedDiff;
private DiffEditorOptions editorOptionsExtenderDiff;
private ELanguage editorLangDiff;
private ELanguage editorLangFramedDiff;
private ELanguage editorLangExtenderDiff;
private transient ResourceBundle examples;
private List<String> languages;
private String extenderError;
private String extenderExample;
private List<SelectItem> extenderExamples;
private List<SelectItem> extenderExamplesDiff;
private String extenderInfo;
private String extenderName;
private List<String> themes;
private String type;
private String mode;
private Locale locale;
private Locale localeFramed;
private List<Locale> locales;
private String value;
private String valueFramed;
private String valueExtender;
private String valueCss;
private MonacoDiffEditorModel valueDiff;
private MonacoDiffEditorModel valueFramedDiff;
private boolean required = false;
private boolean requiredFramed = false;
private boolean disabled = false;
private boolean disabledFramed = false;
private boolean readOnly = false;
private boolean readOnlyFramed = false;
private boolean originalRequired = false;
private boolean originalRequiredFramed = false;
private boolean originalDisabled = true;
private boolean originalDisabledFramed = true;
private boolean originalReadOnly = false;
private boolean originalReadOnlyFramed = false;
@PostConstruct
protected void init() {
this.examples = ResourceBundle.getBundle("monaco-examples");
this.editorOptions = new EditorOptions();
this.editorOptions.setTheme(ETheme.VS);
this.editorOptions.setFontSize(12);
this.editorOptionsDiff = new DiffEditorOptions();
this.editorOptionsDiff.setTheme(ETheme.VS);
this.editorOptionsDiff.setFontSize(12);
this.editorOptionsDiff.setRenderSideBySide(true);
this.editorOptionsFramed = new EditorOptions();
this.editorOptionsFramed.setTheme(ETheme.VS);
this.editorOptionsFramed.setFontSize(12);
this.editorOptionsFramedDiff = new DiffEditorOptions();
this.editorOptionsFramedDiff.setTheme(ETheme.VS);
this.editorOptionsFramedDiff.setFontSize(12);
this.editorOptionsFramedDiff.setRenderSideBySide(true);
this.extenderExamples = MonacoEditorSettings.createEditorExamples();
this.extenderExamplesDiff = MonacoEditorSettings.createEditorExamplesDiff();
this.editorOptionsExtender = MonacoEditorSettings.createEditorOptionsExtender();
this.editorOptionsExtenderDiff = MonacoEditorSettings.createEditorOptionsExtenderDiff();
this.editorOptionsExtenderDiff.setRenderSideBySide(true);
this.editorLangExtenderDiff = ELanguage.JAVASCRIPT;
this.editorOptionsCss = MonacoEditorSettings.createEditorOptionsCss();
this.type = INLINE;
this.languages = Arrays.stream(ELanguage.values()).map(ELanguage::toString).sorted().collect(toList());
this.themes = Arrays.stream(ETheme.values()).map(ETheme::toString).sorted().collect(toList());
this.locales = MonacoEditorSettings.getBuiltInLocales();
}
/**
* @return Custom styling themes that should be made available in the Monaco code editor.
*/
public Map<String, EditorStandaloneTheme> getCustomThemes() {
return customThemes;
}
/**
* @return Options to apply to the Monaco code editor.
*/
public EditorOptions getEditorOptions() {
return editorOptions;
}
/**
* @return Options to apply to the Monaco diff editor.
*/
public DiffEditorOptions getEditorOptionsDiff() {
return editorOptionsDiff;
}
/**
* @return Options to apply to the framed Monaco code editor.
*/
public EditorOptions getEditorOptionsFramed() {
return editorOptionsFramed;
}
/**
* @return Options to apply to the Monaco editor for editing the custom CSS for the extender showcase.
*/
public EditorOptions getEditorOptionsCss() {
return editorOptionsCss;
}
/**
* @return Options to apply to the framed Monaco code editor.
*/
public DiffEditorOptions getEditorOptionsFramedDiff() {
return editorOptionsFramedDiff;
}
/**
* @return Options to apply to the Monaco editor for editing the custom extender.
*/
public EditorOptions getEditorOptionsExtender() {
return editorOptionsExtender;
}
/**
* @return Options to apply to the Monaco editor for editing the custom extender.
*/
public DiffEditorOptions getEditorOptionsExtenderDiff() {
return editorOptionsExtenderDiff;
}
/**
* @return The error that was throw by the custom extender code in the extender showcase.
*/
public String getExtenderError() {
return extenderError;
}
/**
* @return The currently selected example for the extender showcase.
*/
public String getExtenderExample() {
return extenderExample;
}
/***
* @return All examples available in the extender showcase.
*/
public List<SelectItem> getExtenderExamples() {
return extenderExamples;
}
/***
* @return All examples available in the extender showcase.
*/
public List<SelectItem> getExtenderExamplesDiff() {
return extenderExamplesDiff;
}
/**
* @return HTML string with additional info about the loaded extender example.
*/
public String getExtenderInfo() {
return extenderInfo;
}
/**
* @return Name of the loaded extender example.
*/
public String getExtenderName() {
return extenderName;
}
/**
* @return The currently selected code language for the Monaco editor.
*/
public String getLanguage() {
if (CODE.equals(mode)) {
return editorOptions.getLanguage();
}
else {
return editorLangDiff.toString();
}
}
/**
* @return The currently selected code language for the Monaco editor for the extender example.
*/
public String getLanguageExtender() {
if (CODE.equals(mode)) {
return editorOptionsExtender.getLanguage();
}
else {
return editorLangExtenderDiff.toString();
}
}
/**
* @return The currently selected code language for the framed Monaco editor.
*/
public String getLanguageFramed() {
if (CODE.equals(mode)) {
return editorOptionsFramed.getLanguage();
}
else {
return editorLangFramedDiff.toString();
}
}
/**
* @return All available languages for the Monaco editor.
*/
public List<String> getLanguages() {
return languages;
}
/**
* @return The current color theme of the editor.
*/
public String getTheme() {
if (CODE.equals(mode)) {
return editorOptions.getTheme();
}
else {
return editorOptionsDiff.getTheme();
}
}
/**
* @return The current color theme of the framed editor.
*/
public String getThemeFramed() {
if (CODE.equals(mode)) {
return editorOptionsFramed.getTheme();
}
else {
return editorOptionsFramedDiff.getTheme();
}
}
/**
* @return All available themes for the editor.
*/
public List<String> getThemes() {
return themes;
}
/**
* @return Whether to show the inline or framed version of the Monaco code editor.
*/
public String getType() {
return type;
}
/**
* @return The current UI language used in the Monaco code editor.
*/
public Locale getLocale() {
return locale;
}
/**
* @return The current UI language used in the framed Monaco code editor.
*/
public Locale getLocaleFramed() {
return localeFramed;
}
/**
* @return A list of all built-in UI languages for the Monaco code editor.
*/
public List<Locale> getLocales() {
return locales;
}
/**
* @return The code currently being edited by the editor.
*/
public String getValue() {
return value;
}
/**
* @return The code currently being edited by the editor.
*/
public MonacoDiffEditorModel getValueDiff() {
return valueDiff;
}
/**
* @return Code for the Monaco extender that can be edited on the extender showcase page.
*/
public String getValueExtender() {
return valueExtender;
}
/**
* @return The code currently being edited by the framed editor.
*/
public String getValueFramed() {
return valueFramed;
}
/**
* @return The code currently being edited by the framed editor.
*/
public MonacoDiffEditorModel getValueFramedDiff() {
return valueFramedDiff;
}
/**
* @return The custom CSS for the extender showcase.
*/
public String getValueCss() {
return valueCss;
}
/**
* @param valueCss The custom CSS for the extender showcase.
*/
public void setValueCss(final String valueCss) {
this.valueCss = valueCss;
}
/**
* @param extenderExample The currently selected example for the extender showcase.
*/
public void setExtenderExample(final String extenderExample) {
this.extenderExample = extenderExample;
}
/**
* @return Whether the original editor (left side of the diff editor) is disabled.
*/
public boolean isOriginalDisabled() {
return originalDisabled;
}
/**
* @param originalDisabled Whether the original editor (left side of the diff editor) is disabled.
*/
public void setOriginalDisabled(final boolean originalDisabled) {
this.originalDisabled = originalDisabled;
}
/**
* @return Whether the original editor (left side of the diff editor) is disabled.
*/
public boolean isOriginalDisabledFramed() {
return originalDisabledFramed;
}
/**
* @param originalDisabledFramed Whether the original editor (left side of the diff editor) is disabled.
*/
public void setOriginalDisabledFramed(final boolean originalDisabledFramed) {
this.originalDisabledFramed = originalDisabledFramed;
}
/**
* @return Whether the original editor (left side of the diff editor) is read-only.
*/
public boolean isOriginalReadOnly() {
return originalReadOnly;
}
/**
* @param originalReadOnly Whether the original editor (left side of the diff editor) is read-only.
*/
public void setOriginalReadOnly(final boolean originalReadOnly) {
this.originalReadOnly = originalReadOnly;
}
/**
* @return Whether the original framed editor (left side of the diff editor) is read-only.
*/
public boolean isOriginalReadOnlyFramed() {
return originalReadOnlyFramed;
}
/**
* @param originalReadOnlyFramed Whether the original framed editor (left side of the diff editor) is read-only.
*/
public void setOriginalReadOnlyFramed(final boolean originalReadOnlyFramed) {
this.originalReadOnlyFramed = originalReadOnlyFramed;
}
/**
* @return Whether the editor is disabled and does not accept submitted values.
*/
public boolean isDisabled() {
return disabled;
}
/**
* @param disabled Whether the editor is disabled and does not accept submitted values.
*/
public void setDisabled(final boolean disabled) {
this.disabled = disabled;
}
/**
* @return Whether the framed editor is disabled and does not accept submitted values.
*/
public boolean isDisabledFramed() {
return disabledFramed;
}
/**
* @param disabledFramed Whether the framed editor is disabled and does not accept submitted values.
*/
public void setDisabledFramed(final boolean disabledFramed) {
this.disabledFramed = disabledFramed;
}
/**
* @return Whether the modified editor (right side of the diff editor) is read-only.
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* @param readOnly Whether the modified editor (right side of the diff editor) is read-only.
*/
public void setReadOnly(final boolean readOnly) {
this.readOnly = readOnly;
}
/**
* @return Whether the modified editor (right side of the diff editor) is read-only.
*/
public boolean isReadOnlyFramed() {
return readOnlyFramed;
}
/**
* @param readOnlyFramed Whether the modified editor (right side of the diff editor) is read-only.
*/
public void setReadOnlyFramed(final boolean readOnlyFramed) {
this.readOnlyFramed = readOnlyFramed;
}
/**
* @return Whether the editor is required to have a value.
*/
public boolean isRequired() {
return required;
}
/**
* @param required Whether the editor is required to have a value.
*/
public void setRequired(final boolean required) {
this.required = required;
}
/**
* @return Whether the framed editor is required to have a value.
*/
public boolean isRequiredFramed() {
return requiredFramed;
}
/**
* @param requiredFramed Whether the framed editor is required to have a value.
*/
public void setRequiredFramed(final boolean requiredFramed) {
this.requiredFramed = requiredFramed;
}
/**
* @return Whether the original editor is required to have a value.
*/
public boolean isOriginalRequired() {
return originalRequired;
}
/**
* @param originalRequired Whether the original editor is required to have a value.
*/
public void setOriginalRequired(final boolean originalRequired) {
this.originalRequired = originalRequired;
}
/**
* @return Whether the original framed editor is required to have a value.
*/
public boolean isOriginalRequiredFramed() {
return originalRequiredFramed;
}
/**
* @param originalRequiredFramed Whether the original framed editor is required to have a value.
*/
public void setOriginalRequiredFramed(final boolean originalRequiredFramed) {
this.originalRequiredFramed = originalRequiredFramed;
}
/**
* @return Whether to render the diff side-by-side in two editors or inline in one editor.
*/
public boolean isRenderSideBySide() {
if (INLINE.equals(type)) {
return editorOptionsDiff.isRenderSideBySide();
}
else {
return editorOptionsFramedDiff.isRenderSideBySide();
}
}
/**
* @param renderSideBySide Whether to render the diff side-by-side in two editors or inline in one editor.
*/
public void setRenderSideBySide(final boolean renderSideBySide) {
if (INLINE.equals(type)) {
editorOptionsDiff.setRenderSideBySide(renderSideBySide);
}
else {
editorOptionsFramedDiff.setRenderSideBySide(renderSideBySide);
}
}
/**
* @param language The currently selected code language for the monaco editor.
*/
public void setLanguage(final String language) {
if (CODE.equals(mode)) {
if (isEmpty(language)) {
editorOptions.setLanguage(ELanguage.JAVASCRIPT);
}
else {
editorOptions.setLanguage(language);
}
}
else {
if (isEmpty(language)) {
editorLangDiff = ELanguage.JAVASCRIPT;
}
else {
editorLangDiff = ELanguage.parseString(language);
}
}
}
/**
* @param language The currently selected code language for the framed Monaco editor.
*/
public void setLanguageFramed(final String language) {
if (CODE.equals(mode)) {
if (isEmpty(language)) {
editorOptionsFramed.setLanguage(ELanguage.JAVASCRIPT);
}
else {
editorOptionsFramed.setLanguage(language);
}
}
else {
if (isEmpty(language)) {
editorLangFramedDiff = ELanguage.JAVASCRIPT;
}
else {
editorLangFramedDiff = ELanguage.parseString(language);
}
}
}
/**
* @param theme The current color theme of the editor.
*/
public void setTheme(final String theme) {
if (CODE.equals(mode)) {
if (isEmpty(theme)) {
editorOptions.setTheme(ETheme.VS);
}
else {
editorOptions.setTheme(theme);
}
}
else {
if (isEmpty(theme)) {
editorOptionsDiff.setTheme(ETheme.VS);
}
else {
editorOptionsDiff.setTheme(theme);
}
}
}
/**
* @param theme The current color theme of the framed editor.
*/
public void setThemeFramed(final String theme) {
if (CODE.equals(mode)) {
if (isEmpty(theme)) {
editorOptionsFramed.setTheme(ETheme.VS);
}
else {
editorOptionsFramed.setTheme(theme);
}
}
else {
if (isEmpty(theme)) {
editorOptionsFramedDiff.setTheme(ETheme.VS);
}
else {
editorOptionsFramedDiff.setTheme(theme);
}
}
}
/**
* @param type Whether to show the inline or framed version of the Monaco code editor.
*/
public void setType(final String type) {
this.type = type;
}
/**
* @param mode Whether to show the code or diff version of the Monaco code editor.
*/
public void setTypeMode(final String mode) {
this.mode = mode;
}
/**
* @param locale The current UI language used in the Monaco code editor.
*/
public void setLocale(final Locale locale) {
this.locale = locale;
}
/**
* @param localeFramed The current UI language used in the framed Monaco code editor.
*/
public void setLocaleFramed(final Locale localeFramed) {
this.localeFramed = localeFramed;
}
/**
* @param value The code currently being edited by the editor.
*/
public void setValue(final String value) {
this.value = value;
}
/**
* @param valueDiff The code currently being edited by the editor.
*/
public void setValueDiff(final MonacoDiffEditorModel valueDiff) {
this.valueDiff = valueDiff;
}
/**
* @param valueExtender Code for the Monaco extender that can be edited on the extender showcase page.
*/
public void setValueExtender(final String valueExtender) {
this.valueExtender = valueExtender;
}
/**
* @param valueFramed The code currently being edited by the framed editor.
*/
public void setValueFramed(final String valueFramed) {
this.valueFramed = valueFramed;
}
/**
* @param valueFramedDiff The code currently being edited by the framed editor.
*/
public void setValueFramedDiff(final MonacoDiffEditorModel valueFramedDiff) {
this.valueFramedDiff = valueFramedDiff;
}
/**
* Callback for when the code language was changed. Loads the code sample for that language.
*/
public void onLanguageChange() {
if (INLINE.equals(type)) {
loadDefaultCode();
}
else {
loadDefaultCodeFramed();
}
}
/**
* Callback when the selected example was changed in the extender showcase.
*/
public void onExtenderExampleChange() {
loadExtenderExample(extenderExample);
}
/**
* Callback when the run button was pressed in the extender showcase. Resets the error message.
*/
public void onMonacoExtenderRun() {
this.extenderError = null;
}
/**
* Remote command listener when an error occurred in the custom extender entered by the user in the extender showcase.
*/
public void onMonacoExtenderError() {
final HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
.getRequest();
this.extenderError = req.getParameter("monacoExtenderError");
}
/**
* Loads the default code sample for the current language, if available.
*/
private void loadDefaultCode() {
final String language = CODE.equals(mode) ? editorOptions.getLanguage() : editorLangDiff.toString();
final String propertyKey = "sample_code." + language;
loadCode(propertyKey);
}
/**
* Loads the default code sample for the current language, if available.
*/
private void loadDefaultCodeFramed() {
final String language = CODE.equals(mode) ? editorOptionsFramed.getLanguage() : editorLangFramedDiff.toString();
final String propertyKey = "sample_code." + language;
loadCodeFramed(propertyKey);
}
/**
* Loads the code with the given key from the properties file into the code editor.
*
* @param propertyKey Key at which the code is stored in {@code monaco-examples.properties}
*/
private void loadCode(final String propertyKey) {
if (CODE.equals(mode)) {
try {
value = propertyKey != null ? examples.getString(propertyKey) : "";
}
catch (final MissingResourceException e) {
value = "";
}
}
else {
try {
final String original = propertyKey != null ? examples.getString(propertyKey) : "";
final String modified = MonacoEditorSettings.deriveModifiedContent(original);
valueDiff = new MonacoDiffEditorModel(original, modified);
}
catch (final MissingResourceException e) {
valueDiff = MonacoDiffEditorModel.empty();
}
}
}
/**
* Loads the code with the given key from the properties file into the extender editor.
*
* @param propertyKey Key at which the code is stored in {@code monaco-examples.properties}
*/
private void loadCodeExtender(final String propertyKey) {
try {
valueExtender = propertyKey != null ? examples.getString(propertyKey) : "";
}
catch (final MissingResourceException e) {
valueExtender = "";
}
}
/**
* Loads the code with the given key from the properties file into the framed editor.
*
* @param propertyKey Key at which the code is stored in {@code monaco-examples.properties}
*/
private void loadCodeFramed(final String propertyKey) {
if (CODE.equals(mode)) {
try {
valueFramed = propertyKey != null ? examples.getString(propertyKey) : "";
}
catch (final MissingResourceException e) {
valueFramed = "";
}
}
else {
try {
final String original = propertyKey != null ? examples.getString(propertyKey) : "";
final String modified = MonacoEditorSettings.deriveModifiedContent(original);
valueFramedDiff = new MonacoDiffEditorModel(original, modified);
}
catch (final MissingResourceException e) {
valueFramedDiff = MonacoDiffEditorModel.empty();
}
}
}
/**
* Loads the info about the extender example with the given key from the properties file.
*
* @param propertyKey Key at which the info is stored in {@code monaco-examples.properties}
*/
private void loadExtenderInfo(final String propertyKey) {
try {
extenderInfo = propertyKey != null ? examples.getString(propertyKey) : "";
}
catch (final MissingResourceException e) {
extenderInfo = "No info available for this extender. Check the ?example=... URL parameter.";
}
}
/**
* Loads the CSS for the extender example with the given key from the properties file.
*
* @param propertyKey Key at which the CSS is stored in {@code monaco-examples.properties}
*/
private void loadExtenderCss(final String propertyKey) {
try {
valueCss = propertyKey != null ? examples.getString(propertyKey) : "";
}
catch (final MissingResourceException e) {
valueCss = "";
}
}
/**
* Loads the code language for the extender example with the given key from the properties file.
*
* @param propertyKey Key at which the code language is stored in {@code monaco-examples.properties}
*/
private void loadExtenderLanguage(final String propertyKey) {
try {
String language = propertyKey != null ? examples.getString(propertyKey) : "";
language = StringUtils.defaultIfBlank(language, "plaintext");
if (CODE.equals(mode)) {
try {
editorOptions.setLanguage(language);
}
catch (final MissingResourceException e) {
editorOptions.setLanguage(ELanguage.TYPESCRIPT);
}
}
else {
try {
editorLangDiff = ELanguage.parseString(language);
}
catch (final MissingResourceException e) {
editorLangDiff = ELanguage.TYPESCRIPT;
}
}
}
catch (final MissingResourceException e) {
if (CODE.equals(mode)) {
editorOptions.setLanguage(ELanguage.PLAINTEXT);
}
else {
editorLangDiff = ELanguage.PLAINTEXT;
}
}
}
/**
* Loads the name of the extender example with the given key from the properties file.
*
* @param propertyKey Key at which the name is stored in {@code monaco-examples.properties}
*/
private void loadExtenderName(final String propertyKey) {
try {
extenderName = propertyKey != null ? examples.getString(propertyKey) : "";
}
catch (final MissingResourceException e) {
extenderName = "Unknown extender";
}
}
/**
* Loads the given example for the extender showcase.
*
* @param key Key of the extender example.
*/
public void loadExtenderExample(final String key) {
loadCode(getExtenderExampleKey(key, "sample"));
loadCodeExtender(getExtenderExampleKey(key, "script"));
loadExtenderName(getExtenderExampleKey(key, "name"));
loadExtenderInfo(getExtenderExampleKey(key, "info"));
loadExtenderCss(getExtenderExampleKey(key, "css"));
loadExtenderLanguage(getExtenderExampleKey(key, "language"));
}
/**
* Demo submit to show that the data can be transferred to the server. Shows a message with the current code.
*/
public void submitContent() {
if (CODE.equals(mode)) {
final String content = INLINE.equals(type) ? value : valueFramed;
final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success",
"MonacoEditor content: " + abbreviate(content, "...", 300));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
else {
final MonacoDiffEditorModel value = INLINE.equals(type) ? valueDiff : valueFramedDiff;
final String left = abbreviate(value.getOriginalValue(), "...", 150);
final String right = abbreviate(value.getModifiedValue(), "...", 150);
final FacesMessage msg1 = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success",
"MonacoEditor content original: " + left);
final FacesMessage msg2 = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success",
"MonacoEditor content modified: " + right);
FacesContext.getCurrentInstance().addMessage(null, msg1);
FacesContext.getCurrentInstance().addMessage(null, msg2);
}
}
/**
* Set the initial values for the {@code basicUsage} showcase.
*
* @param mode Whether to use the code of diff editor.
*/
public void initBasicUsage(final String mode) {
this.mode = mode;
if (CODE.equals(mode)) {
editorOptions.setLanguage(ELanguage.TYPESCRIPT);
editorOptionsFramed.setLanguage(ELanguage.TYPESCRIPT);
}
else {
editorLangDiff = ELanguage.TYPESCRIPT;
editorLangFramedDiff = ELanguage.TYPESCRIPT;
}
loadDefaultCode();
loadDefaultCodeFramed();
}
/**
* Set the initial values for the {@code customTheme} showcase.
*
* @param mode Whether to use the code of diff editor.
*/
public void initCustomTheme(final String mode) {
this.mode = mode;
customThemes = singletonMap(MY_CUSTOM_THEME, MonacoEditorSettings.createDemoCustomTheme());
if (CODE.equals(mode)) {
editorOptions.setLanguage(ELanguage.HTML);
editorOptions.setTheme(MY_CUSTOM_THEME);
editorOptionsFramed.setLanguage(ELanguage.HTML);
editorOptionsFramed.setTheme(MY_CUSTOM_THEME);
}
else {
editorLangDiff = ELanguage.HTML;
editorOptionsDiff.setTheme(MY_CUSTOM_THEME);
editorLangFramedDiff = ELanguage.HTML;
editorOptionsFramedDiff.setTheme(MY_CUSTOM_THEME);
}
loadCode("custom_code.htmlCustomTheme");
loadCodeFramed("custom_code.htmlCustomTheme");
}
/**
* Set the initial values for the {@code customLocalization} showcase.
*
* @param mode Whether to use the code of diff editor.
*/
public void initCustomLocalization(final String mode) {
this.mode = mode;
if (CODE.equals(mode)) {
editorOptions.setLanguage(ELanguage.TYPESCRIPT);
editorOptionsFramed.setLanguage(ELanguage.TYPESCRIPT);
}
else {
editorLangDiff = ELanguage.TYPESCRIPT;
editorLangFramedDiff = ELanguage.TYPESCRIPT;
}
loadDefaultCode();
loadDefaultCodeFramed();
}
/**
* Set the initial values for the {@code events} showcase.
*
* @param mode Whether to use the code of diff editor.
*/
public void initEvents(final String mode) {
this.mode = mode;
if (CODE.equals(mode)) {
editorOptions.setLanguage(ELanguage.TYPESCRIPT);
editorOptionsFramed.setLanguage(ELanguage.TYPESCRIPT);
}
else {
editorLangDiff = ELanguage.TYPESCRIPT;
editorLangFramedDiff = ELanguage.TYPESCRIPT;
}
loadDefaultCode();
loadDefaultCodeFramed();
}
/**
* Set the initial values for the {@code extender} showcase.
*
* @param mode Whether to use the code of diff editor.
*/
public void initExtender(final String mode) {
this.mode = mode;
if (CODE.equals(mode)) {
editorOptions.setLanguage(ELanguage.JAVASCRIPT);
}
else {
editorLangExtenderDiff = ELanguage.JAVASCRIPT;
}
final String requested = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
.get("example");
if (CODE.equals(mode)) {
extenderExample = StringUtils.defaultIfBlank(requested, "jquery");
}
else {
extenderExample = StringUtils.defaultIfBlank(requested, "jquery");
}
loadExtenderExample(extenderExample);
}
/**
* @param exampleName Name of the example.
* @param subType Type of the data to get, e.g. {@code name} or {@code description}.
* @return The key for the given extender example property.
*/
private String getExtenderExampleKey(final String exampleName, final String subType) {
if (CODE.equals(mode)) {
return CUSTOM_CODE_EXTENDER_CODE + exampleName + "." + subType;
}
else {
return CUSTOM_CODE_EXTENDER_DIFF + exampleName + "." + subType;
}
}
}
function createExtender(a){return{beforeCreate:function(b,c,g){if(g){if(a.moreDeclarationUrls&&a.moreDeclarationNames){a.declarations=a.declarations||[];b=Array.isArray(a.moreDeclarationUrls)?a.moreDeclarationUrls:[a.moreDeclarationUrls];g=Array.isArray(a.moreDeclarationNames)?a.moreDeclarationNames:[a.moreDeclarationNames];for(var k=document.createElement("a"),f=0;f<b.length;f++)k.href=b[f],a.declarations.push([k.href,g[f]])}a.tsCheck&&"javascript"===a.language&&(monaco.typescript.javascriptDefaults.setCompilerOptions(Object.assign({},
monaco.typescript.javascriptDefaults.getCompilerOptions(),{checkJs:!0,strict:!0})),monaco.typescript.javascriptDefaults.setDiagnosticsOptions(Object.assign({},monaco.typescript.javascriptDefaults.getDiagnosticsOptions(),{noSemanticValidation:!1})));if(a.declarations)return b=a.declarations.map(function(d){var e=Array.isArray(d)?d[0]:d,l=Array.isArray(d)?d[1]:d;return fetch(e).then(function(h){return h.text()}).then(function(h){return{text:h,file:l}})}),b=Promise.all(b).then(function(d){return d.forEach(function(e){"javascript"===
a.language&&monaco.typescript.javascriptDefaults.addExtraLib(e.text,e.file);"typescript"===a.language&&monaco.typescript.typescriptDefaults.addExtraLib(e.text,e.file)})}),Promise.all([b]).then(function(){return c})}}}}
function createExtenderJQuery(a){return createExtender(Object.assing({},{declarations:"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/sizzle/index.d.ts https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/JQuery.d.ts https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/JQueryStatic.d.ts https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/misc.d.ts https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/legacy.d.ts https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jqueryui/index.d.ts".split(" ")},a))}
function createExtenderMonaco(a){return createExtender(Object.assign({},{declarations:[["https://unpkg.com/monaco-editor@latest/esm/vs/editor/editor.api.d.ts","file:///node_modules/@types/monaco-editor/index.d.ts"],["https://unpkg.com/primefaces@latest/PrimeFaces.d.ts","file:///node_modules/primefaces/PrimeFaces.d.ts"],["https://unpkg.com/primefaces@latest/PrimeFaces-module.d.ts","file:///node_modules/primefaces/PrimeFaces-module.d.ts"]]},a))}
function parseUrlParams(){var a=window.location.search;a="?"===a.charAt(0)?a.substring(1):a;return a.split("\x26").map(function(b){return b.split("\x3d").map(decodeURIComponent)}).reduce(function(b,c){c[0]in b?(Array.isArray(b[c[0]])||(b[c[0]]=[b[c[0]]]),b[c[0]].push(c[1])):b[c[0]]=c[1];return b},{})}
if(window.MonacoEnvironment){var params=parseUrlParams();switch(params.extender){case "jquery":window.MonacoEnvironment.Extender={codeEditor:createExtenderJQuery(params)};break;case "monaco":window.MonacoEnvironment.Extender={codeEditor:createExtenderMonaco(params)};break;case "default":window.MonacoEnvironment.Extender={codeEditor:createExtender(params)}}};
function monacoFollowScheme(){var a="true"===document.documentElement.getAttribute("data-dark"),b=this.cfg.editorOptions;"vs"===("string"===typeof b?JSON.parse(b):b).theme&&this.invokeMonaco("updateOptions",{theme:a?"vs-dark":"vs"})}(new MutationObserver(function(){Object.values(PrimeFaces.widgets).forEach(function(a){a instanceof PrimeFaces.widget.ExtMonacoBaseEditor&&a.isReady()&&monacoFollowScheme.call(a)})})).observe(document.documentElement,{attributes:!0,attributeFilter:["data-dark"]});
custom_code.extender.code.jquery.info = This example illustrates how you can add custom type declaration files to the editor. It loads the type declarations files for JQuery -- try hovering over the JQuery functions in the editor to the right or try typing some code to see the autocomplete feature in action.\n<br><br>\nTo do so, you should add the <strong>beforeCreate</strong> to your extender object. Use the third parameter <code>wasLibLoaded</code> to check whether the Monaco editor library was reloaded -- if not, there's no need to add declarations files again.\n<br><br>\nThen you can add the required type declaration files via <strong>monaco.typescript.javascriptDefaults.addExtraLib</strong> (if you are editing a JavaScript file) or <strong>monaco.typescript.typescriptDefaults.addExtraLib</strong> (if you are editing a TypeScript file). See the <a href="https://microsoft.github.io/monaco-editor/api/interfaces/monaco.typescript.LanguageServiceDefaults.html#addExtraLib" target="_blank">Monaco editor API DOC for more info on that function</a>.\n<br><br>\nFinally, you may wonder from where you should load the declaration files. You could add the declaration inline into the extender script, which may be a viable option for small declaration files. For larger files, it is recommended you load the declaration file from a network resource. Note that the <code>beforeCreate</code> hook of the extender may return a Promise. If it does, the Monaco editor widget will wait until that Promise resolves and only create the editor once it does.\n<br><br>\nSee also <a href="https://github.com/DefinitelyTyped/DefinitelyTyped" target="_blank">https://github.com/DefinitelyTyped/DefinitelyTyped</a>, the repository for high quality TypeScript type definitions for many popular JavaScript libraries.
custom_code.extender.code.jquery.language = typescript
custom_code.extender.code.jquery.name = Additional type declarations (JQuery)
custom_code.extender.code.jquery.sample = // IntelliSense provides you with warnings for deprecated API method\n// Try hovering over "ready" to see more details\n$(document).ready(function () {\n $("p")\n // try adding a new line and type a period (.) to trigger autocompletion\n // press Ctrl + Space to see more details on the available suggestions\n .append(" <a href=\\"#\\">read more...</a>");\n\n // This is deprecated as well , try replacing it with \n // .on("change", ...) \n $("button").click(function (event) {\n $("#container").append("This is demo text.");\n // Uncomment the following line by pressing Ctrl + /\n // Then move to the end oft the period and press\n // Ctrl + Space to trigger autocomplete\n // event.\n });\n});
custom_code.extender.code.jquery.script = // FOR BREVITY WE ARE USING MODERN JAVASCRIPT AND API FEATURES\n// IF YOU NEED TO SUPPORT OLDER BROWSERS, ADJUST THIS SCRIPT ACCORDINGLY\n// IN PARTICULAR, CHECK IF YOUR TARGET BROWSERS SUPPORT ASYNC FUNCTIONS,\n// PROMISES, AND THE FETCH API\n\n/**\n * Load JQuery / JQuery UI declarations form GitHub and add them to\n * the editor.\n * @return {PrimeFaces.widget.ExtMonacoEditor.ExtenderCodeEditorInline}\n */\nfunction createExtender() {\n const declarations = [\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/sizzle/index.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/JQuery.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/JQueryStatic.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/misc.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/legacy.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jqueryui/index.d.ts"\n ];\n return {\n async beforeCreate(context, options, wasLibLoaded) {\n const items = await Promise.all(declarations.map(async file => {\n const response = await fetch(file);\n const text = await response.text();\n return {file, text};\n }));\n for (const {file, text} of items) {\n // Only add libs that don't exist yet.\n const extraLibs = monaco.typescript.typescriptDefaults\n .getExtraLibs();\n if (!(file in extraLibs)) {\n monaco.typescript.typescriptDefaults\n .addExtraLib(text, file);\n }\n }\n return options;\n }\n };\n}
custom_code.extender.code.jsonschema.info = This example illustrates how you can use a custom JSON schema for editing JSON files with validation and autocomplete. We set the JSON schema via the <strong><code>$schema</code></strong> property in the JSON file, which points to a URL with the JSON schema content. Now we need to allow Monaco editor to access network resources for JSON schemas. We do so by setting the <strong><code>enableSchemaRequest</code></strong> to <code>true</code> via <strong><code>monaco.json.jsonDefaults.setDiagnosticsOptions</code></strong>.\n<br><br>\nPlease note that this requires the browser to support the fetch API. If you need to support older browsers, you can add a polyfill for <code>window.fetch</code>.\n<br><br>\nAlso, if you do not wish to, or cannot, set the <code>$schema</code> property in the JSON file, it is also possible to define an implicit JSON schema that should be applied to a certain JSON file. You can do so with the <code>schema</code> setting that can be set via <code>monaco.json.jsonDefaults.setDiagnosticsOptions</code>. Here you need to specifiy the URI of the JSON file to which the schema should apply. By default, the Monaco editor widget generates the URI automatically based on the the component's client ID and the file type. For example, when the Monaco editor widget has the client <code>monacoEditor</code>, the default URI for JSON files is <code>inmemory:monacoEditor/file.json</code>. When the <code>widgetVar</code> of the component is <code>monacoEditor</code>, you can also check out the URI via the following code:\n<pre>\nPrimeFaces.widgets.monacoEditor.getMonaco().getModel().uri\n</pre>\nFinally, you can also change the URI either via the extender or by specifying the options <code>scheme</code>, <code>directory</code>, <code>basename</code>, and <code>extension</code> on the Monaco editor widget, see also the options panel to the right.
custom_code.extender.code.jsonschema.language = json
custom_code.extender.code.jsonschema.name = JSON Schema
custom_code.extender.code.jsonschema.sample = {\n "$schema": "https://raw.githubusercontent.com/SchemaStore/schemastore/master/src/schemas/json/tsconfig.json",\n "compilerOptions": {\n "module": false,\n "noImplicitAny": true,\n "removeComments": true,\n "preserveConstEnums": true,\n "sourceMap": true\n },\n "files": [\n "core.ts",\n "sys.ts",\n "types.ts",\n "scanner.ts",\n "parser.ts",\n "utilities.ts",\n "binder.ts",\n "checker.ts",\n "emitter.ts",\n "program.ts",\n "commandLineParser.ts",\n "tsc.ts",\n "diagnosticInformationMap.generated.ts"\n ]\n}
custom_code.extender.code.jsonschema.script = // FOR BREVITY WE ARE USING MODERN JAVASCRIPT AND API FEATURES\n// IF YOU NEED TO SUPPORT OLDER BROWSERS, ADJUST THIS SCRIPT ACCORDINGLY\n// IN PARTICULAR, CHECK IF YOUR TARGET BROWSERS SUPPORT ASYNC FUNCTIONS,\n// PROMISES, AND THE FETCH API\n\n/**\n * Enable schema requests via the fetch API. Also enables validation.\n * @return {PrimeFaces.widget.ExtMonacoEditor.ExtenderCodeEditorInline}\n */\nfunction createExtender() {\n return {\n async beforeCreate(context, options, wasLibLoaded) {\n if (wasLibLoaded) {\n monaco.json.jsonDefaults.setDiagnosticsOptions({\n ...monaco.json.jsonDefaults.diagnosticsOptions,\n enableSchemaRequest: true,\n schemaValidation: "error",\n validate: true\n });\n }\n return options;\n }\n };\n}
custom_code.extender.code.localstorage.info = This example illustrates how you can use the <strong><code>createEditorOverrideServices</code></strong> hook of the extender. It lets you add custom editor services to the editor. See this <a href="https://github.com/Microsoft/monaco-editor/issues/935#issuecomment-402174095" target="_blank">here on GitHub</a> for the available editor overrides.\n<br><br>\nThis particular example adds an implementation of the <code>storageService</code> that uses the Local Storage API of the browser. By also setting the option <code>suggestSelection</code> to <code>recentlyUsed</code> in the <code>beforeCreate</code> hook, Monaco editor will remember which suggestions the user has used recently and favor these suggestions in subsequent autocomplete queries. Also. edit the code and accept an autocomplete suggestion, then try opening the dev tools and check out the local storage to see what the editor stores there.
custom_code.extender.code.localstorage.language = typescript
custom_code.extender.code.localstorage.name = Editor overrides (Storage Service)
custom_code.extender.code.localstorage.sample = // Function to change the content of t2\nfunction modifyText() {\n const t2 = document.getElementById("t2");\n if (t2.firstChild.nodeValue == "three") {\n t2.firstChild.nodeValue = "two";\n } else {\n t2.firstChild.nodeValue = "three";\n }\n}\n\n// Add event listener to table\nconst el = document.getElementById("outside");\nel.addEventListener("click", modifyText, false);\n
custom_code.extender.code.localstorage.script = /**\n * Simple extender that adjusts the editor options.\n * @return {PrimeFaces.widget.ExtMonacoEditor.ExtenderCodeEditorInline}\n */\nfunction createExtender() {\n /** @enum {number} */\n const StorageScope = {\n GLOBAL: 0,\n WORKSPACE: 1\n };\n /** @enum {number} */\n const StorageTarget = {\n USER: 0,\n MACHINE: 1\n };\n return {\n beforeCreate(context, options, wasLibLoaded) {\n options.suggestSelection = "recentlyUsed";\n return options;\n },\n createEditorOverrideServices(context, options) {\n return {\n storageService: {\n _serviceBrand: undefined,\n onDidChangeValue() {},\n onDidChangeTarget() {},\n onWillSaveState() {},\n\n /**\n * Store a string value under the given key to local storage.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {any} value\n * @param {StorageScope} [scope]\n */\n store(key, value, scope) {\n if (window.localStorage) {\n localStorage.setItem(key, value);\n }\n },\n\n /**\n * Delete an element stored under the provided key from local storage.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {StorageScope} [scope]\n */\n remove(key, scope) {\n if (window.localStorage) {\n localStorage.removeItem(key);\n }\n },\n\n /**\n * Retrieve an element stored with the given key from local storage. Use\n * the provided defaultValue if the element is null or undefined.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {StorageScope} [scope]\n * @param {string} [defaultValue]\n * @return {string}\n */\n get(key, scope, defaultValue) {\n if (window.localStorage) {\n const value = localStorage.getItem(key);\n return value !== null && value !== undefined\n ? value\n : defaultValue ?? "";\n }\n return "";\n },\n\n /**\n * Retrieve an element stored with the given key from local storage. Use\n * the provided defaultValue if the element is null or undefined. The element\n * will be converted to a number using parseInt with a base of 10.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {StorageScope} [scope]\n * @param {number} [defaultValue]\n * @return {number}\n */\n getInteger(key, scope, defaultValue) {\n if (window.localStorage) {\n const value = localStorage.getItem(key);\n return value !== null && value !== undefined\n ? parseInt(value, 10)\n : defaultValue ?? 0;\n }\n return 0;\n },\n\n /**\n * Retrieve an element stored with the given key from local storage. Use\n * the provided defaultValue if the element is null or undefined. The element\n * will be converted to a boolean.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {StorageScope} [scope]\n * @param {boolean} [defaultValue]\n * @return {boolean}\n */\n getBoolean(key, scope, defaultValue) {\n if (window.localStorage) {\n const value = localStorage.getItem(key);\n return value !== null && value !== undefined\n ? value === "true" || value === "1" || value === "on"\n : defaultValue ?? false;\n }\n return false;\n },\n\n /**\n * Returns all the keys used in the storage for the provided `scope`\n * and `target`.\n *\n * Note: this will NOT return all keys stored in the storage layer.\n * Some keys may not have an associated `StorageTarget` and thus\n * will be excluded from the results.\n *\n * @param {StorageScope} scope allows to define the scope for the keys\n * to either the current workspace only or all workspaces.\n *\n * @param {StorageTarget} target allows to define the target for the keys\n * to either the current machine or user.\n * \n * @return {string[]}\n */\n keys(scope, target) {\n /** @type {string[]} */\n const keys = [];\n if (window.localStorage) {\n for (let i = 0; i < localStorage.length; ++i) {\n keys.push(localStorage.key(i) ?? "");\n }\n }\n return keys;\n },\n\n /**\n * Log the contents of the storage to the console.\n */\n logStorage() { },\n\n /**\n * Whether the storage for the given scope was created during this session or\n * existed before.\n * @param {StorageScope} scope\n * @return {boolean}\n */\n isNew(scope) {\n return false;\n },\n\n /**\n * Allows to flush state, e.g. in cases where a shutdown is\n * imminent. This will send out the `onWillSaveState` to ask\n * everyone for latest state.\n *\n * @return {Promise<void>} A `Promise` that can be awaited on when all updates\n * to the underlying storage have been flushed.\n */\n flush() {\n return Promise.resolve(undefined);\n },\n\n /**\n * Migrate the storage contents to another workspace.\n * @param {unknown} toWorkspace\n * @return {Promise<void>}\n */\n migrate(toWorkspace) {\n // not implemented\n console.warn("Migrating workspaces is not implemented");\n return Promise.resolve(undefined);\n }\n }\n };\n },\n };\n}
custom_code.extender.code.options.info = This examples illustrates how you can adjust the editor options via JavaScript. While many options can be set on the Monaco editor widget via Java, there are a few options that cannot (either because it is a new option that has not yet been added to the Java API, or when the option is callback function). Sometimes it may also be neccessary to adjust the options depending on some data only available on the client. \n<br><br>\nSee also <a href="https://microsoft.github.io/monaco-editor/docs.html#interfaces/editor.IStandaloneEditorConstructionOptions.html" target="_blank">the Monaco editor API DOC</a> for a list of all options.
custom_code.extender.code.options.language = javascript
custom_code.extender.code.options.name = Adjust editor options
custom_code.extender.code.options.sample = // program to find Armstrong number between intervals\n\n// take an input\nconst lowNumber = parseInt(prompt('Enter a positive low integer value: '));\nconst highNumber = parseInt(prompt('Enter a positive high integer value: '));\n\nconsole.log ('Armstrong Numbers:');\n\n// looping through lowNumber to highNumber\nfor (let i = lowNumber; i <= highNumber; i++) {\n\n // converting number to string \n let numberOfDigits = i.toString().length;\n\n let sum = 0;\n\n // create a temporary variable\n let temp = i;\n\n /* loop through a number to find if \n a number is an Armstrong number */\n while (temp > 0) {\n\n let remainder = temp % 10;\n sum += remainder ** numberOfDigits;\n // removing last digit from the number\n temp = parseInt(temp / 10); // convert float into integer\n }\n \n if (sum == i) {\n console.log(i);\n }\n}\n
custom_code.extender.code.options.script = /**\n * Simple extender that adjusts the editor options.\n * @return {PrimeFaces.widget.ExtMonacoEditor.ExtenderCodeEditorInline}\n */\nfunction createExtender() {\n return {\n async beforeCreate(context, options, wasLibLoaded) {\n // Use hexadecimal line numbers\n options.lineNumbers = line => {\n return line.toString(16);\n };\n // Set some other options\n options.rulers = [\n { column: 60, color: "orange" },\n { column: 80, color: "red" },\n ];\n options.fontSize = 16;\n options.insertSpaces = true;\n options.tabSize = 4;\n return options;\n }\n };\n}
custom_code.extender.diff.jquery.info = This example illustrates how you can add custom type declaration files to the editor. It loads the type declarations files for JQuery -- try hovering over the JQuery functions in the editor to the right or try typing some code to see the autocomplete feature in action.\n<br><br>\nTo do so, you should add the <strong>beforeCreate</strong> to your extender object. Use the third parameter <code>wasLibLoaded</code> to check whether the Monaco editor library was reloaded -- if not, there's no need to add declarations files again.\n<br><br>\nThen you can add the required type declaration files via <strong>monaco.typescript.javascriptDefaults.addExtraLib</strong> (if you are editing a JavaScript file) or <strong>monaco.typescript.typescriptDefaults.addExtraLib</strong> (if you are editing a TypeScript file). See the <a href="https://microsoft.github.io/monaco-editor/api/interfaces/monaco.typescript.LanguageServiceDefaults.html#addExtraLib" target="_blank">Monaco editor API DOC for more info on that function</a>.\n<br><br>\nFinally, you may wonder from where you should load the declaration files. You could add the declaration inline into the extender script, which may be a viable option for small declaration files. For larger files, it is recommended you load the declaration file from a network resource. Note that the <code>beforeCreate</code> hook of the extender may return a Promise. If it does, the Monaco editor widget will wait until that Promise resolves and only create the editor once it does.\n<br><br>\nSee also <a href="https://github.com/DefinitelyTyped/DefinitelyTyped" target="_blank">https://github.com/DefinitelyTyped/DefinitelyTyped</a>, the repository for high quality TypeScript type definitions for many popular JavaScript libraries.
custom_code.extender.diff.jquery.language = typescript
custom_code.extender.diff.jquery.name = Additional type declarations (JQuery)
custom_code.extender.diff.jquery.sample = // IntelliSense provides you with warnings for deprecated API method\n// Try hovering over "ready" to see more details\n$(document).ready(function () {\n $("p")\n // try adding a new line and type a period (.) to trigger autocompletion\n // press Ctrl + Space to see more details on the available suggestions\n .append(" <a href=\\"#\\">read more...</a>");\n\n // This is deprecated as well , try replacing it with \n // .on("change", ...) \n $("button").click(function (event) {\n $("#container").append("This is demo text.");\n // Uncomment the following line by pressing Ctrl + /\n // Then move to the end oft the period and press\n // Ctrl + Space to trigger autocomplete\n // event.\n });\n});
custom_code.extender.diff.jquery.script = // FOR BREVITY WE ARE USING MODERN JAVASCRIPT AND API FEATURES\n// IF YOU NEED TO SUPPORT OLDER BROWSERS, ADJUST THIS SCRIPT ACCORDINGLY\n// IN PARTICULAR, CHECK IF YOUR TARGET BROWSERS SUPPORT ASYNC FUNCTIONS,\n// PROMISES, AND THE FETCH API\n\n/**\n * Load JQuery / JQuery UI declarations form GitHub and add them to\n * the editor.\n * @return {PrimeFaces.widget.ExtMonacoEditor.ExtenderDiffEditorInline}\n */\nfunction createExtender() {\n const declarations = [\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/sizzle/index.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/JQuery.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/JQueryStatic.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/misc.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/legacy.d.ts",\n "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jqueryui/index.d.ts"\n ];\n return {\n async beforeCreate(context, options, wasLibLoaded) {\n const items = await Promise.all(declarations.map(async file => {\n const response = await fetch(file);\n const text = await response.text();\n return {file, text};\n }));\n for (const {file, text} of items) {\n // Only add libs that don't exist yet.\n const extraLibs = monaco.typescript.typescriptDefaults\n .getExtraLibs();\n if (!(file in extraLibs)) {\n monaco.typescript.typescriptDefaults\n .addExtraLib(text, file);\n }\n }\n return options;\n }\n };\n}
custom_code.extender.diff.jsonschema.info = This example illustrates how you can use a custom JSON schema for editing JSON files with validation and autocomplete. We set the JSON schema via the <strong><code>$schema</code></strong> property in the JSON file, which points to a URL with the JSON schema content. Now we need to allow Monaco editor to access network resources for JSON schemas. We do so by setting the <strong><code>enableSchemaRequest</code></strong> to <code>true</code> via <strong><code>monaco.json.jsonDefaults.setDiagnosticsOptions</code></strong>.\n<br><br>\nPlease note that this requires the browser to support the fetch API. If you need to support older browsers, you can add a polyfill for <code>window.fetch</code>.\n<br><br>\nAlso, if you do not wish to, or cannot, set the <code>$schema</code> property in the JSON file, it is also possible to define an implicit JSON schema that should be applied to a certain JSON file. You can do so with the <code>schema</code> setting that can be set via <code>monaco.json.jsonDefaults.setDiagnosticsOptions</code>. Here you need to specifiy the URI of the JSON file to which the schema should apply. By default, the Monaco editor widget generates the URI automatically based on the the component's client ID and the file type. For example, when the Monaco editor widget has the client <code>monacoEditor</code>, the default URI for JSON files is <code>inmemory:monacoEditor/file.json</code>. When the <code>widgetVar</code> of the component is <code>monacoEditor</code>, you can also check out the URI via the following code:\n<pre>\nPrimeFaces.widgets.monacoEditor.getMonaco().getModel().uri\n</pre>\nFinally, you can also change the URI either via the extender or by specifying the options <code>scheme</code>, <code>directory</code>, <code>basename</code>, and <code>extension</code> on the Monaco editor widget, see also the options panel to the right.
custom_code.extender.diff.jsonschema.language = json
custom_code.extender.diff.jsonschema.name = JSON Schema
custom_code.extender.diff.jsonschema.sample = {\n "$schema": "https://raw.githubusercontent.com/SchemaStore/schemastore/master/src/schemas/json/tsconfig.json",\n "compilerOptions": {\n "module": false,\n "noImplicitAny": true,\n "removeComments": true,\n "preserveConstEnums": true,\n "sourceMap": true\n },\n "files": [\n "core.ts",\n "sys.ts",\n "types.ts",\n "scanner.ts",\n "parser.ts",\n "utilities.ts",\n "binder.ts",\n "checker.ts",\n "emitter.ts",\n "program.ts",\n "commandLineParser.ts",\n "tsc.ts",\n "diagnosticInformationMap.generated.ts"\n ]\n}
custom_code.extender.diff.jsonschema.script = // FOR BREVITY WE ARE USING MODERN JAVASCRIPT AND API FEATURES\n// IF YOU NEED TO SUPPORT OLDER BROWSERS, ADJUST THIS SCRIPT ACCORDINGLY\n// IN PARTICULAR, CHECK IF YOUR TARGET BROWSERS SUPPORT ASYNC FUNCTIONS,\n// PROMISES, AND THE FETCH API\n\n/**\n * Enable schema requests via the fetch API. Also enables validation.\n * @return {PrimeFaces.widget.ExtMonacoEditor.ExtenderDiffEditorInline}\n */\nfunction createExtender() {\n return {\n async beforeCreate(context, options, wasLibLoaded) {\n if (wasLibLoaded) {\n monaco.json.jsonDefaults.setDiagnosticsOptions({\n ...monaco.json.jsonDefaults.diagnosticsOptions,\n enableSchemaRequest: true,\n schemaValidation: "error",\n validate: true\n });\n }\n return options;\n }\n };\n}
custom_code.extender.diff.localstorage.info = This example illustrates how you can use the <strong><code>createEditorOverrideServices</code></strong> hook of the extender. It lets you add custom editor services to the editor. See this <a href="https://github.com/Microsoft/monaco-editor/issues/935#issuecomment-402174095" target="_blank">here on GitHub</a> for the available editor overrides.\n<br><br>\nThis particular example adds an implementation of the <code>storageService</code> that uses the Local Storage API of the browser. By also setting the option <code>suggestSelection</code> to <code>recentlyUsed</code> in the <code>beforeCreate</code> hook, Monaco editor will remember which suggestions the user has used recently and favor these suggestions in subsequent autocomplete queries. Also. edit the code and accept an autocomplete suggestion, then try opening the dev tools and check out the local storage to see what the editor stores there.
custom_code.extender.diff.localstorage.language = typescript
custom_code.extender.diff.localstorage.name = Editor overrides (Storage Service)
custom_code.extender.diff.localstorage.sample = // Function to change the content of t2\nfunction modifyText() {\n const t2 = document.getElementById("t2");\n if (t2.firstChild.nodeValue == "three") {\n t2.firstChild.nodeValue = "two";\n } else {\n t2.firstChild.nodeValue = "three";\n }\n}\n\n// Add event listener to table\nconst el = document.getElementById("outside");\nel.addEventListener("click", modifyText, false);\n
custom_code.extender.diff.localstorage.script = /**\n * Simple extender that adjusts the editor options.\n * @return {PrimeFaces.widget.ExtMonacoEditor.ExtenderDiffEditorInline}\n */\nfunction createExtender() {\n /** @enum {number} */\n const StorageScope = {\n GLOBAL: 0,\n WORKSPACE: 1\n };\n /** @enum {number} */\n const StorageTarget = {\n USER: 0,\n MACHINE: 1\n };\n return {\n beforeCreate(context, options, wasLibLoaded) {\n options.suggestSelection = "recentlyUsed";\n return options;\n },\n createEditorOverrideServices(context, options) {\n return {\n storageService: {\n _serviceBrand: undefined,\n onDidChangeValue() {},\n onDidChangeTarget() {},\n onWillSaveState() {},\n\n /**\n * Store a string value under the given key to local storage.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {any} value\n * @param {StorageScope} [scope]\n */\n store(key, value, scope) {\n if (window.localStorage) {\n localStorage.setItem(key, value);\n }\n },\n\n /**\n * Delete an element stored under the provided key from local storage.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {StorageScope} [scope]\n */\n remove(key, scope) {\n if (window.localStorage) {\n localStorage.removeItem(key);\n }\n },\n\n /**\n * Retrieve an element stored with the given key from local storage. Use\n * the provided defaultValue if the element is null or undefined.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {StorageScope} [scope]\n * @param {string} [defaultValue]\n * @return {string}\n */\n get(key, scope, defaultValue) {\n if (window.localStorage) {\n const value = localStorage.getItem(key);\n return value !== null && value !== undefined\n ? value\n : defaultValue ?? "";\n }\n return "";\n },\n\n /**\n * Retrieve an element stored with the given key from local storage. Use\n * the provided defaultValue if the element is null or undefined. The element\n * will be converted to a number using parseInt with a base of 10.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {StorageScope} [scope]\n * @param {number} [defaultValue]\n * @return {number}\n */\n getInteger(key, scope, defaultValue) {\n if (window.localStorage) {\n const value = localStorage.getItem(key);\n return value !== null && value !== undefined\n ? parseInt(value, 10)\n : defaultValue ?? 0;\n }\n return 0;\n },\n\n /**\n * Retrieve an element stored with the given key from local storage. Use\n * the provided defaultValue if the element is null or undefined. The element\n * will be converted to a boolean.\n *\n * The optional scope argument allows to define the scope of the operation.\n * @param {string} key\n * @param {StorageScope} [scope]\n * @param {boolean} [defaultValue]\n * @return {boolean}\n */\n getBoolean(key, scope, defaultValue) {\n if (window.localStorage) {\n const value = localStorage.getItem(key);\n return value !== null && value !== undefined\n ? value === "true" || value === "1" || value === "on"\n : defaultValue ?? false;\n }\n return false;\n },\n\n /**\n * Returns all the keys used in the storage for the provided `scope`\n * and `target`.\n *\n * Note: this will NOT return all keys stored in the storage layer.\n * Some keys may not have an associated `StorageTarget` and thus\n * will be excluded from the results.\n *\n * @param {StorageScope} scope allows to define the scope for the keys\n * to either the current workspace only or all workspaces.\n *\n * @param {StorageTarget} target allows to define the target for the keys\n * to either the current machine or user.\n * \n * @return {string[]}\n */\n keys(scope, target) {\n /** @type {string[]} */\n const keys = [];\n if (window.localStorage) {\n for (let i = 0; i < localStorage.length; ++i) {\n keys.push(localStorage.key(i) ?? "");\n }\n }\n return keys;\n },\n\n /**\n * Log the contents of the storage to the console.\n */\n logStorage() { },\n\n /**\n * Whether the storage for the given scope was created during this session or\n * existed before.\n * @param {StorageScope} scope\n * @return {boolean}\n */\n isNew(scope) {\n return false;\n },\n\n /**\n * Allows to flush state, e.g. in cases where a shutdown is\n * imminent. This will send out the `onWillSaveState` to ask\n * everyone for latest state.\n *\n * @return {Promise<void>} A `Promise` that can be awaited on when all updates\n * to the underlying storage have been flushed.\n */\n flush() {\n return Promise.resolve(undefined);\n },\n\n /**\n * Migrate the storage contents to another workspace.\n * @param {unknown} toWorkspace\n * @return {Promise<void>}\n */\n migrate(toWorkspace) {\n // not implemented\n console.warn("Migrating workspaces is not implemented");\n return Promise.resolve(undefined);\n }\n }\n };\n },\n };\n}
custom_code.extender.diff.options.info = This examples illustrates how you can adjust the editor options via JavaScript. While many options can be set on the Monaco editor widget via Java, there are a few options that cannot (either because it is a new option that has not yet been added to the Java API, or when the option is callback function). Sometimes it may also be neccessary to adjust the options depending on some data only available on the client. \n<br><br>\nSee also <a href="https://microsoft.github.io/monaco-editor/docs.html#interfaces/editor.IStandaloneDiffEditorConstructionOptions.html" target="_blank">the Monaco editor API DOC</a> for a list of all options.
custom_code.extender.diff.options.language = javascript
custom_code.extender.diff.options.name = Adjust editor options
custom_code.extender.diff.options.sample = // program to find Armstrong number between intervals\n\n// take an input\nconst lowNumber = parseInt(prompt('Enter a positive low integer value: '));\nconst highNumber = parseInt(prompt('Enter a positive high integer value: '));\n\nconsole.log ('Armstrong Numbers:');\n\n// looping through lowNumber to highNumber\nfor (let i = lowNumber; i <= highNumber; i++) {\n\n // converting number to string \n let numberOfDigits = i.toString().length;\n\n let sum = 0;\n\n // create a temporary variable\n let temp = i;\n\n /* loop through a number to find if \n a number is an Armstrong number */\n while (temp > 0) {\n\n let remainder = temp % 10;\n sum += remainder ** numberOfDigits;\n // removing last digit from the number\n temp = parseInt(temp / 10); // convert float into integer\n }\n \n if (sum == i) {\n console.log(i);\n }\n}\n
custom_code.extender.diff.options.script = /**\n * Simple extender that adjusts the editor options.\n * @return {PrimeFaces.widget.ExtMonacoEditor.ExtenderDiffEditorInline}\n */\nfunction createExtender() {\n return {\n async beforeCreate(context, options, wasLibLoaded) {\n // Use hexadecimal line numbers\n options.lineNumbers = line => {\n return line.toString(16);\n };\n // Set some other options\n options.rulers = [\n { column: 60, color: "orange" },\n { column: 80, color: "red" },\n ];\n options.fontSize = 22;\n options.lineHeight = 40;\n options.renderIndicators = false;\n return options;\n }\n };\n}
custom_code.htmlCustomTheme = <html><!-- // !!! Tokens can be inspected using F1 > Developer: Inspect Tokens !!! -->\n<head>\n\u0009<!-- HTML comment -->\n\u0009<style type="text/css">\n\u0009\u0009/* CSS comment */\n\u0009</style>\n\u0009<script type="javascript">\n\u0009\u0009// JavaScript comment\n\u0009</script>\n</head>\n<body></body>\n</html>
sample_code.abap = REPORT zrosetta_base64_encode_data.\n\nDATA: li_client TYPE REF TO if_http_client,\n lv_encoded TYPE string,\n lv_data TYPE xstring.\n\n\ncl_http_client=>create_by_url(\n EXPORTING\n url = 'http://rosettacode.org/favicon.ico'\n IMPORTING\n client = li_client ).\n\nli_client->send( ).\nli_client->receive( ).\n\nlv_data = li_client->response->get_data( ).\n\nCALL FUNCTION 'SSFC_BASE64_ENCODE'\n EXPORTING\n bindata = lv_data\n IMPORTING\n b64data = lv_encoded.\n\nWHILE strlen( lv_encoded ) > 100.\n WRITE: / lv_encoded(100).\n lv_encoded = lv_encoded+100.\nENDWHILE.\nWRITE: / lv_encoded.\n
sample_code.aes = // Contract simulating developers organization\ncontract HackBG =\n\n record state = { developers: map(address, developer) }\n\n record developer = { name: string\n , age: int\n , skillset: map(skill, experience) }\n\n type skill = string\n type experience = int\n\n datatype event =\n LogDeveloperAdded(indexed address, indexed int, string)\n\n entrypoint init() : state = { developers = {} }\n\n stateful entrypoint dev_add(account: address, dev_name: string, dev_age: int) =\n require(!is_member(account), "ERROR_DEVELOPER_ALREADY_EXISTS")\n let dev : developer = { name = dev_name\n , age = dev_age\n , skillset = {} }\n put(state{ developers[account] = dev })\n Chain.event(LogDeveloperAdded(account, Chain.timestamp, dev_name))\n\n stateful entrypoint dev_update(account: address, dev_name: string, dev_age: int) =\n require(is_member(account), "ERROR_DEVELOPER_DOES_NOT_EXIST")\n put(state{ developers[account].name = dev_name })\n put(state{ developers[account].age = dev_age })\n\n function is_member(account: address) : bool =\n Map.member(account, state.developers)\n\n stateful entrypoint dev_skill_modify(account: address, skill: string, experience: int) =\n put(state{ developers[account].skillset[skill] = experience })\n\n entrypoint dev_get(account: address) : developer =\n state.developers[account]
sample_code.apex = /* Using a single database query, find all the leads in\n the database that have the same email address as any\n of the leads being inserted or updated. */\nfor (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) {\n Lead newLead = leadMap.get(lead.Email);\n newLead.Email.addError('A lead with this email address already exists.');\n}\n
sample_code.azcli = # Create a resource group.\naz group create --name myResourceGroup --location westeurope\n\n# Create a new virtual machine, this creates SSH keys if not present.\naz vm create --resource-group myResourceGroup --name myVM --image UbuntuLTS --generate-ssh-keys
sample_code.bat = rem *******Begin Comment**************\nrem This program starts the superapp batch program on the network,\nrem directs the output to a file, and displays the file\nrem in Notepad.\nrem *******End Comment**************\n@echo off\nif exist C:\\output.txt goto EMPTYEXISTS\nsetlocal\n\u0009path=g:\\programs\\superapp;%path%\n\u0009call superapp>C:\\output.txt\nendlocal\n:EMPTYEXISTS\nstart notepad c:\\output.txt
sample_code.bicep = targetScope = 'subscription'\n\nparam deployStorage bool = true\n\n@description('The object ID of the principal that will get the role assignment')\nparam aadPrincipalId string\n\nmodule stg './storage.bicep' = if(deployStorage) {\n name: 'storageDeploy'\n scope: resourceGroup('another-rg') // this will target another resource group in the same subscription\n params: {\n storageAccountName: '<YOURUNIQUESTORAGENAME>'\n }\n}\n\nvar contributor = 'b24988ac-6180-42a0-ab88-20f7382dd24c'\nresource roleDef 'Microsoft.Authorization/roleDefinitions@2018-01-01-preview' existing = {\n name: contributor\n}\n\nresource rbac 'Microsoft.Authorization/roleAssignments@2020-04-01-preview' = {\n name: guid(subscription().id, aadPrincipalId, contributor)\n properties: {\n roleDefinitionId: roleDef.id\n principalId: aadPrincipalId\n }\n}\n\noutput storageName array = stg.outputs.containerProps\n
sample_code.c = // Copyright (c) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full\n// license information.\n\n/*\n *\u0009COMMAND LINE: -Ox -Gz -YX -UPROTOTYPES_REQUIRED\n */\n\n#pragma warning(disable : 4532)\n#pragma warning(disable : 4702)\n\n#if defined(_WIN32)\n\n#if defined(_M_SH)\n#define WIN_CE\n#endif\n\n#if defined(_M_AMD64)\n#define NEST_IN_FINALLY /* allow when __try nested in __finally OK */\n#endif\n\n#define NTSTATUS LONG\n#define EXCEPTION_NESTED_CALL 0x10\n#define RtlRaiseStatus(x) RaiseException((x), 0, 0, NULL)\n#define RtlRaiseException(x) \\\n RaiseException((x)->ExceptionCode, (x)->ExceptionFlags, \\\n (x)->NumberParameters, (x)->ExceptionInformation)\n#define IN\n#define OUT\n#if !(defined(_M_IA64) || defined(_M_ALPHA) || defined(_M_PPC) || \\\n defined(_M_AMD64) || defined(_M_ARM) || defined(_M_ARM64))\n#define i386 1\n#endif\n#define try __try\n#define except __except\n#define finally __finally\n#define leave __leave\n\n#endif\n\n#define WIN32_LEAN_AND_MEAN\n\n#include "stdio.h"\n#if defined(_M_IA64) || defined(_M_ALPHA) || defined(_M_PPC) || \\\n defined(_M_AMD64) || defined(_M_ARM) || defined(_M_ARM64)\n#include "setjmpex.h"\n#else\n#include "setjmp.h"\n#endif\n#include "float.h"\n#include "windows.h"\n#include "math.h"\n\n#if !defined(STATUS_SUCCESS)\n#define STATUS_SUCCESS 0\n#endif\n#if !defined(STATUS_UNSUCCESSFUL)\n#define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001L)\n#endif\n\n//\n// Define switch constants.\n//\n\n#define BLUE 0\n#define RED 1\n\n//\n// Define function prototypes.\n//\n\nVOID addtwo(IN LONG First, IN LONG Second, IN PLONG Place);\n\nVOID bar1(IN NTSTATUS Status, IN PLONG Counter);\n\nVOID bar2(IN PLONG BlackHole, IN PLONG BadAddress, IN PLONG Counter);\n\nVOID dojump(IN jmp_buf JumpBuffer, IN PLONG Counter);\n\nLONG Echo(IN LONG Value);\n\n#if !defined(WIN_CE) // return through finally not allowed on WinCE\nVOID eret(IN NTSTATUS Status, IN PLONG Counter);\n#endif\n\nVOID except1(IN PLONG Counter);\n\nULONG\nexcept2(IN PEXCEPTION_POINTERS ExceptionPointers, IN PLONG Counter);\n\nULONG\nexcept3(IN PEXCEPTION_POINTERS ExceptionPointers, IN PLONG Counter);\n\nVOID foo1(IN NTSTATUS Status);\n\nVOID foo2(IN PLONG BlackHole, IN PLONG BadAddress);\n\n#if !defined(WIN_CE) // return from finally not allowed on WinCE\nVOID fret(IN PLONG Counter);\n#endif\n\nBOOLEAN\nTkm(VOID);\n\nVOID Test61Part2(IN OUT PULONG Counter);\n\ndouble SquareDouble(IN double op);\n\nDECLSPEC_NOINLINE\nULONG\nPgFilter(VOID)\n\n{\n\n printf("filter entered...");\n return EXCEPTION_EXECUTE_HANDLER;\n}\n\n#pragma warning(push)\n#pragma warning(disable : 4532)\n\nVOID PgTest69(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 1) {\n *State += 1;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 1) == 1) ? PgFilter() : EXCEPTION_CONTINUE_SEARCH) {\n if (*State != 2) {\n *Fault += 1;\n }\n }\n\n return;\n}\n\nVOID PgTest70(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 2) {\n PgFilter();\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 2) == 2) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\nVOID PgTest71(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 3) {\n *State += 3;\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 6) {\n *State += 3;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 3) == 3) ? PgFilter() : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\nVOID PgTest72(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 4) {\n *State += 4;\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 8) {\n *State += 4;\n PgFilter();\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 4) == 4) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\nVOID PgTest73(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 5) {\n *State += 5;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 10) {\n *State += 5;\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 5) == 5) ? PgFilter() : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\nVOID PgTest74(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 6) {\n *State += 6;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 12) {\n *State += 6;\n PgFilter();\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 6) == 6) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\nVOID PgTest75(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 7) {\n *State += 7;\n *Fault += 1;\n\n } else {\n *State += 10;\n }\n }\n }\n }\n except(((*State += 7) == 7) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 28) {\n *State += 7;\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 7) == 28) ? PgFilter() : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\nVOID PgTest76(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 8) {\n *State += 8;\n *Fault += 1;\n\n } else {\n *State += 10;\n }\n }\n }\n }\n except(((*State += 8) == 8) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 32) {\n *State += 8;\n PgFilter();\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 8) == 32) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\nVOID PgTest77(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 9) {\n *State += 9;\n *Fault += 1;\n\n } else {\n *State += 10;\n }\n }\n }\n }\n except(((*State += 9) == 9) ? PgFilter() : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 36) {\n *State += 9;\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 9) == 36) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\nVOID PgTest78(IN PLONG State, IN PLONG Fault)\n\n{\n\n try {\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 10) {\n *State += 10;\n PgFilter();\n *Fault += 1;\n\n } else {\n *State += 10;\n }\n }\n }\n }\n except(((*State += 10) == 10) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n }\n finally {\n if (AbnormalTermination()) {\n if (*State == 40) {\n *State += 10;\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n except(((*State += 10) == 40) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n\n return;\n}\n\n#pragma warning(pop)\n\nVOID Test79(PLONG Counter, PLONG Fault)\n\n{\n\n try {\n try {\n try {\n *Fault += 1;\n }\n finally {\n printf("finally 1...");\n *Fault += 1;\n }\n }\n finally { printf("finally 2..."); }\n }\n except(*Counter += 1, printf("filter 1..."), EXCEPTION_CONTINUE_SEARCH) {}\n\n return;\n}\n\nULONG G;\n\nULONG\nTest80(VOID)\n\n{\n\n G = 1;\n try {\n while (G) {\n try {\n if (G == 10) {\n return 1;\n }\n\n if (G == 1) {\n continue;\n }\n }\n finally { G = 0; }\n }\n }\n finally { G = 10; }\n\n return 0;\n}\n\nvoid Test81(int *pCounter) {\n volatile char *AvPtr = NULL;\n\n __try {\n __try { *AvPtr = '\\0'; }\n __except(EXCEPTION_EXECUTE_HANDLER) { __leave; }\n }\n __finally {\n printf("in finally ");\n *pCounter += 1;\n }\n return;\n}\n\nDECLSPEC_NOINLINE\nVOID Test82Foo(VOID)\n\n{\n *(volatile int *)0 = 0;\n}\n\nVOID Test82(__inout PLONG Counter)\n\n{\n\n int retval = 1;\n\n __try {\n __try { Test82Foo(); }\n __finally {\n switch (*Counter) {\n case 0:\n printf("something failed!\\n");\n retval = 6;\n break;\n\n case 1:\n retval = 0;\n break;\n\n case 2:\n printf("how did you get here?\\n");\n retval = 2;\n break;\n\n case 3:\n printf("what?!?\\n");\n retval = 3;\n break;\n\n case 4:\n printf("not correct\\n");\n retval = 4;\n break;\n\n case 5:\n printf("error!\\n");\n retval = 5;\n break;\n }\n }\n }\n __except(1){}\n\n *Counter = retval;\n return;\n}\n\nLONG Test83(VOID)\n\n{\n\n G = 1;\n try {\n try {\n while (G) {\n try {\n if (G == 10) {\n return 1;\n }\n\n if (G == 1) {\n continue;\n }\n }\n finally { G = 0; }\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { leave; }\n }\n finally { G = 10; }\n\n return 0;\n}\n\nDECLSPEC_NOINLINE\nVOID Test84(_Inout_ PLONG Counter)\n\n{\n volatile int *Fault = 0;\n\n try {\n try {\n *Fault += 1;\n }\n except(EXCEPTION_EXECUTE_HANDLER) {\n try {\n return;\n }\n finally { *Counter += 1; }\n }\n }\n finally {\n\n if (AbnormalTermination()) {\n *Counter += 1;\n }\n }\n\n return;\n}\n\nDECLSPEC_NOINLINE\nLONG Test85(_Inout_ PLONG Counter)\n\n{\n volatile int *Fault = 0;\n\n G = 1;\n try {\n try {\n try {\n while (G) {\n try {\n try {\n if (G == 10) {\n return 1;\n }\n try {\n *Counter += 1;\n }\n except(EXCEPTION_EXECUTE_HANDLER) {}\n\n if (G == 1) {\n continue;\n }\n }\n finally {\n G = 0;\n *Counter += 1;\n *Fault += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) {\n *Counter += 1;\n leave;\n }\n }\n }\n finally {\n G = 10;\n *Counter += 1;\n *Fault += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { *Counter += 1; }\n *Counter += 1;\n }\n finally { *Counter += 1; }\n return 1;\n}\n\nDECLSPEC_NOINLINE\nVOID Test86(_Inout_ PLONG Counter)\n\n{\n volatile int *Fault = 0;\n\n try {\n try {\n try {\n try {\n try {\n try {\n *Fault += 1;\n }\n except(printf("Filter1 %d..", *Counter),\n EXCEPTION_EXECUTE_HANDLER) {\n try {\n printf("Handler1 %d..", *Counter);\n return;\n }\n finally {\n printf("Finally1 %d..", *Counter);\n *Counter += 1;\n }\n }\n }\n finally {\n printf("Finally2 %d..", *Counter);\n *Counter += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { leave; }\n }\n finally { *Counter += 1; }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { leave; }\n }\n finally { *Counter += 1; }\n\n return;\n}\n\nVOID Test87(_Inout_ PLONG Counter)\n\n/*++\n\nRoutine Description:\n\n This function verifies the behavior of nested exception dispatching.\n\nArguments:\n\n Counter - Supplies a pointer to the state counter.\n\nReturn Value:\n None.\n\n--*/\n\n{\n volatile int *Fault = 0;\n\n//\n// N.B. Disabled on x86 due to failing test case with handling of returns\n// in nested termination handlers on x86.\n//\n// Disabled on ARM due to failing test case with handling of abutting\n// termination handlers within an except handler.\n//\n// Disabled on AMD64 due to failing test case with handling of\n// abutting termination handlers within an except handler when a\n// non-local goto is involved.\n//\n\n#if !defined(_X86_)\n try {\n try {\n try {\n try {\n try {\n *Fault += 1;\n\n try {\n }\n finally {\n if (AbnormalTermination()) {\n *Fault += 1;\n }\n }\n }\n finally {\n\n if (AbnormalTermination()) {\n if ((*Counter += 13) == 26) {\n return;\n\n } else {\n *Fault += 1;\n }\n }\n }\n }\n finally {\n if (AbnormalTermination()) {\n *Counter += 13;\n *Fault += 1;\n }\n }\n }\n except(((*Counter += 13) == 13) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Fault += 1;\n }\n }\n except(((*Counter += 13) == 65) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n try {\n *Counter += 13;\n return;\n }\n finally {\n if (AbnormalTermination()) {\n *Counter += 13;\n goto Finish;\n }\n }\n }\n }\n finally {\n\n if (AbnormalTermination()) {\n if ((*Counter += 13) == 104) {\n goto Finish;\n }\n }\n }\n\nFinish:\n#else\n *Counter = 104;\n#endif\n\n return;\n}\n\nVOID Test88(_Inout_ PLONG Counter)\n\n{\n volatile int *Fault = 0;\n\n try {\n try {\n try {\n try {\n try {\n try {\n try {\n try {\n *Fault += 1;\n }\n except(((*Counter += 1) == 1) ? *Fault\n : EXCEPTION_CONTINUE_SEARCH) {}\n }\n except(*Counter += 1, EXCEPTION_EXECUTE_HANDLER) { *Fault += 2; }\n }\n except(*Counter += 1, EXCEPTION_CONTINUE_SEARCH) { leave; }\n }\n except(*Counter += 1, EXCEPTION_CONTINUE_SEARCH) { leave; }\n }\n except(EXCEPTION_EXECUTE_HANDLER) {}\n }\n except(EXCEPTION_EXECUTE_HANDLER) {}\n }\n except(EXCEPTION_EXECUTE_HANDLER) { leave; }\n }\n finally { *Counter += 1; }\n}\n\nint main(int argc, char *argv[])\n\n{\n\n PLONG BadAddress;\n PCHAR BadByte;\n PLONG BlackHole;\n ULONG Index1;\n ULONG Index2 = RED;\n jmp_buf JumpBuffer;\n LONG Counter;\n EXCEPTION_RECORD ExceptionRecord;\n double doubleresult;\n\n //\n // Announce start of exception test.\n //\n\n printf("Start of exception test\\n");\n\n //\n // Initialize exception record.\n //\n\n ExceptionRecord.ExceptionCode = STATUS_INTEGER_OVERFLOW;\n ExceptionRecord.ExceptionFlags = 0;\n ExceptionRecord.ExceptionRecord = NULL;\n ExceptionRecord.NumberParameters = 0;\n\n //\n // Initialize pointers.\n //\n\n BadAddress = (PLONG)NULL;\n BadByte = (PCHAR)NULL;\n BadByte += 1;\n BlackHole = &Counter;\n\n //\n // Simply try statement with a finally clause that is entered sequentially.\n //\n\n printf(" test1...");\n Counter = 0;\n try {\n Counter += 1;\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 1;\n }\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try statement with an exception clause that is never executed\n // because there is no exception raised in the try clause.\n //\n\n printf(" test2...");\n Counter = 0;\n try {\n Counter += 1;\n }\n except(Counter) { Counter += 1; }\n\n if (Counter != 1) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try statement with an exception handler that is never executed\n // because the exception expression continues execution.\n //\n\n printf(" test3...");\n Counter = 0;\n try {\n Counter -= 1;\n RtlRaiseException(&ExceptionRecord);\n }\n except(Counter) { Counter -= 1; }\n\n if (Counter != -1) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try statement with an exception clause that is always executed.\n //\n\n printf(" test4...");\n Counter = 0;\n try {\n Counter += 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n except(Counter) { Counter += 1; }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try statement with an exception clause that is always executed.\n //\n\n printf(" test5...");\n Counter = 0;\n try {\n Counter += 1;\n *BlackHole += *BadAddress;\n }\n except(Counter) { Counter += 1; }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simply try statement with a finally clause that is entered as the\n // result of an exception.\n //\n\n printf(" test6...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n RtlRaiseException(&ExceptionRecord);\n }\n finally {\n if (abnormal_termination() != FALSE) {\n Counter += 1;\n }\n }\n }\n except(Counter) {\n if (Counter == 2) {\n Counter += 1;\n }\n }\n\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simply try statement with a finally clause that is entered as the\n // result of an exception.\n //\n\n printf(" test7...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n *BlackHole += *BadAddress;\n }\n finally {\n if (abnormal_termination() != FALSE) {\n Counter += 1;\n }\n }\n }\n except(Counter) {\n if (Counter == 2) {\n Counter += 1;\n }\n }\n\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try that calls a function which raises an exception.\n //\n\n printf(" test8...");\n Counter = 0;\n try {\n Counter += 1;\n foo1(STATUS_ACCESS_VIOLATION);\n }\n except((GetExceptionCode() == STATUS_ACCESS_VIOLATION)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter += 1;\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try that calls a function which raises an exception.\n //\n\n printf(" test9...");\n Counter = 0;\n try {\n Counter += 1;\n foo2(BlackHole, BadAddress);\n }\n except((GetExceptionCode() == STATUS_ACCESS_VIOLATION)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter += 1;\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try that calls a function which calls a function that\n // raises an exception. The first function has a finally clause\n // that must be executed for this test to work.\n //\n\n printf(" test10...");\n Counter = 0;\n try {\n bar1(STATUS_ACCESS_VIOLATION, &Counter);\n }\n except((GetExceptionCode() == STATUS_ACCESS_VIOLATION)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter -= 1;\n }\n\n if (Counter != 98) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try that calls a function which calls a function that\n // raises an exception. The first function has a finally clause\n // that must be executed for this test to work.\n //\n\n printf(" test11...");\n Counter = 0;\n try {\n bar2(BlackHole, BadAddress, &Counter);\n }\n except((GetExceptionCode() == STATUS_ACCESS_VIOLATION)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter -= 1;\n }\n\n if (Counter != 98) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A try within an except\n //\n\n printf(" test12...");\n Counter = 0;\n try {\n foo1(STATUS_ACCESS_VIOLATION);\n }\n except((GetExceptionCode() == STATUS_ACCESS_VIOLATION)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter += 1;\n try {\n foo1(STATUS_SUCCESS);\n }\n except((GetExceptionCode() == STATUS_SUCCESS) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n if (Counter != 1) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded...");\n }\n\n Counter += 1;\n }\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A try within an except\n //\n\n printf(" test13...");\n Counter = 0;\n try {\n foo2(BlackHole, BadAddress);\n }\n except((GetExceptionCode() == STATUS_ACCESS_VIOLATION)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter += 1;\n try {\n foo1(STATUS_SUCCESS);\n }\n except((GetExceptionCode() == STATUS_SUCCESS) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n if (Counter != 1) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded...");\n }\n\n Counter += 1;\n }\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#if !defined(WIN_CE) // gotos from except/finally not allowed on WinCE\n //\n // A goto from an exception clause that needs to pass\n // through a finally\n //\n\n printf(" test14...");\n Counter = 0;\n try {\n try {\n foo1(STATUS_ACCESS_VIOLATION);\n }\n except((GetExceptionCode() == STATUS_ACCESS_VIOLATION)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter += 1;\n goto t9;\n }\n }\n finally { Counter += 1; }\n\nt9:\n ;\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A goto from an finally clause that needs to pass\n // through a finally\n //\n\n printf(" test15...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n }\n finally {\n Counter += 1;\n goto t10;\n }\n }\n finally { Counter += 1; }\n\nt10:\n ;\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A goto from an exception clause that needs to pass\n // through a finally into the outer finally clause.\n //\n\n printf(" test16...");\n Counter = 0;\n try {\n try {\n try {\n Counter += 1;\n foo1(STATUS_INTEGER_OVERFLOW);\n }\n except(EXCEPTION_EXECUTE_HANDLER) {\n Counter += 1;\n goto t11;\n }\n }\n finally { Counter += 1; }\n t11:\n ;\n }\n finally { Counter += 1; }\n\n if (Counter != 4) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A goto from an finally clause that needs to pass\n // through a finally into the outer finally clause.\n //\n\n printf(" test17...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n }\n finally {\n Counter += 1;\n goto t12;\n }\n t12:\n ;\n }\n finally { Counter += 1; }\n\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A return from an except clause\n //\n\n printf(" test18...");\n Counter = 0;\n try {\n Counter += 1;\n eret(STATUS_ACCESS_VIOLATION, &Counter);\n }\n finally { Counter += 1; }\n\n if (Counter != 4) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A return from a finally clause\n //\n\n printf(" test19...");\n Counter = 0;\n try {\n Counter += 1;\n fret(&Counter);\n }\n finally { Counter += 1; }\n\n if (Counter != 5) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif\n\n //\n // A simple set jump followed by a long jump.\n //\n\n printf(" test20...");\n Counter = 0;\n if (setjmp(JumpBuffer) == 0) {\n Counter += 1;\n longjmp(JumpBuffer, 1);\n\n } else {\n Counter += 1;\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A set jump followed by a long jump out of a finally clause that is\n // sequentially executed.\n //\n\n printf(" test21...");\n Counter = 0;\n if (setjmp(JumpBuffer) == 0) {\n try {\n Counter += 1;\n }\n finally {\n Counter += 1;\n longjmp(JumpBuffer, 1);\n }\n\n } else {\n Counter += 1;\n }\n\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A set jump within a try clause followed by a long jump out of a\n // finally clause that is sequentially executed.\n //\n\n printf(" test22...");\n Counter = 0;\n try {\n if (setjmp(JumpBuffer) == 0) {\n Counter += 1;\n\n } else {\n Counter += 1;\n }\n }\n finally {\n Counter += 1;\n if (Counter == 2) {\n Counter += 1;\n longjmp(JumpBuffer, 1);\n }\n }\n\n if (Counter != 5) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A set jump followed by a try/except, followed by a try/finally where\n // the try body of the try/finally raises an exception that is handled\n // by the try/excecpt which causes the try/finally to do a long jump out\n // of a finally clause. This will create a collided unwind.\n //\n\n printf(" test23...");\n Counter = 0;\n if (setjmp(JumpBuffer) == 0) {\n try {\n try {\n Counter += 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n finally {\n Counter += 1;\n longjmp(JumpBuffer, 1);\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 1; }\n\n } else {\n Counter += 1;\n }\n\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A set jump followed by a try/except, followed by a several nested\n // try/finally's where the inner try body of the try/finally raises an\n // exception that is handled by the try/except which causes the\n // try/finally to do a long jump out of a finally clause. This will\n // create a collided unwind.\n //\n\n printf(" test24...");\n Counter = 0;\n if (setjmp(JumpBuffer) == 0) {\n try {\n try {\n try {\n try {\n Counter += 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n finally { Counter += 1; }\n }\n finally {\n Counter += 1;\n longjmp(JumpBuffer, 1);\n }\n }\n finally { Counter += 1; }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 1; }\n\n } else {\n Counter += 1;\n }\n\n if (Counter != 5) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A set jump followed by a try/except, followed by a try/finally which\n // calls a subroutine which contains a try finally that raises an\n // exception that is handled to the try/except.\n //\n\n printf(" test25...");\n Counter = 0;\n if (setjmp(JumpBuffer) == 0) {\n try {\n try {\n try {\n Counter += 1;\n dojump(JumpBuffer, &Counter);\n }\n finally { Counter += 1; }\n }\n finally { Counter += 1; }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 1; }\n\n } else {\n Counter += 1;\n }\n\n if (Counter != 7) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A set jump followed by a try/except, followed by a try/finally which\n // calls a subroutine which contains a try finally that raises an\n // exception that is handled to the try/except.\n //\n\n printf(" test26...");\n Counter = 0;\n if (setjmp(JumpBuffer) == 0) {\n try {\n try {\n try {\n try {\n Counter += 1;\n dojump(JumpBuffer, &Counter);\n }\n finally { Counter += 1; }\n }\n finally {\n Counter += 1;\n longjmp(JumpBuffer, 1);\n }\n }\n finally { Counter += 1; }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 1; }\n\n } else {\n Counter += 1;\n }\n\n if (Counter != 8) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Test nested exceptions.\n //\n\n printf(" test27...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n except1(&Counter);\n }\n except(except2(GetExceptionInformation(), &Counter)) { Counter += 2; }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 3; }\n\n if (Counter != 55) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Simple try that causes an integer overflow exception.\n //\n\n printf(" test28...");\n Counter = 0;\n try {\n Counter += 1;\n addtwo(0x7fff0000, 0x10000, &Counter);\n }\n except((GetExceptionCode() == STATUS_INTEGER_OVERFLOW)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter += 1;\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n//\n// Simple try that raises an misaligned data exception.\n//\n#if !defined(i386) && !defined(_M_IA64) && !defined(_M_AMD64) && \\\n !defined(_M_ARM) && !defined(_M_ARM64)\n printf(" test29...");\n Counter = 0;\n try {\n Counter += 1;\n foo2(BlackHole, (PLONG)BadByte);\n }\n except((GetExceptionCode() == STATUS_DATATYPE_MISALIGNMENT)\n ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n Counter += 1;\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#endif\n //\n // Continue from a try body with an exception clause in a loop.\n //\n\n printf(" test30...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n if ((Index1 & 0x1) == 0) {\n continue;\n\n } else {\n Counter += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 40; }\n\n Counter += 2;\n }\n\n if (Counter != 15) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#if !defined(WIN_CE) // gotos from try/finally not allowed on WinCE\n //\n // Continue from a try body with an finally clause in a loop.\n //\n\n printf(" test31...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n if ((Index1 & 0x1) == 0) {\n continue;\n\n } else {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 3;\n }\n\n if (Counter != 40) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif\n\n //\n // Continue from doubly nested try body with an exception clause in a\n // loop.\n //\n\n printf(" test32...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n try {\n if ((Index1 & 0x1) == 0) {\n continue;\n\n } else {\n Counter += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 10; }\n\n Counter += 2;\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 20; }\n\n Counter += 3;\n }\n\n if (Counter != 30) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#if !defined(WIN_CE) // gotos from try/finally not allowed on WinCE\n //\n // Continue from doubly nested try body with an finally clause in a loop.\n //\n\n printf(" test33...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n try {\n if ((Index1 & 0x1) == 0) {\n continue;\n\n } else {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 3;\n }\n finally { Counter += 4; }\n\n Counter += 5;\n }\n\n if (Counter != 105) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Continue from a finally clause in a loop.\n //\n\n printf(" test34...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n if ((Index1 & 0x1) == 0) {\n Counter += 1;\n }\n }\n finally {\n Counter += 2;\n continue;\n }\n\n Counter += 4;\n }\n\n if (Counter != 25) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Continue from a doubly nested finally clause in a loop.\n //\n\n printf(" test35...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n try {\n if ((Index1 & 0x1) == 0) {\n Counter += 1;\n }\n }\n finally {\n Counter += 2;\n continue;\n }\n\n Counter += 4;\n }\n finally { Counter += 5; }\n\n Counter += 6;\n }\n\n if (Counter != 75) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Continue from a doubly nested finally clause in a loop.\n //\n\n printf(" test36...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n try {\n if ((Index1 & 0x1) == 0) {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 4;\n }\n finally {\n Counter += 5;\n continue;\n }\n\n Counter += 6;\n }\n\n if (Counter != 115) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif\n\n //\n // Break from a try body with an exception clause in a loop.\n //\n\n printf(" test37...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n if ((Index1 & 0x1) == 1) {\n break;\n\n } else {\n Counter += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 40; }\n\n Counter += 2;\n }\n\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#if !defined(WIN_CE) // gotos from try/finally not allowed on WinCE\n //\n // Break from a try body with an finally clause in a loop.\n //\n\n printf(" test38...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n if ((Index1 & 0x1) == 1) {\n break;\n\n } else {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 3;\n }\n\n if (Counter != 8) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif\n\n //\n // Break from doubly nested try body with an exception clause in a\n // loop.\n //\n\n printf(" test39...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n try {\n if ((Index1 & 0x1) == 1) {\n break;\n\n } else {\n Counter += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 10; }\n\n Counter += 2;\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 20; }\n\n Counter += 3;\n }\n\n if (Counter != 6) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#if !defined(WIN_CE) // gotos from try/finally not allowed on WinCE\n //\n // Break from doubly nested try body with an finally clause in a loop.\n //\n\n printf(" test40...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n try {\n if ((Index1 & 0x1) == 1) {\n break;\n\n } else {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 3;\n }\n finally { Counter += 4; }\n\n Counter += 5;\n }\n\n if (Counter != 21) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Break from a finally clause in a loop.\n //\n\n printf(" test41...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n if ((Index1 & 0x1) == 1) {\n Counter += 1;\n }\n }\n finally {\n Counter += 2;\n break;\n }\n\n Counter += 4;\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Break from a doubly nested finally clause in a loop.\n //\n\n printf(" test42...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n try {\n if ((Index1 & 0x1) == 1) {\n Counter += 1;\n }\n }\n finally {\n Counter += 2;\n break;\n }\n\n Counter += 4;\n }\n finally { Counter += 5; }\n\n Counter += 6;\n }\n\n if (Counter != 7) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Break from a doubly nested finally clause in a loop.\n //\n\n printf(" test43...");\n Counter = 0;\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n try {\n try {\n if ((Index1 & 0x1) == 1) {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 4;\n }\n finally {\n Counter += 5;\n break;\n }\n\n Counter += 6;\n }\n\n if (Counter != 11) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif\n\n //\n // Break from a try body with an exception clause in a switch.\n //\n\n printf(" test44...");\n Counter = 0;\n Index1 = 1;\n switch (Index2) {\n case BLUE:\n Counter += 100;\n break;\n\n case RED:\n try {\n if ((Index1 & 0x1) == 1) {\n break;\n\n } else {\n Counter += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 40; }\n\n Counter += 2;\n break;\n }\n\n if (Counter != 0) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#if !defined(WIN_CE) // gotos from try/finally not allowed on WinCE\n //\n // Break from a try body with an finally clause in a switch.\n //\n\n printf(" test45...");\n Counter = 0;\n Index1 = 1;\n switch (Index2) {\n case BLUE:\n Counter += 100;\n break;\n\n case RED:\n try {\n if ((Index1 & 0x1) == 1) {\n break;\n\n } else {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 3;\n }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif\n\n //\n // Break from doubly nested try body with an exception clause in a\n // switch.\n //\n\n printf(" test46...");\n Counter = 0;\n Index1 = 1;\n switch (Index2) {\n case BLUE:\n Counter += 100;\n break;\n\n case RED:\n try {\n try {\n if ((Index1 & 0x1) == 1) {\n break;\n\n } else {\n Counter += 1;\n }\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 10; }\n\n Counter += 2;\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 20; }\n\n Counter += 3;\n }\n\n if (Counter != 0) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#if !defined(WIN_CE) // gotos from try/finally not allowed on WinCE\n //\n // Break from doubly nested try body with an finally clause in a switch.\n //\n\n printf(" test47...");\n Counter = 0;\n Index1 = 1;\n switch (Index2) {\n case BLUE:\n Counter += 100;\n break;\n\n case RED:\n try {\n try {\n if ((Index1 & 0x1) == 1) {\n break;\n\n } else {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 3;\n }\n finally { Counter += 4; }\n\n Counter += 5;\n }\n\n if (Counter != 6) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Break from a finally clause in a switch.\n //\n\n printf(" test48...");\n Counter = 0;\n Index1 = 1;\n switch (Index2) {\n case BLUE:\n Counter += 100;\n break;\n\n case RED:\n try {\n if ((Index1 & 0x1) == 1) {\n Counter += 1;\n }\n }\n finally {\n Counter += 2;\n break;\n }\n\n Counter += 4;\n }\n\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Break from a doubly nested finally clause in a switch.\n //\n\n printf(" test49...");\n Counter = 0;\n Index1 = 1;\n switch (Index2) {\n case BLUE:\n Counter += 100;\n break;\n\n case RED:\n try {\n try {\n if ((Index1 & 0x1) == 1) {\n Counter += 1;\n }\n }\n finally {\n Counter += 2;\n break;\n }\n\n Counter += 4;\n }\n finally { Counter += 5; }\n\n Counter += 6;\n }\n\n if (Counter != 8) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Break from a doubly nested finally clause in a switch.\n //\n\n printf(" test50...");\n Counter = 0;\n Index1 = 1;\n switch (Index2) {\n case BLUE:\n Counter += 100;\n break;\n\n case RED:\n try {\n try {\n if ((Index1 & 0x1) == 1) {\n Counter += 1;\n }\n }\n finally { Counter += 2; }\n\n Counter += 4;\n }\n finally {\n Counter += 5;\n break;\n }\n\n Counter += 6;\n }\n\n if (Counter != 12) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif\n\n //\n // Leave from an if in a simple try/finally.\n //\n\n printf(" test51...");\n Counter = 0;\n try {\n if (Echo(Counter) == Counter) {\n Counter += 3;\n leave;\n\n } else {\n Counter += 100;\n }\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n\n if (Counter != 8) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Leave from a loop in a simple try/finally.\n //\n\n printf(" test52...");\n Counter = 0;\n try {\n for (Index1 = 0; Index1 < 10; Index1 += 1) {\n if (Echo(Index1) == Index1) {\n Counter += 3;\n leave;\n }\n\n Counter += 100;\n }\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n\n if (Counter != 8) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Leave from a switch in a simple try/finally.\n //\n\n printf(" test53...");\n Counter = 0;\n try {\n switch (Index2) {\n case BLUE:\n break;\n\n case RED:\n Counter += 3;\n leave;\n }\n\n Counter += 100;\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n\n if (Counter != 8) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Leave from an if in doubly nested try/finally followed by a leave\n // from an if in the outer try/finally.\n //\n\n printf(" test54...");\n Counter = 0;\n try {\n try {\n if (Echo(Counter) == Counter) {\n Counter += 3;\n leave;\n\n } else {\n Counter += 100;\n }\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n\n if (Echo(Counter) == Counter) {\n Counter += 3;\n leave;\n\n } else {\n Counter += 100;\n }\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n\n if (Counter != 16) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#if !defined(WIN_CE) // leave from finally not allowed on WinCE\n //\n // Leave from an if in doubly nested try/finally followed by a leave\n // from the finally of the outer try/finally.\n //\n\n printf(" test55...");\n Counter = 0;\n try {\n try {\n if (Echo(Counter) == Counter) {\n Counter += 3;\n leave;\n\n } else {\n Counter += 100;\n }\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n leave;\n }\n }\n\n Counter += 100;\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n\n if (Counter != 13) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif\n\n //\n // Try/finally within the except clause of a try/except that is always\n // executed.\n //\n\n printf(" test56...");\n Counter = 0;\n try {\n Counter += 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n except(Counter) {\n try {\n Counter += 3;\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n }\n\n if (Counter != 9) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Try/finally within the finally clause of a try/finally.\n //\n\n printf(" test57...");\n Counter = 0;\n try {\n Counter += 1;\n }\n finally {\n if (abnormal_termination() == FALSE) {\n try {\n Counter += 3;\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n }\n }\n\n if (Counter != 9) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Try/except within the finally clause of a try/finally.\n //\n\n printf(" test58...");\n#if !defined(NEST_IN_FINALLY)\n printf("skipped\\n");\n#else\n Counter = 0;\n try {\n Counter -= 1;\n }\n finally {\n try {\n Counter += 2;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n except(Counter) {\n try {\n Counter += 3;\n }\n finally {\n if (abnormal_termination() == FALSE) {\n Counter += 5;\n }\n }\n }\n }\n\n if (Counter != 9) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif /* def(NEST_IN_FINALLY) */\n\n //\n // Try/except within the except clause of a try/except that is always\n // executed.\n //\n\n printf(" test59...");\n Counter = 0;\n try {\n Counter += 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n except(Counter) {\n try {\n Counter += 3;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n except(Counter - 3) { Counter += 5; }\n }\n\n if (Counter != 9) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Try with a Try which exits the scope with a goto\n //\n\n printf(" test60...");\n Counter = 0;\n try {\n try {\n goto outside;\n }\n except(1) { Counter += 1; }\n\n outside:\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n except(1) { Counter += 3; }\n\n if (Counter != 3) {\n printf("failed, count = %d\\n", Counter);\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Try/except which gets an exception from a subfunction within\n // a try/finally which has a try/except in the finally clause\n //\n\n printf(" test61...");\n#if !defined(NEST_IN_FINALLY)\n printf("skipped\\n");\n#else\n Counter = 0;\n try {\n Test61Part2(&Counter);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { Counter += 11; }\n\n if (Counter != 24) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n#endif /* def(NEST_IN_FINALLY) */\n\n //\n // Check for precision of exception on floating point\n //\n\n printf(" test62...");\n\n#if defined(i386) || defined(_M_IA64) || defined(_M_ALPHA) || defined(_M_AMD64)\n\n/* enable floating point overflow */\n#if defined(i386)\n _control87(_control87(0, 0) & ~EM_OVERFLOW, _MCW_EM);\n#else\n //\n // use portable version of _control87\n //\n _controlfp(_controlfp(0, 0) & ~EM_OVERFLOW, _MCW_EM);\n#endif\n\n Counter = 0;\n try {\n doubleresult = SquareDouble(1.7e300);\n\n try {\n doubleresult = SquareDouble(1.0);\n }\n except(1) { Counter += 3; }\n }\n except(1) { Counter += 1; }\n\n if (Counter != 1) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n/* clear up pending unmasked exceptions and restore FP control registers */\n#if defined(i386)\n _clear87();\n _control87(_control87(0, 0) | EM_OVERFLOW, 0xfffff);\n#else\n _clearfp();\n _controlfp(_controlfp(0, 0) | EM_OVERFLOW, 0xfffff);\n#endif\n\n#else\n printf("skipped\\n");\n#endif\n\n //\n // A try/finally inside a try/except where an exception is raised in the\n // try/finally.\n //\n\n printf(" test63...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n }\n finally {\n Counter += 3;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n }\n except(1) { Counter += 6; }\n\n if (Counter != 10) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A try/finally inside a try/except where an exception is raised in the\n // in the try/except and the try/finally.\n //\n\n printf(" test64...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n finally {\n Counter += 3;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n }\n except(1) { Counter += 6; }\n\n if (Counter != 10) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A try/finally inside a try/except where an exception is raised in the\n // try/finally.\n //\n\n printf(" test65...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n }\n finally {\n Counter += 3;\n *BlackHole += *BadAddress;\n Counter += 13;\n }\n }\n except(1) { Counter += 6; }\n\n if (Counter != 10) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A try/finally inside a try/except where an exception is raised in the\n // in the try/except and the try/finally.\n //\n\n printf(" test66...");\n Counter = 0;\n try {\n try {\n Counter += 1;\n *BlackHole += *BadAddress;\n Counter += 13;\n }\n finally {\n Counter += 3;\n *BlackHole += *BadAddress;\n Counter += 13;\n }\n }\n except(1) { Counter += 6; }\n\n if (Counter != 10) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A try/finally inside a try/finally inside a try/except where an\n // exception is raised in the in the try/except and in try/finally.\n //\n\n printf(" test67...");\n try {\n try {\n *BlackHole += *BadAddress;\n }\n finally {\n try {\n Counter = 0;\n }\n finally {\n if (Counter != 0) {\n Counter += 1;\n }\n }\n\n Counter += 1;\n *BlackHole += *BadAddress;\n }\n }\n except(1) { Counter += 1; }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // A try/finally inside a try/finally inside a try/except where an\n // exception is raised in the in the try/except and in try/finally.\n //\n\n printf(" test68...");\n try {\n try {\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n finally {\n try {\n Counter = 0;\n }\n finally {\n if (Counter != 0) {\n Counter += 1;\n }\n }\n\n Counter += 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n }\n except(1) { Counter += 1; }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n//\n// Patch guard test 69.\n//\n\n#if defined(_AMD64_) || defined(_X86_)\n\n printf(" test69...");\n Counter = 0;\n try {\n PgTest69(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test70...");\n Counter = 0;\n try {\n PgTest70(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 2) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test71...");\n Counter = 0;\n try {\n PgTest71(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 9) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test72...");\n Counter = 0;\n try {\n PgTest72(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 12) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test73...");\n Counter = 0;\n try {\n PgTest73(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 15) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test74...");\n Counter = 0;\n try {\n PgTest74(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 18) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test75...");\n Counter = 0;\n try {\n PgTest75(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 35) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test76...");\n Counter = 0;\n try {\n PgTest76(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 40) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test77...");\n Counter = 0;\n try {\n PgTest77(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 45) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test78...");\n Counter = 0;\n try {\n PgTest78(&Counter, BadAddress);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { printf("unexpected exception..."); }\n\n if (Counter != 50) {\n printf("failed, count = %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n#else\n printf(" test69...filter entered...succeeded\\n");\n printf(" test70...filter entered...succeeded\\n");\n printf(" test71...filter entered...succeeded\\n");\n printf(" test72...filter entered...succeeded\\n");\n printf(" test73...filter entered...succeeded\\n");\n printf(" test74...filter entered...succeeded\\n");\n printf(" test75...filter entered...succeeded\\n");\n printf(" test76...filter entered...succeeded\\n");\n printf(" test77...filter entered...succeeded\\n");\n printf(" test78...filter entered...succeeded\\n");\n#endif\n\n if (LOBYTE(LOWORD(GetVersion())) < 6) {\n printf(" test79...");\n printf("filter 1...filter 2...finally 1...filter 1...filter 2...finally "\n "2...passed\\n");\n } else {\n\n printf(" test79...");\n Counter = 0;\n try {\n Test79(&Counter, BadAddress);\n }\n except(printf("filter 2..."), EXCEPTION_EXECUTE_HANDLER) { Counter += 1; }\n\n if (Counter == 3) {\n printf("passed\\n");\n\n } else {\n printf("failed %d \\n", Counter);\n }\n }\n\n printf(" test80...");\n if (Test80() != 0) {\n printf("failed\\n");\n\n } else {\n printf("passed\\n");\n }\n\n printf(" test81...");\n Counter = 0;\n Test81(&Counter);\n if (Counter != 1) {\n printf("failed %d \\n", Counter);\n\n } else {\n printf("passed\\n");\n }\n\n printf(" test82...");\n Counter = 1;\n Test82(&Counter);\n if (Counter != 0) {\n printf("failed\\n");\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test83...");\n if (Test83() != 0) {\n printf("failed\\n");\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test84...");\n Counter = 0;\n Test84(&Counter);\n if (Counter != 2) {\n printf("failed\\n");\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test85...");\n Counter = 0;\n Test85(&Counter);\n if (Counter != 7) {\n printf("failed\\n");\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test86...");\n Counter = 0;\n Test86(&Counter);\n if (Counter != 4) {\n printf("failed %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test87...");\n Counter = 0;\n Test87(&Counter);\n if (Counter != 104) {\n printf("failed %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n printf(" test88...");\n Counter = 0;\n Test88(&Counter);\n if (Counter != 6) {\n printf("failed %d\\n", Counter);\n\n } else {\n printf("succeeded\\n");\n }\n\n //\n // Announce end of exception test.\n //\n\n printf("End of exception test\\n");\n return;\n}\n\n#pragma optimize("a", off)\nVOID addtwo(long First, long Second, long *Place)\n\n{\n\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n *Place = First + Second;\n return;\n}\n#pragma optimize("", on)\n\nVOID bar1(IN NTSTATUS Status, IN PLONG Counter) {\n\n try {\n foo1(Status);\n }\n finally {\n if (abnormal_termination() != FALSE) {\n *Counter = 99;\n\n } else {\n *Counter = 100;\n }\n }\n\n return;\n}\n\nVOID bar2(IN PLONG BlackHole, IN PLONG BadAddress, IN PLONG Counter) {\n\n try {\n foo2(BlackHole, BadAddress);\n }\n finally {\n if (abnormal_termination() != FALSE) {\n *Counter = 99;\n\n } else {\n *Counter = 100;\n }\n }\n\n return;\n}\n\nVOID dojump(IN jmp_buf JumpBuffer, IN PLONG Counter)\n\n{\n\n try {\n try {\n *Counter += 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n finally { *Counter += 1; }\n }\n finally {\n *Counter += 1;\n longjmp(JumpBuffer, 1);\n }\n}\n\n#if !defined(WIN_CE) // return through finally not allowed on WinCE\nVOID eret(IN NTSTATUS Status, IN PLONG Counter)\n\n{\n\n try {\n try {\n foo1(Status);\n }\n except((GetExceptionCode() == Status) ? EXCEPTION_EXECUTE_HANDLER\n : EXCEPTION_CONTINUE_SEARCH) {\n *Counter += 1;\n return;\n }\n }\n finally { *Counter += 1; }\n\n return;\n}\n#endif\n\nVOID except1(IN PLONG Counter)\n\n{\n\n try {\n *Counter += 5;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n except(except3(GetExceptionInformation(), Counter)) { *Counter += 7; }\n\n *Counter += 9;\n return;\n}\n\nULONG\nexcept2(IN PEXCEPTION_POINTERS ExceptionPointers, IN PLONG Counter)\n\n{\n\n PEXCEPTION_RECORD ExceptionRecord;\n\n ExceptionRecord = ExceptionPointers->ExceptionRecord;\n if ((ExceptionRecord->ExceptionCode == STATUS_UNSUCCESSFUL) &&\n ((ExceptionRecord->ExceptionFlags & EXCEPTION_NESTED_CALL) == 0)) {\n *Counter += 11;\n return EXCEPTION_EXECUTE_HANDLER;\n\n } else {\n *Counter += 13;\n return EXCEPTION_CONTINUE_SEARCH;\n }\n}\n\nULONG\nexcept3(IN PEXCEPTION_POINTERS ExceptionPointers, IN PLONG Counter)\n\n{\n\n PEXCEPTION_RECORD ExceptionRecord;\n\n ExceptionRecord = ExceptionPointers->ExceptionRecord;\n if ((ExceptionRecord->ExceptionCode == STATUS_INTEGER_OVERFLOW) &&\n ((ExceptionRecord->ExceptionFlags & EXCEPTION_NESTED_CALL) == 0)) {\n *Counter += 17;\n RtlRaiseStatus(STATUS_UNSUCCESSFUL);\n\n } else if ((ExceptionRecord->ExceptionCode == STATUS_UNSUCCESSFUL) &&\n ((ExceptionRecord->ExceptionFlags & EXCEPTION_NESTED_CALL) != 0)) {\n *Counter += 19;\n return EXCEPTION_CONTINUE_SEARCH;\n }\n\n *Counter += 23;\n return EXCEPTION_EXECUTE_HANDLER;\n}\n\nVOID foo1(IN NTSTATUS Status)\n\n{\n\n //\n // Raise exception.\n //\n\n RtlRaiseStatus(Status);\n return;\n}\n\nVOID foo2(IN PLONG BlackHole, IN PLONG BadAddress)\n\n{\n\n //\n // Raise exception.\n //\n\n *BlackHole += *BadAddress;\n return;\n}\n\n#if !defined(WIN_CE) // return from finally not allowed on WinCE\nVOID fret(IN PLONG Counter)\n\n{\n\n try {\n try {\n *Counter += 1;\n }\n finally {\n *Counter += 1;\n return;\n }\n }\n finally { *Counter += 1; }\n\n return;\n}\n#endif\n\nLONG Echo(IN LONG Value)\n\n{\n return Value;\n}\n\n#if defined(NEST_IN_FINALLY)\nVOID Test61Part2(IN OUT PULONG Counter) {\n try {\n *Counter -= 1;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n finally {\n try {\n *Counter += 2;\n RtlRaiseStatus(STATUS_INTEGER_OVERFLOW);\n }\n except(EXCEPTION_EXECUTE_HANDLER) { *Counter += 5; }\n *Counter += 7;\n }\n}\n#endif /* def(NEST_IN_FINALLY) */\n\ndouble SquareDouble(IN double op) {\n return exp(2.0 * log(op));\n}\n
sample_code.cameligo = type storage = int\ntype parameter =\n Increment of int\n| Decrement of int\n| Reset\ntype return = operation list * storage\n// Two entrypoints\nlet add (store, delta : storage * int) : storage = store + delta\nlet sub (store, delta : storage * int) : storage = store - delta\n(* Main access point that dispatches to the entrypoints according to\n the smart contract parameter. *)\nlet main (action, store : parameter * storage) : return =\n ([] : operation list), // No operations\n (match action with\n Increment (n) -> add (store, n)\n | Decrement (n) -> sub (store, n)\n | Reset -> 0)\n
sample_code.clojure = (ns game-of-life\n "Conway's Game of Life, based on the work of\n Christophe Grand (http://clj-me.cgrand.net/2011/08/19/conways-game-of-life)\n and Laurent Petit (https://gist.github.com/1200343).")\n\n;;; Core game of life's algorithm functions\n\n(defn neighbors\n "Given a cell's coordinates `[x y]`, returns the coordinates of its\n neighbors."\n [[x y]]\n (for [dx [-1 0 1]\n dy (if (zero? dx)\n [-1 1]\n [-1 0 1])]\n [(+ dx x) (+ dy y)]))\n\n(defn step\n "Given a set of living `cells`, computes the new set of living cells."\n [cells]\n (set (for [[cell n] (frequencies (mapcat neighbors cells))\n :when (or (= n 3)\n (and (= n 2)\n (cells cell)))]\n cell)))\n\n;;; Utility methods for displaying game on a text terminal\n\n(defn print-grid\n "Prints a `grid` of `w` columns and `h` rows, on *out*, representing a\n step in the game."\n [grid w h]\n (doseq [x (range (inc w))\n y (range (inc h))]\n (when (= y 0) (println))\n (print (if (grid [x y])\n "[X]"\n " . "))))\n\n(defn print-grids\n "Prints a sequence of `grids` of `w` columns and `h` rows on *out*,\n representing several steps."\n [grids w h]\n (doseq [grid grids]\n (print-grid grid w h)\n (println)))\n\n;;; Launches an example grid\n\n(def grid\n "`grid` represents the initial set of living cells"\n #{[2 1] [2 2] [2 3]})\n\n(print-grids (take 3 (iterate step grid)) 5 5)
sample_code.coffeescript = """\nA CoffeeScript sample.\n"""\n\nclass Vehicle\n constructor: (@name) =>\n \n drive: () =>\n alert "Conducting #{@name}"\n\nclass Car extends Vehicle\n drive: () =>\n alert "Driving #{@name}"\n\nc = new Car "Brandie"\n\nwhile notAtDestination()\n c.drive()\n\nraceVehicles = (new Car for i in [1..100])\n\nstartRace = (vehicles) -> [vehicle.drive() for vehicle in vehicles]\n\nfancyRegExp = ///\n\u0009(\\d+)\u0009# numbers\n\u0009(\\w*)\u0009# letters\n\u0009$\u0009\u0009# the end\n///\n
sample_code.cpp = #include "pch.h"\n#include "Direct3DBase.h"\n\nusing namespace Microsoft::WRL;\nusing namespace Windows::UI::Core;\nusing namespace Windows::Foundation;\n\n// Constructor.\nDirect3DBase::Direct3DBase()\n{\n}\n\n// Initialize the Direct3D resources required to run.\nvoid Direct3DBase::Initialize(CoreWindow^ window)\n{\n m_window = window;\n \n CreateDeviceResources();\n CreateWindowSizeDependentResources();\n}\n\n// These are the resources that depend on the device.\nvoid Direct3DBase::CreateDeviceResources()\n{\n // This flag adds support for surfaces with a different color channel ordering than the API default.\n // It is recommended usage, and is required for compatibility with Direct2D.\n UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;\n\n#if defined(_DEBUG)\n // If the project is in a debug build, enable debugging via SDK Layers with this flag.\n creationFlags |= D3D11_CREATE_DEVICE_DEBUG;\n#endif\n\n // This array defines the set of DirectX hardware feature levels this app will support.\n // Note the ordering should be preserved.\n // Don't forget to declare your application's minimum required feature level in its\n // description. All applications are assumed to support 9.1 unless otherwise stated.\n D3D_FEATURE_LEVEL featureLevels[] = \n {\n D3D_FEATURE_LEVEL_11_1,\n D3D_FEATURE_LEVEL_11_0,\n D3D_FEATURE_LEVEL_10_1,\n D3D_FEATURE_LEVEL_10_0,\n D3D_FEATURE_LEVEL_9_3,\n D3D_FEATURE_LEVEL_9_2,\n D3D_FEATURE_LEVEL_9_1\n };\n\n // Create the DX11 API device object, and get a corresponding context.\n ComPtr<ID3D11Device> device;\n ComPtr<ID3D11DeviceContext> context;\n DX::ThrowIfFailed(\n D3D11CreateDevice(\n nullptr, // specify null to use the default adapter\n D3D_DRIVER_TYPE_HARDWARE,\n nullptr, // leave as nullptr unless software device\n creationFlags, // optionally set debug and Direct2D compatibility flags\n featureLevels, // list of feature levels this app can support\n ARRAYSIZE(featureLevels), // number of entries in above list\n D3D11_SDK_VERSION, // always set this to D3D11_SDK_VERSION\n &device, // returns the Direct3D device created\n &m_featureLevel, // returns feature level of device created\n &context // returns the device immediate context\n )\n );\n\n // Get the DirectX11.1 device by QI off the DirectX11 one.\n DX::ThrowIfFailed(\n device.As(&m_d3dDevice)\n );\n\n // And get the corresponding device context in the same way.\n DX::ThrowIfFailed(\n context.As(&m_d3dContext)\n );\n}\n\n// Allocate all memory resources that change on a window SizeChanged event.\nvoid Direct3DBase::CreateWindowSizeDependentResources()\n{ \n // Store the window bounds so the next time we get a SizeChanged event we can\n // avoid rebuilding everything if the size is identical.\n m_windowBounds = m_window->Bounds;\n\n // If the swap chain already exists, resize it.\n if(m_swapChain != nullptr)\n {\n DX::ThrowIfFailed(\n m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0)\n );\n }\n // Otherwise, create a new one.\n else\n {\n // Create a descriptor for the swap chain.\n DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};\n swapChainDesc.Width = 0; // use automatic sizing\n swapChainDesc.Height = 0;\n swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // this is the most common swapchain format\n swapChainDesc.Stereo = false; \n swapChainDesc.SampleDesc.Count = 1; // don't use multi-sampling\n swapChainDesc.SampleDesc.Quality = 0;\n swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;\n swapChainDesc.BufferCount = 2; // use two buffers to enable flip effect\n swapChainDesc.Scaling = DXGI_SCALING_NONE;\n swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // we recommend using this swap effect for all applications\n swapChainDesc.Flags = 0;\n\n // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device\n\n // First, retrieve the underlying DXGI Device from the D3D Device\n ComPtr<IDXGIDevice1> dxgiDevice;\n DX::ThrowIfFailed(\n m_d3dDevice.As(&dxgiDevice)\n );\n\n // Identify the physical adapter (GPU or card) this device is running on.\n ComPtr<IDXGIAdapter> dxgiAdapter;\n DX::ThrowIfFailed(\n dxgiDevice->GetAdapter(&dxgiAdapter)\n );\n\n // And obtain the factory object that created it.\n ComPtr<IDXGIFactory2> dxgiFactory;\n DX::ThrowIfFailed(\n dxgiAdapter->GetParent(\n __uuidof(IDXGIFactory2), \n &dxgiFactory\n )\n );\n\n\u0009\u0009Windows::UI::Core::CoreWindow^ p = m_window.Get();\n\n // Create a swap chain for this window from the DXGI factory.\n DX::ThrowIfFailed(\n dxgiFactory->CreateSwapChainForCoreWindow(\n m_d3dDevice.Get(),\n reinterpret_cast<IUnknown*>(p),\n &swapChainDesc,\n nullptr, // allow on all displays\n &m_swapChain\n )\n );\n \n // Ensure that DXGI does not queue more than one frame at a time. This both reduces \n // latency and ensures that the application will only render after each VSync, minimizing \n // power consumption.\n DX::ThrowIfFailed(\n dxgiDevice->SetMaximumFrameLatency(1)\n );\n }\n \n // Obtain the backbuffer for this window which will be the final 3D rendertarget.\n ComPtr<ID3D11Texture2D> backBuffer;\n DX::ThrowIfFailed(\n m_swapChain->GetBuffer(\n 0,\n __uuidof(ID3D11Texture2D),\n &backBuffer\n )\n );\n\n // Create a view interface on the rendertarget to use on bind.\n DX::ThrowIfFailed(\n m_d3dDevice->CreateRenderTargetView(\n backBuffer.Get(),\n nullptr,\n &m_renderTargetView\n )\n );\n\n // Cache the rendertarget dimensions in our helper class for convenient use.\n D3D11_TEXTURE2D_DESC backBufferDesc;\n backBuffer->GetDesc(&backBufferDesc);\n m_renderTargetSize.Width = static_cast<float>(backBufferDesc.Width);\n m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);\n\n // Create a descriptor for the depth/stencil buffer.\n CD3D11_TEXTURE2D_DESC depthStencilDesc(\n DXGI_FORMAT_D24_UNORM_S8_UINT, \n backBufferDesc.Width,\n backBufferDesc.Height,\n 1,\n 1,\n D3D11_BIND_DEPTH_STENCIL);\n\n // Allocate a 2-D surface as the depth/stencil buffer.\n ComPtr<ID3D11Texture2D> depthStencil;\n DX::ThrowIfFailed(\n m_d3dDevice->CreateTexture2D(\n &depthStencilDesc,\n nullptr,\n &depthStencil\n )\n );\n\n // Create a DepthStencil view on this surface to use on bind.\n DX::ThrowIfFailed(\n m_d3dDevice->CreateDepthStencilView(\n depthStencil.Get(),\n &CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D),\n &m_depthStencilView\n )\n );\n\n // Create a viewport descriptor of the full window size.\n CD3D11_VIEWPORT viewPort(\n 0.0f,\n 0.0f,\n static_cast<float>(backBufferDesc.Width),\n static_cast<float>(backBufferDesc.Height)\n );\n \n // Set the current viewport using the descriptor.\n m_d3dContext->RSSetViewports(1, &viewPort);\n}\n\nvoid Direct3DBase::UpdateForWindowSizeChange()\n{\n if (m_window->Bounds.Width != m_windowBounds.Width ||\n m_window->Bounds.Height != m_windowBounds.Height)\n {\n m_renderTargetView = nullptr;\n m_depthStencilView = nullptr;\n CreateWindowSizeDependentResources();\n }\n}\n\nvoid Direct3DBase::Present()\n{\n // The first argument instructs DXGI to block until VSync, putting the application\n // to sleep until the next VSync. This ensures we don't waste any cycles rendering\n // frames that will never be displayed to the screen.\n HRESULT hr = m_swapChain->Present(1, 0);\n\n // If the device was removed either by a disconnect or a driver upgrade, we \n // must completely reinitialize the renderer.\n if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)\n {\n Initialize(m_window.Get());\n }\n else\n {\n DX::ThrowIfFailed(hr);\n }\n}\n
sample_code.csharp = /*\n* C# Program to Display All the Prime Numbers Between 1 to 100\n*/\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace VS\n{\n\u0009class Program\n\u0009{\n\u0009\u0009static void Main(string[] args)\n\u0009\u0009{\n\u0009\u0009\u0009bool isPrime = true;\n\u0009\u0009\u0009Console.WriteLine("Prime Numbers : ");\n\u0009\u0009\u0009for (int i = 2; i <= 100; i++)\n\u0009\u0009\u0009{\n\u0009\u0009\u0009\u0009for (int j = 2; j <= 100; j++)\n\u0009\u0009\u0009\u0009{\n\u0009\u0009\u0009\u0009\u0009if (i != j && i % j == 0)\n\u0009\u0009\u0009\u0009\u0009{\n\u0009\u0009\u0009\u0009\u0009\u0009isPrime = false;\n\u0009\u0009\u0009\u0009\u0009\u0009break;\n\u0009\u0009\u0009\u0009\u0009}\n\u0009\u0009\u0009\u0009}\n\u0009\u0009\u0009\u0009\n\u0009\u0009\u0009\u0009if (isPrime)\n\u0009\u0009\u0009\u0009{\n\u0009\u0009\u0009\u0009\u0009Console.Write("\\t" +i);\n\u0009\u0009\u0009\u0009}\n\u0009\u0009\u0009\u0009isPrime = true;\n\u0009\u0009\u0009}\n\u0009\u0009\u0009Console.ReadKey();\n\u0009\u0009}\n\u0009}\n}\n
sample_code.csp = Content-Security-Policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com
sample_code.css = html {\n background-color: #e2e2e2;\n margin: 0;\n padding: 0;\n}\n\nbody {\n background-color: #fff;\n border-top: solid 10px #000;\n color: #333;\n font-size: .85em;\n font-family: "Segoe UI","HelveticaNeue-Light", sans-serif;\n margin: 0;\n padding: 0;\n}\n\na:link, a:visited, \na:active, a:hover {\n color: #333;\n outline: none;\n padding-left: 0;\n padding-right: 3px;\n text-decoration: none;\n \n}\n\n\na:hover {\n background-color: #c7d1d6;\n}\n\n\nheader, footer, hgroup\nnav, section {\n display: block;\n}\n\n.float-left {\n float: left;\n}\n\n.float-right {\n float: right;\n}\n\n.highlight {\n/* background-color: #a6dbed;\n padding-left: 5px;\n padding-right: 5px;*/\n}\n\n.clear-fix:after {\n content: ".";\n clear: both;\n display: block;\n height: 0;\n visibility: hidden;\n}\n\nh1, h2, h3, \nh4, h5, h6 {\n color: #000;\n margin-bottom: 0;\n padding-bottom: 0;\n \n}\n\nh1 {\n font-size: 2em; \n}\n\nh2 {\n font-size: 1.75em;\n}\n\nh3 {\n font-size: 1.2em;\n}\n\nh4 {\n font-size: 1.1em;\n}\n\nh5, h6 {\n font-size: 1em;\n}\n\n\n.tile {\n /* 2px solid #7ac0da; */\n border: 0;\n \n float: left;\n width: 200px;\n height: 325px;\n \n padding: 5px;\n margin-right: 5px;\n margin-bottom: 20px;\n margin-top: 20px;\n -webkit-perspective: 0;\n -webkit-transform-style: preserve-3d;\n -webkit-transition: -webkit-transform 0.2s;\n -webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.3);\n background-position: center center;\n background-repeat: no-repeat;\n \n background-color: #fff;\n}\n\n.tile-item {\n /* 2px solid #7ac0da; */\n border-color: inherit;\n float: left;\n width: 50px;\n height: 70px;\n margin-right: 20px;\n margin-bottom: 20px;\n margin-top: 20px;\n background-image: url('../Images/documents.png');\n background-repeat: no-repeat;\n \n}\n\n.tile-wrapper {\n width: 100%;\n font-family: "Segoe UI" , Tahoma, Geneva, Verdana, sans-serif;\n line-height: 21px;\n font-size: 14px;\n}\n\na.blue-box {\n font-size: 28px;\n height: 100px;\n display: block;\n border-style: solid;\n border-width: 1px 1px 4px 1px;\n border-color: #C0C0C0 #C0C0C0 #8ABAE4 #C0C0C0;\n padding-top: 15px;\n padding-left: 15px;\n}\n\n a.blue-box:hover {\n border: 4px solid #8ABAE4; \n padding-top: 12px;\n padding-left: 12px;\n background-color: #FFFFFF;\n}\n \na.green-box {\n font-size: 28px;\n height: 100px;\n display: block;\n border-style: solid;\n border-width: 1px 1px 4px 1px;\n border-color: #C0C0C0 #C0C0C0 #9CCF42 #C0C0C0;\n padding-top: 15px;\n padding-left: 15px;\n}\n\n a.green-box:hover {\n border: 4px solid #9CCF42; \n padding-top: 12px;\n padding-left: 12px;\n background-color: #FFFFFF;\n}\n\n\na.green-box2 {\n font-size: 14px;\n height: 48px;\n width: 48px;\n display: block; /* border-color: #C0C0C0; */\n padding-top: 6px;\n font-weight: bold;\n \n}\n\n a.green-box2:hover {\n border: solid #8ABAE4;\n padding-top: 0px;\n padding-left: 0px;\n background-image: url('../Images/documents.png');\n background-color: #EFEFEF;\n}\n\na.yellow-box {\n font-size: 28px;\n height: 100px;\n display: block;\n border-style: solid;\n border-width: 1px 1px 4px 1px;\n border-color: #C0C0C0 #C0C0C0 #DECF6B #C0C0C0;\n padding-top: 15px;\n padding-left: 15px;\n}\n\n a.yellow-box:hover {\n border: 4px solid #DECF6B; \n padding-top: 12px;\n padding-left: 12px;\n background-color: #FFFFFF;\n}\n \n \na.red-box {\n font-size: 28px;\n height: 100px;\n display: block;\n border-style: solid;\n border-width: 1px 1px 4px 1px;\n border-color: #C0C0C0 #C0C0C0 #F79E84 #C0C0C0;\n padding-top: 15px;\n padding-left: 15px;\n}\n\n a.red-box:hover {\n border: 4px solid #F79E84; \n padding-top: 12px;\n padding-left: 12px;\n background-color: #FFFFFF;\n}\n \n/* main layout \n----------------------------------------------------------*/\n.content-wrapper {\n margin: 0 auto;\n max-width: 960px;\n}\n\n#body {\n background-color: #efeeef;\n clear: both;\n padding-bottom: 35px;\n}\n\n .main-content {\n background: url("../images/accent.png") no-repeat;\n padding-left: 10px;\n padding-top: 30px;\n }\n\n .featured + .main-content {\n background: url("../images/heroaccent.png") no-repeat;\n }\n\nfooter {\n clear: both;\n background-color: #e2e2e2;\n font-size: .8em;\n height: 100px;\n}\n\n\n/* site title\n----------------------------------------------------------*/\n.site-title {\n color: #0066CC; /* font-family: Rockwell, Consolas, "Courier New", Courier, monospace; */\n font-size: 3.3em;\n margin-top: 40px;\n margin-bottom: 0;\n}\n\n.site-title a, .site-title a:hover, .site-title a:active {\n background: none;\n color: #0066CC;\n outline: none;\n text-decoration: none;\n}\n\n\n/* login \n----------------------------------------------------------*/\n#login {\n display: block;\n font-size: .85em;\n margin-top: 20px;\n text-align: right;\n}\n\n #login a {\n background-color: #d3dce0;\n margin-left: 10px;\n margin-right: 3px;\n padding: 2px 3px;\n text-decoration: none;\n }\n \n #login a.username {\n background: none;\n margin-left: 0px;\n text-decoration: underline;\n }\n\n #login li {\n display: inline;\n list-style: none;\n }\n \n \n/* menu \n----------------------------------------------------------*/\nul#menu {\n font-size: 1.3em;\n font-weight: 600;\n margin: 0;\n text-align: right;\n text-decoration: none;\n\n}\n\n ul#menu li {\n display: inline;\n list-style: none;\n padding-left: 15px;\n }\n\n ul#menu li a {\n background: none;\n color: #999;\n text-decoration: none;\n }\n\n ul#menu li a:hover {\n color: #333;\n text-decoration: none;\n }\n\n\n\n/* page elements \n----------------------------------------------------------*/\n/* featured */\n.featured {\n background-color: #fff;\n}\n\n .featured .content-wrapper {\n /*background-color: #7ac0da;\n background-image: -ms-linear-gradient(left, #7AC0DA 0%, #A4D4E6 100%);\n background-image: -o-linear-gradient(left, #7AC0DA 0%, #A4D4E6 100%);\n background-image: -webkit-gradient(linear, left top, right top, color-stop(0, #7AC0DA), color-stop(1, #A4D4E6));\n background-image: -webkit-linear-gradient(left, #7AC0DA 0%, #A4D4E6 100%);\n background-image: linear-gradient(left, #7AC0DA 0%, #A4D4E6 100%);\n color: #3e5667;\n */\n padding: 0px 40px 30px 40px;\n }\n\n .featured hgroup.title h1, .featured hgroup.title h2 {\n /* color: #fff;\n */\n }\n\n .featured p {\n font-size: 1.1em;\n }\n\n/* page titles */ \nhgroup.title {\n margin-bottom: 10px;\n}\n\nhgroup.title h1, hgroup.title h2 {\ndisplay: inline;\n}\n\nhgroup.title h2 {\n font-weight: normal;\n}\n\n/* releases */\n.milestone {\n color: #fff;\n background-color: #8ABAE4;\n font-weight: normal;\n padding: 10px 10px 10px 10px;\n margin: 0 0 0 0;\n}\n .milestone .primary {\n font-size: 1.75em;\n }\n\n .milestone .secondary {\n font-size: 1.2em;\n font-weight: normal;\n /* padding: 5px 5px 5px 10px;*/\n }\n \n/* features */\nsection.feature {\n width: 200px;\n float: left;\n padding: 10px;\n}\n\n/* ordered list */\nol.round {\n list-style-type: none;\n padding-left: 0;\n}\n\n ol.round li {\n margin: 25px 0;\n padding-left: 45px;\n }\n \n ol.round li.one {\n background: url("../images/orderedlistOne.png") no-repeat; \n }\n \n ol.round li.two {\n background: url("../images/orderedlistTwo.png") no-repeat; \n }\n \n ol.round li.three {\n background: url("../images/orderedlistThree.png") no-repeat; \n }\n \n/* content */ \narticle {\n float: left;\n width: 70%;\n}\n\naside {\n float: right;\n width: 25%;\n}\n\n aside ul {\n list-style: none;\n padding: 0;\n }\n \n aside ul li {\n background: url("../images/bullet.png") no-repeat 0 50%;\n padding: 2px 0 2px 20px;\n }\n \n.label {\n font-weight: 700;\n}\n\n/* login page */ \n#loginForm {\n border-right: solid 2px #c8c8c8;\n float: left;\n width: 45%;\n}\n\n #loginForm .validation-error {\n display: block;\n margin-left: 15px;\n }\n\n#socialLoginForm {\n margin-left: 40px;\n float: left;\n width: 50%;\n}\n\n/* contact */\n.contact h3 {\n font-size: 1.2em;\n}\n\n.contact p {\n margin: 5px 0 0 10px;\n}\n\n.contact iframe {\n border: solid 1px #333;\n margin: 5px 0 0 10px;\n}\n\n/* forms */\nfieldset {\n border: none;\n margin: 0;\n padding: 0;\n}\n\n fieldset legend {\n display: none;\n }\n \n fieldset ol {\n padding: 0;\n list-style: none;\n }\n \n fieldset ol li {\n padding-bottom: 5px;\n }\n \n fieldset label {\n display: block;\n font-size: 1.2em;\n font-weight: 600;\n }\n \n fieldset label.checkbox {\n display: inline;\n }\n \n fieldset input[type="text"], \n fieldset input[type="password"] {\n border: 1px solid #e2e2e2;\n color: #333;\n font-size: 1.2em;\n margin: 5px 0 6px 0;\n padding: 5px;\n width: 300px;\n }\n \n fieldset input[type="text"]:focus, \n fieldset input[type="password"]:focus {\n border: 1px solid #7ac0da;\n }\n \n fieldset input[type="submit"] {\n background-color: #d3dce0;\n border: solid 1px #787878;\n cursor: pointer;\n font-size: 1.2em;\n font-weight: 600;\n padding: 7px;\n }\n\n/* ajax login/registration dialog */\n.modal-popup {\n font-size: 0.7em;\n}\n\n/* info and errors */ \n.message-info {\n border: solid 1px;\n clear: both;\n padding: 10px 20px;\n}\n\n.message-error {\n clear: both;\n color: #e80c4d;\n font-size: 1.1em;\n font-weight: bold;\n margin: 20px 0 10px 0;\n}\n\n.message-success {\n color: #7ac0da;\n font-size: 1.3em;\n font-weight: bold;\n margin: 20px 0 10px 0;\n}\n\n.success {\n color: #7ac0da;\n}\n\n.error {\n color: #e80c4d;\n}\n\n/* styles for validation helpers */\n.field-validation-error {\n color: #e80c4d;\n font-weight: bold;\n}\n\n.field-validation-valid {\n display: none;\n}\n\ninput[type="text"].input-validation-error,\ninput[type="password"].input-validation-error {\n border: solid 1px #e80c4d;\n}\n\n.validation-summary-errors {\n color: #e80c4d;\n font-weight: bold;\n font-size: 1.1em;\n}\n\n.validation-summary-valid {\n display: none;\n}\n\n\n/* social */\nul#social li {\n display: inline;\n list-style: none;\n}\n\n ul#social li a {\n color: #999;\n text-decoration: none;\n }\n \n a.facebook, a.twitter {\n display: block;\n float: left;\n height: 24px;\n padding-left: 17px;\n text-indent: -9999px;\n width: 16px;\n }\n \n a.facebook {\n background: url("../images/facebook.png") no-repeat;\n }\n \n a.twitter {\n background: url("../images/twitter.png") no-repeat;\n }\n \n \n \n/********************\n* Mobile Styles *\n********************/\n@media only screen and (max-width: 850px) {\n \n /* header \n ----------------------------------------------------------*/\n header .float-left, \n header .float-right {\n float: none;\n }\n \n /* logo */\n header .site-title {\n /*margin: 0; */\n /*margin: 10px;*/\n text-align: left;\n padding-left: 0;\n }\n\n /* login */\n #login {\n font-size: .85em;\n margin-top: 0;\n text-align: center;\n }\n \n #login ul {\n margin: 5px 0;\n padding: 0;\n }\n \n #login li {\n display: inline;\n list-style: none;\n margin: 0;\n padding:0;\n }\n\n #login a {\n background: none;\n color: #999;\n font-weight: 600;\n margin: 2px;\n padding: 0;\n }\n \n #login a:hover {\n color: #333;\n }\n\n /* menu */\n nav {\n margin-bottom: 5px;\n }\n \n ul#menu {\n margin: 0;\n padding:0;\n text-align: center;\n }\n\n ul#menu li {\n margin: 0;\n padding: 0;\n }\n\n \n /* main layout \n ----------------------------------------------------------*/\n .main-content,\n .featured + .main-content {\n background-position: 10px 0;\n }\n \n .content-wrapper {\n padding-right: 10px;\n padding-left: 10px;\n }\n\n .featured .content-wrapper {\n padding: 10px;\n }\n \n /* page content */ \n article, aside {\n float: none;\n width: 100%;\n }\n \n /* ordered list */\n ol.round {\n list-style-type: none;\n padding-left: 0;\n }\n\n ol.round li {\n padding-left: 10px;\n margin: 25px 0;\n }\n \n ol.round li.one,\n ol.round li.two,\n ol.round li.three {\n background: none; \n }\n \n /* features */\n section.feature {\n float: none;\n padding: 10px;\n width: auto;\n }\n \n section.feature img {\n color: #999;\n content: attr(alt);\n font-size: 1.5em;\n font-weight: 600;\n }\n \n /* forms */ \n fieldset input[type="text"], \n fieldset input[type="password"] {\n width: 90%;\n }\n \n /* login page */ \n #loginForm {\n border-right: none;\n float: none;\n width: auto;\n }\n\n #loginForm .validation-error {\n display: block;\n margin-left: 15px;\n }\n\n #socialLoginForm {\n margin-left: 0;\n float: none;\n width: auto;\n }\n\n /* footer \n ----------------------------------------------------------*/ \n footer .float-left,\n footer .float-right {\n float: none;\n }\n \n footer {\n text-align: center;\n height: auto;\n padding: 10px 0;\n }\n \n footer p {\n margin: 0;\n }\n \n ul#social {\n padding:0;\n margin: 0;\n }\n \n a.facebook, a.twitter {\n background: none;\n display: inline;\n float: none;\n height: auto;\n padding-left: 0;\n text-indent: 0;\n width: auto;\n } \n}\n\n.subsite {\n\u0009color: #444;\n}\n\nh3 {\n\u0009font-weight: normal;\n\u0009font-size: 24px;\n\u0009color: #444;\n\u0009margin-bottom: 20px;\n}\n\n.tiles {\n\u0009padding-bottom: 20px;\n\u0009background-color: #e3e3e3;\n}\n\n#editor {\n\u0009margin: 0 auto;\n\u0009height: 500px;\n\u0009border: 1px solid #ccc;\n}\n\n.monaco-editor.monaco, .monaco-editor.vs, .monaco-editor.eclipse {\n\u0009background: #F9F9F9;\n}\n\n.monaco-editor.monaco .monaco-editor-background, .monaco-editor.vs .monaco-editor-background, .monaco-editor.eclipse .monaco-editor-background {\n\u0009background: #F9F9F9;\n}
sample_code.cypher = MATCH (person:Person)-[:WORKS_FOR]->(company)\nWHERE company.name STARTS WITH "Company"\nAND EXISTS {\n MATCH (person)-[:LIKES]->(t:Technology)\n WHERE size((t)<-[:LIKES]-()) >= 3\n}\nRETURN person.name as person, company.name AS company;\n
sample_code.dart = import 'dart:async';\nimport 'dart:math' show Random;\nmain() async {\n print('Compute \u03C0 using the Monte Carlo method.');\n await for (var estimate in computePi().take(100)) {\n print('\u03C0 \u2245 $estimate');\n }\n}\n/// Generates a stream of increasingly accurate estimates of \u03C0.\nStream<double> computePi({int batch: 100000}) async* {\n var total = 0;\n var count = 0;\n while (true) {\n var points = generateRandom().take(batch);\n var inside = points.where((p) => p.isInsideUnitCircle);\n total += batch;\n count += inside.length;\n var ratio = count / total;\n // Area of a circle is A = \u03C0\u22C5r\u00B2, therefore \u03C0 = A/r\u00B2.\n // So, when given random points with x \u2208 <0,1>,\n // y \u2208 <0,1>, the ratio of those inside a unit circle\n // should approach \u03C0 / 4. Therefore, the value of \u03C0\n // should be:\n yield ratio * 4;\n }\n}\nIterable<Point> generateRandom([int seed]) sync* {\n final random = Random(seed);\n while (true) {\n yield Point(random.nextDouble(), random.nextDouble());\n }\n}\nclass Point {\n final double x, y;\n const Point(this.x, this.y);\n bool get isInsideUnitCircle => x * x + y * y <= 1;\n}\n
sample_code.dockerfile = FROM mono:3.12\n\nENV KRE_FEED https://www.myget.org/F/aspnetvnext/api/v2\nENV KRE_USER_HOME /opt/kre\n\nRUN apt-get -qq update && apt-get -qqy install unzip \n\nONBUILD RUN curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/kvminstall.sh | sh\nONBUILD RUN bash -c "source $KRE_USER_HOME/kvm/kvm.sh \\\n && kvm install latest -a default \\\n && kvm alias default | xargs -i ln -s $KRE_USER_HOME/packages/{} $KRE_USER_HOME/packages/default"\n\n# Install libuv for Kestrel from source code (binary is not in wheezy and one in jessie is still too old)\nRUN apt-get -qqy install \\\n autoconf \\\n automake \\\n build-essential \\\n libtool \nRUN LIBUV_VERSION=1.0.0-rc2 \\\n && curl -sSL https://github.com/joyent/libuv/archive/v${LIBUV_VERSION}.tar.gz | tar zxfv - -C /usr/local/src \\\n && cd /usr/local/src/libuv-$LIBUV_VERSION \\\n && sh autogen.sh && ./configure && make && make install \\\n && rm -rf /usr/local/src/libuv-$LIBUV_VERSION \\\n && ldconfig\n\nENV PATH $PATH:$KRE_USER_HOME/packages/default/bin\n\n# Extra things to test\nRUN echo "string at end"\nRUN echo must work 'some str' and some more\nRUN echo hi this is # not a comment\nRUN echo 'String with ${VAR} and another $one here'
sample_code.ecl = // First declare a dataset with one column containing a list of strings\n// Datasets can also be binary, CSV, XML or externally defined structures\n\nD := DATASET([{'ECL'},{'Declarative'},{'Data'},{'Centric'},{'Programming'},{'Language'}],{STRING Value;});\nSD := SORT(D,Value);\noutput(SD)
sample_code.elixir = # Elixir is a dynamic, functional language for building scalable\n# and maintainable applications. Learn more: https://elixir-lang.org\n\n"Elixir" |> String.graphemes() |> Enum.frequencies()\n#=> %{"E" => 1, "i" => 2, "l" => 1, "r" => 1, "x" => 1}\n\n\n### Scalability ###\n\n# All Elixir code runs inside lightweight threads of execution (called processes)\n# that are isolated and exchange information via messages:\n\ncurrent_process = self()\n\n# Spawn an Elixir process (not an operating system one!)\nspawn_link(fn ->\n send(current_process, {:msg, "hello world"})\nend)\n\n# Block until the message is received\nreceive do\n {:msg, contents} -> IO.puts(contents)\nend\n\n\n### Fault-tolerance ###\n\n# To cope with failures, Elixir provides supervisors which describe\n# how to restart parts of your system when things go awry, going back\n# to a known initial state that is guaranteed to work:\n\nchildren = [\n TCP.Pool,\n {TCP.Acceptor, port: 4040}\n]\n\nSupervisor.start_link(children, strategy: :one_for_one)\n\n\n### Functional programming ###\n\n# Functional programming promotes a coding style that helps\n# developers write code that is short, concise, and maintainable.\n# One prominent example is pattern matching:\n\n%User{name: name, age: age} = User.get("John Doe")\nname #=> "John Doe"\n\n# When mixed with guards, pattern matching allows us to elegantly\n# match and assert specific conditions for some code to execute:\n\ndef drive(%User{age: age}) when age >= 16 do\n # Code that drives a car\nend\n\ndrive(User.get("John Doe"))\n#=> Fails if the user is under 16\n\n\n### Extensibility and DSLs ###\n\n# Elixir has been designed to be extensible, letting developers\n# naturally extend the language to particular domains,\n# in order to increase their productivity.\n\ndefmodule MathTest do\n use ExUnit.Case, async: true\n\n test "can add two numbers" do\n assert 1 + 1 == 2\n end\nend\n\n\n### Erlang compatible ###\n\n# An Elixir programmer can invoke any Erlang function with no runtime cost:\n\n:crypto.hash(:md5, "Using crypto from Erlang OTP")\n#=> <<192, 223, 75, 115, ...>>\n
sample_code.flow9 = import material/material;\n\nexport {\n\u0009demoMakeHelloWorld(onClose : () -> void) -> Material;\n}\n\ndemoMakeHelloWorld(onClose : () -> void) -> Material {\n\u0009MCenter(\n\u0009\u0009MLines2(\n\u0009\u0009\u0009MText("Hello, world!", []),\n\u0009\u0009\u0009MTextButton("CLOSE", onClose, [], [])\n\u0009\u0009)\n\u0009);\n}\n
sample_code.freemarker2 = <#ftl stripText=false>\n\n<#-- Free marker demo -->\n\n<#comment>\nThis demonstrates the FreeMarker language. The default theme is not very\ncolorful and displays many different token types in the same color, but keep in\nmind that you can define your own theme (or extend an existing one).\n\nDo\n\nRight click -> Command Palette -> > Developer: Inspect Tokens\n\nto see the token name to use with the custom theme.\n\nNote that free marker actually defines 6 similar but different syntax modes:\n\n- 3 tag syntax modes: Angle (<#if>), Bracket ([#if]), and Auto.\n- 2 interpolation modes: Dollar (${...}) and Bracket ([=...])\n\nIn auto mode, the first tag determines the tag syntax. You can use the language\nIDs "freemarker.tag-bracket.interpolation-dollar" etc. to force a specific mode.\n\nThe default FreeMarker mode is Angle/Dollar.\n</#comment>\n\n<#macro greet name>\n <font size="+2">Hello PrimeFaces Extensions Showcase!</font>\n</#macro>\n\n<#macro border>\n <table border=4 cellspacing=0 cellpadding=4><tr><td>\n <#nested>\n </tr></td></table>\n</#macro>\n\n<#function avg x y>\n <#return (x + y) / 2>\n</#function>\n\n<#assign user = "Juila Smith">\n<#assign animals = [{"name": "Tanuki", "price": 200}, {"name": "Phoenix", "price": 1111}]>\n\n<html>\n<head>\n <title>Welcome!</title>\n</head>\n<body>\n <#-- Greet the user with his/her name -->\n <h1>\n \u0009<@greet user />\n </h1>\n\n <p>We have these animals:\n\n <ul>\n <#list animals as animal>\n <li>${animal.name} for ${animal.price} Euros\n </#list>\n </ul>\n\n <@border>The bordered text</@border>\n\n The average of 35 and 49 is ${avg(35, 49)}.\n\n</body>\n</html>\n
sample_code.freemarker2.tag-angle.interpolation-bracket = <#ftl stripText=false>\n\n<#-- Free marker demo -->\n\n<#comment>\nThis demonstrates the FreeMarker language. The default theme is not very\ncolorful and displays many different token types in the same color, but keep in\nmind that you can define your own theme (or extend an existing one).\n\nDo\n\nRight click -> Command Palette -> > Developer: Inspect Tokens\n\nto see the token name to use with the custom theme.\n\nNote that free marker actually defines 6 similar but different syntax modes:\n\n- 3 tag syntax modes: Angle (<#if>), Bracket ([#if]), and Auto.\n- 2 interpolation modes: Dollar (${...}) and Bracket ([=...])\n\nIn auto mode, the first tag determines the tag syntax. You can use the language\nIDs "freemarker.tag-bracket.interpolation-dollar" etc. to force a specific mode.\n\nThe default FreeMarker mode is Angle/Dollar.\n</#comment>\n\n<#macro greet name>\n <font size="+2">Hello [=name]!</font>\n</#macro>\n\n<#macro border>\n <table border=4 cellspacing=0 cellpadding=4><tr><td>\n <#nested>\n </tr></td></table>\n</#macro>\n\n<#function avg x y>\n <#return (x + y) / 2>\n</#function>\n\n<#assign user = "Juila Smith">\n<#assign animals = [{"name": "Tanuki", "price": 200}, {"name": "Phoenix", "price": 1111}]>\n\n<html>\n<head>\n <title>Welcome!</title>\n</head>\n<body>\n <#-- Greet the user with his/her name -->\n <h1>\n \u0009<@greet user />\n </h1>\n\n <p>We have these animals:\n\n <ul>\n <#list animals as animal>\n <li>[=animal.name] for [=animal.price] Euros\n </#list>\n </ul>\n\n <@border>The bordered text</@border>\n\n The average of 35 and 49 is [=avg(35, 49)].\n\n</body>\n</html>\n
sample_code.freemarker2.tag-angle.interpolation-dollar = <#ftl stripText=false>\n\n<#-- Free marker demo -->\n\n<#comment>\nThis demonstrates the FreeMarker language. The default theme is not very\ncolorful and displays many different token types in the same color, but keep in\nmind that you can define your own theme (or extend an existing one).\n\nDo\n\nRight click -> Command Palette -> > Developer: Inspect Tokens\n\nto see the token name to use with the custom theme.\n\nNote that free marker actually defines 6 similar but different syntax modes:\n\n- 3 tag syntax modes: Angle (<#if>), Bracket ([#if]), and Auto.\n- 2 interpolation modes: Dollar (${...}) and Bracket ([=...])\n\nIn auto mode, the first tag determines the tag syntax. You can use the language\nIDs "freemarker.tag-bracket.interpolation-dollar" etc. to force a specific mode.\n\nThe default FreeMarker mode is Angle/Dollar.\n</#comment>\n\n<#macro greet name>\n <font size="+2">Hello PrimeFaces Extensions Showcase!</font>\n</#macro>\n\n<#macro border>\n <table border=4 cellspacing=0 cellpadding=4><tr><td>\n <#nested>\n </tr></td></table>\n</#macro>\n\n<#function avg x y>\n <#return (x + y) / 2>\n</#function>\n\n<#assign user = "Juila Smith">\n<#assign animals = [{"name": "Tanuki", "price": 200}, {"name": "Phoenix", "price": 1111}]>\n\n<html>\n<head>\n <title>Welcome!</title>\n</head>\n<body>\n <#-- Greet the user with his/her name -->\n <h1>\n \u0009<@greet user />\n </h1>\n\n <p>We have these animals:\n\n <ul>\n <#list animals as animal>\n <li>${animal.name} for ${animal.price} Euros\n </#list>\n </ul>\n\n <@border>The bordered text</@border>\n\n The average of 35 and 49 is ${avg(35, 49)}.\n\n</body>\n</html>\n
sample_code.freemarker2.tag-auto.interpolation-bracket = Auto mode detect the tag syntax mode automatically.\nTry exchanging the order of the next two lines and see what happens!\n\n[#ftl stripText=false]\n<#ftl stripText=false>\n\n<#-- Free marker demo -->\n\n<#comment>\nThis demonstrates the FreeMarker language. The default theme is not very\ncolorful and displays many different token types in the same color, but keep in\nmind that you can define your own theme (or extend an existing one).\n\nDo\n\nRight click -> Command Palette -> > Developer: Inspect Tokens\n\nto see the token name to use with the custom theme.\n\nNote that free marker actually defines 6 similar but different syntax modes:\n\n- 3 tag syntax modes: Angle (<#if>), Bracket ([#if]), and Auto.\n- 2 interpolation modes: Dollar (${...}) and Bracket ([=...])\n\nIn auto mode, the first tag determines the tag syntax. You can use the language\nIDs "freemarker.tag-bracket.interpolation-dollar" etc. to force a specific mode.\n\nThe default FreeMarker mode is Angle/Dollar.\n</#comment>\n\n<#macro greet name>\n <font size="+2">Hello [=name]!</font>\n</#macro>\n\n<#macro border>\n <table border=4 cellspacing=0 cellpadding=4><tr><td>\n <#nested>\n </tr></td></table>\n</#macro>\n\n<#function avg x y>\n <#return (x + y) / 2>\n</#function>\n\n<#assign user = "Juila Smith">\n<#assign animals = [{"name": "Tanuki", "price": 200}, {"name": "Phoenix", "price": 1111}]>\n\n<html>\n<head>\n <title>Welcome!</title>\n</head>\n<body>\n <#-- Greet the user with his/her name -->\n <h1>\n \u0009<@greet user />\n </h1>\n\n <p>We have these animals:\n\n <ul>\n <#list animals as animal>\n <li>[=animal.name] for [=animal.price] Euros\n </#list>\n </ul>\n\n <@border>The bordered text</@border>\n\n The average of 35 and 49 is [=avg(35, 49)].\n\n</body>\n</html>\n
sample_code.freemarker2.tag-auto.interpolation-dollar = Auto mode detect the tag syntax mode automatically.\nTry exchanging the order of the next two lines and see what happens!\n\n<#ftl stripText=false>\n[#ftl stripText=false]\n\n<#-- Free marker demo -->\n\n<#comment>\nThis demonstrates the FreeMarker language. The default theme is not very\ncolorful and displays many different token types in the same color, but keep in\nmind that you can define your own theme (or extend an existing one).\n\nDo\n\nRight click -> Command Palette -> > Developer: Inspect Tokens\n\nto see the token name to use with the custom theme.\n\nNote that free marker actually defines 6 similar but different syntax modes:\n\n- 3 tag syntax modes: Angle (<#if>), Bracket ([#if]), and Auto.\n- 2 interpolation modes: Dollar (${...}) and Bracket ([=...])\n\nIn auto mode, the first tag determines the tag syntax. You can use the language\nIDs "freemarker.tag-bracket.interpolation-dollar" etc. to force a specific mode.\n\nThe default FreeMarker mode is Angle/Dollar.\n</#comment>\n\n<#macro greet name>\n <font size="+2">Hello PrimeFaces Extensions Showcase!</font>\n</#macro>\n\n<#macro border>\n <table border=4 cellspacing=0 cellpadding=4><tr><td>\n <#nested>\n </tr></td></table>\n</#macro>\n\n<#function avg x y>\n <#return (x + y) / 2>\n</#function>\n\n<#assign user = "Juila Smith">\n<#assign animals = [{"name": "Tanuki", "price": 200}, {"name": "Phoenix", "price": 1111}]>\n\n<html>\n<head>\n <title>Welcome!</title>\n</head>\n<body>\n <#-- Greet the user with his/her name -->\n <h1>\n \u0009<@greet user />\n </h1>\n\n <p>We have these animals:\n\n <ul>\n <#list animals as animal>\n <li>${animal.name} for ${animal.price} Euros\n </#list>\n </ul>\n\n <@border>The bordered text</@border>\n\n The average of 35 and 49 is ${avg(35, 49)}.\n\n</body>\n</html>\n
sample_code.freemarker2.tag-bracket.interpolation-bracket = [#ftl stripText=false]\n\n[#-- Free marker demo --]\n\n[#comment]\nThis demonstrates the FreeMarker language. The default theme is not very\ncolorful and displays many different token types in the same color, but keep in\nmind that you can define your own theme (or extend an existing one).\n\nDo\n\nRight click -> Command Palette -> > Developer: Inspect Tokens\n\nto see the token name to use with the custom theme.\n\nNote that free marker actually defines 6 similar but different syntax modes:\n\n- 3 tag syntax modes: Angle (<#if>), Bracket ([#if]), and Auto.\n- 2 interpolation modes: Dollar (${...}) and Bracket ([=...])\n\nIn auto mode, the first tag determines the tag syntax. You can use the language\nIDs "freemarker.tag-bracket.interpolation-dollar" etc. to force a specific mode.\n\nThe default FreeMarker mode is Angle/Dollar.\n[/#comment]\n\n[#macro greet name]\n <font size="+2">Hello [=name]!</font>\n[/#macro[\n\n[#macro border]\n <table border=4 cellspacing=0 cellpadding=4><tr><td>\n [#nested]\n </tr></td></table>\n[/#macro]\n\n[#function avg x y]\n [#return (x + y) / 2]\n[/#function]\n\n[#assign user = "Juila Smith"]\n[#assign animals = [{"name": "Tanuki", "price": 200}, {"name": "Phoenix", "price": 1111}]]\n\n<html>\n<head>\n <title>Welcome!</title>\n</head>\n<body>\n [#-- Greet the user with his/her name --]\n <h1>\n \u0009<@greet user />\n </h1>\n\n <p>We have these animals:\n\n <ul>\n [#list animals as animal]\n <li>[=animal.name] for [=animal.price] Euros\n [/#list][\n </ul>\n\n <@border>The bordered text</@border>\n\n The average of 35 and 49 is [=avg(35, 49]}.\n\n</body>\n</html>\n
sample_code.freemarker2.tag-bracket.interpolation-dollar = [#ftl stripText=false]\n\n[#-- Free marker demo --]\n\n[#comment]\nThis demonstrates the FreeMarker language. The default theme is not very\ncolorful and displays many different token types in the same color, but keep in\nmind that you can define your own theme (or extend an existing one).\n\nDo\n\nRight click -> Command Palette -> > Developer: Inspect Tokens\n\nto see the token name to use with the custom theme.\n\nNote that free marker actually defines 6 similar but different syntax modes:\n\n- 3 tag syntax modes: Angle (<#if>), Bracket ([#if]), and Auto.\n- 2 interpolation modes: Dollar (${...}) and Bracket ([=...])\n\nIn auto mode, the first tag determines the tag syntax. You can use the language\nIDs "freemarker.tag-bracket.interpolation-dollar" etc. to force a specific mode.\n\nThe default FreeMarker mode is Angle/Dollar.\n[/#comment]\n\n[#macro greet name]\n <font size="+2">Hello PrimeFaces Extensions Showcase!</font>\n[/#macro[\n\n[#macro border]\n <table border=4 cellspacing=0 cellpadding=4><tr><td>\n [#nested]\n </tr></td></table>\n[/#macro]\n\n[#function avg x y]\n [#return (x + y) / 2]\n[/#function]\n\n[#assign user = "Juila Smith"]\n[#assign animals = [{"name": "Tanuki", "price": 200}, {"name": "Phoenix", "price": 1111}]]\n\n<html>\n<head>\n <title>Welcome!</title>\n</head>\n<body>\n [#-- Greet the user with his/her name --]\n <h1>\n \u0009<@greet user />\n </h1>\n\n <p>We have these animals:\n\n <ul>\n [#list animals as animal]\n <li>${animal.name} for ${animal.price} Euros\n [/#list][\n </ul>\n\n <@border>The bordered text</@border>\n\n The average of 35 and 49 is ${avg(35, 49)}.\n\n</body>\n</html>\n
sample_code.fsharp = (* Sample F# application *)\n[<EntryPoint>]\nlet main argv = \n printfn "%A" argv\n System.Console.WriteLine("Hello from F#")\n 0 // return an integer exit code\n\n//-------------------------------------------------------- \n
sample_code.go = // We often need our programs to perform operations on\n// collections of data, like selecting all items that\n// satisfy a given predicate or mapping all items to a new\n// collection with a custom function.\n\n// In some languages it's idiomatic to use [generic](http://en.wikipedia.org/wiki/Generic_programming)\n// data structures and algorithms. Go does not support\n// generics; in Go it's common to provide collection\n// functions if and when they are specifically needed for\n// your program and data types.\n\n// Here are some example collection functions for slices\n// of `strings`. You can use these examples to build your\n// own functions. Note that in some cases it may be\n// clearest to just inline the collection-manipulating\n// code directly, instead of creating and calling a\n// helper function.\n\npackage main\n\nimport "strings"\nimport "fmt"\n\n// Returns the first index of the target string `t`, or\n// -1 if no match is found.\nfunc Index(vs []string, t string) int {\n for i, v := range vs {\n if v == t {\n return i\n }\n }\n return -1\n}\n\n// Returns `true` if the target string t is in the\n// slice.\nfunc Include(vs []string, t string) bool {\n return Index(vs, t) >= 0\n}\n\n// Returns `true` if one of the strings in the slice\n// satisfies the predicate `f`.\nfunc Any(vs []string, f func(string) bool) bool {\n for _, v := range vs {\n if f(v) {\n return true\n }\n }\n return false\n}\n\n// Returns `true` if all of the strings in the slice\n// satisfy the predicate `f`.\nfunc All(vs []string, f func(string) bool) bool {\n for _, v := range vs {\n if !f(v) {\n return false\n }\n }\n return true\n}\n\n// Returns a new slice containing all strings in the\n// slice that satisfy the predicate `f`.\nfunc Filter(vs []string, f func(string) bool) []string {\n vsf := make([]string, 0)\n for _, v := range vs {\n if f(v) {\n vsf = append(vsf, v)\n }\n }\n return vsf\n}\n\n// Returns a new slice containing the results of applying\n// the function `f` to each string in the original slice.\nfunc Map(vs []string, f func(string) string) []string {\n vsm := make([]string, len(vs))\n for i, v := range vs {\n vsm[i] = f(v)\n }\n return vsm\n}\n\nfunc main() {\n\n // Here we try out our various collection functions.\n var strs = []string{"peach", "apple", "pear", "plum"}\n\n fmt.Println(Index(strs, "pear"))\n\n fmt.Println(Include(strs, "grape"))\n\n fmt.Println(Any(strs, func(v string) bool {\n return strings.HasPrefix(v, "p")\n }))\n\n fmt.Println(All(strs, func(v string) bool {\n return strings.HasPrefix(v, "p")\n }))\n\n fmt.Println(Filter(strs, func(v string) bool {\n return strings.Contains(v, "e")\n }))\n\n // The above examples all used anonymous functions,\n // but you can also use named functions of the correct\n // type.\n fmt.Println(Map(strs, strings.ToUpper))\n\n}\n
sample_code.graphql = # GraphQL Schema Definition Language\n\n"""\nColor value\n"""\nscalar Color\n\n"""\nNode interface\n\n- allows (re)fetch arbitrary entity only by ID\n- allows client side cache normalization\n\nSee [Relay Global Object Identification Specification](https://facebook.github.io/relay/graphql/objectidentification.htm)\n"""\ninterface Node {\n """\n Globally unique identifier,\n typically `${__typename}:${dbId}`\n may be encoded in *base64*\n """\n id: ID!\n}\n\n"""\nA character in the Star Wars Trilogy\n"""\ninterface Character {\n """\n The id of the character.\n """\n id: ID!\n\n """\n The name of the character.\n """\n name: String\n\n """\n The friends of the character, or an empty list if they have none.\n """\n friends: [Character]\n\n """\n Which movies they appear in\n """\n appearsIn: [Episode]\n\n """\n All secrets about their past\n """\n secretBackstory: String\n}\n\n"""\nA mechanical creature in the Star Wars universe.\n"""\ntype Droid implements Character {\n """\n The id of the droid.\n """\n id: ID!\n\n """\n The name of the droid.\n """\n name: String\n\n """\n The friends of the droid, or an empty list if they have none.\n """\n friends: [Character]\n\n """\n Which movies they appear in.\n """\n appearsIn: [Episode]\n\n """\n Construction date and the name of the designer.\n """\n secretBackstory: String\n\n """\n The primary function of the droid.\n """\n primaryFunction: String\n\n """\n Chase color of the droid.\n """\n color: Color\n}\n\n# One of the films in the Star Wars Trilogy\nenum Episode {\n """\n Released in 1977.\n """\n NEWHOPE\n\n """\n Released in 1980.\n """\n EMPIRE\n\n """\n Released in 1983.\n """\n JEDI\n}\n\n"""\nA humanoid creature in the Star Wars universe.\n"""\ntype Human implements Character {\n """\n The id of the human.\n """\n id: ID!\n\n """\n The name of the human.\n """\n name: String\n\n """\n The friends of the human, or an empty list if they have none.\n """\n friends: [Character]\n\n """\n Which movies they appear in.\n """\n appearsIn: [Episode]\n\n """\n The home planet of the human, or null if unknown.\n """\n homePlanet: String\n\n """\n Where are they from and how they came to be who they are.\n """\n secretBackstory: String\n}\n\nenum LengthUnit {\n METER\n FEET\n}\n\ntype Starship {\n id: ID!\n name: String!\n length(unit: LengthUnit = METER): Float\n}\n\nunion SearchResult = Human | Droid | Starship\n\ninput SearchInput {\n name: String\n episode: Episode\n}\n\n"""\nRoot Query\n"""\ntype Query {\n """\n Return the hero by episode.\n """\n hero(\n """\n If omitted, returns the hero of the whole saga. If provided, returns the hero of that particular episode.\n """\n episode: Episode\n ): Character\n\n """\n Return the Human by ID.\n """\n human(\n """\n id of the human\n """\n id: ID!\n ): Human\n\n """\n Return the Droid by ID.\n """\n droid(\n """\n id of the droid\n """\n id: ID!\n ): Droid\n\n """\n Search everything by name\n\n __NOTE__: You should use Relay pagination\n """\n search(search: SearchInput!): [SearchResult]\n @deprecated(reason: "`search` will be replaced.")\n}\n\n"""\nRoot Mutation\n"""\ntype Mutation {\n """\n Save the favorite episode.\n """\n favorite(\n """\n Favorite episode.\n """\n episode: Episode!\n ): Episode\n}\n\n"""\nSubscriptions \u2014 live events\n"""\ntype Subscription {\n """\n Message\n """\n message: String\n}\n\nextend type Query {\n """\n Dummy query for highlighting test\n """\n dummy(\n int: Int = 123\n float: Float = 123.456\n str: String = "Hello World!"\n boolDefaultTrue: Boolean = true\n boolDefaultFalse: Boolean = false\n id: ID\n search: SearchInput = null\n ): Boolean\n}\n\nschema {\n query: Query\n mutation: Mutation\n subscription: Subscription\n}\n\n# GraphQL Query Language\n\nquery dummyQuery($int: Int) {\n dummy(int: $int)\n}\n\nmutation favoriteEpisode($episode: Episode) {\n favorite(episode: $episode)\n}\n
sample_code.handlebars = \n<div class="entry">\n\u0009<h1>{{title}}</h1>\n\u0009{{#if author}}\n\u0009<h2>{{author.firstName}} {{author.lastName}}</h2>\n\u0009{{else}}\n\u0009<h2>Unknown Author</h2>\n\u0009{{/if}}\n\u0009{{contentBody}}\n</div>\n\n{{#unless license}}\n <h3 class="warning">WARNING: This entry does not have a license!</h3>\n{{/unless}}\n\n<div class="footnotes">\n\u0009<ul>\n\u0009\u0009{{#each footnotes}}\n\u0009\u0009<li>{{this}}</li>\n\u0009\u0009{{/each}}\n\u0009</ul>\n</div>\n\n<h1>Comments</h1>\n\n<div id="comments">\n\u0009{{#each comments}}\n\u0009<h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2>\n\u0009<div>{{body}}</div>\n\u0009{{/each}}\n</div>\n
sample_code.hcl = terraform {\n required_providers {\n aws = {\n source = "hashicorp/aws"\n version = "~> 1.0.4"\n }\n }\n}\n\nvariable "aws_region" {}\n\nvariable "base_cidr_block" {\n description = "A /16 CIDR range definition, such as 10.1.0.0/16, that the VPC will use"\n default = "10.1.0.0/16"\n}\n\nvariable "availability_zones" {\n description = "A list of availability zones in which to create subnets"\n type = list(string)\n}\n\nprovider "aws" {\n region = var.aws_region\n}\n\nresource "aws_vpc" "main" {\n # Referencing the base_cidr_block variable allows the network address\n # to be changed without modifying the configuration.\n cidr_block = var.base_cidr_block\n}\n\nresource "aws_subnet" "az" {\n # Create one subnet for each given availability zone.\n count = length(var.availability_zones)\n\n # For each subnet, use one of the specified availability zones.\n availability_zone = var.availability_zones[count.index]\n\n # By referencing the aws_vpc.main object, Terraform knows that the subnet\n # must be created only after the VPC is created.\n vpc_id = aws_vpc.main.id\n\n # Built-in functions and operators can be used for simple transformations of\n # values, such as computing a subnet address. Here we create a /20 prefix for\n # each subnet, using consecutive addresses for each availability zone,\n # such as 10.1.16.0/20 .\n cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 4, count.index+1)\n}\n
sample_code.html = <!DOCTYPE HTML>\n<!--Example of comments in HTML-->\n<html>\n<head>\n\u0009<!--This is the head section-->\n\u0009<title>HTML Sample</title>\n\u0009<meta charset="utf-8">\n\n\u0009<!--This is the style tag to set style on elements-->\n\u0009<style type="text/css">\n\u0009\u0009h1\n\u0009\u0009{\n\u0009\u0009\u0009font-family: Tahoma;\n\u0009\u0009\u0009font-size: 40px;\n\u0009\u0009\u0009font-weight: normal;\n\u0009\u0009\u0009margin: 50px;\n\u0009\u0009\u0009color: #a0a0a0;\n\u0009\u0009}\n\n\u0009\u0009h2\n\u0009\u0009{\n\u0009\u0009\u0009font-family: Tahoma;\n\u0009\u0009\u0009font-size: 30px;\n\u0009\u0009\u0009font-weight: normal;\n\u0009\u0009\u0009margin: 50px;\n\u0009\u0009\u0009color: #fff;\n\u0009\u0009}\n\n\u0009\u0009p\n\u0009\u0009{\n\u0009\u0009\u0009font-family: Tahoma;\n\u0009\u0009\u0009font-size: 17px;\n\u0009\u0009\u0009font-weight: normal;\n\u0009\u0009\u0009margin: 0px 200px;\n\u0009\u0009\u0009color: #fff;\n\u0009\u0009}\n\n\u0009\u0009div.Center\n\u0009\u0009{\n\u0009\u0009\u0009text-align: center;\n\u0009\u0009}\n\n\u0009\u0009div.Blue\n\u0009\u0009{\n\u0009\u0009\u0009padding: 50px;\n\u0009\u0009\u0009background-color: #7bd2ff;\n\u0009\u0009}\n\n\u0009\u0009button.Gray\n\u0009\u0009{\n\u0009\u0009\u0009font-family: Tahoma;\n\u0009\u0009\u0009font-size: 17px;\n\u0009\u0009\u0009font-weight: normal;\n\u0009\u0009\u0009margin-top: 100px;\n\u0009\u0009\u0009padding: 10px 50px;\n\u0009\u0009\u0009background-color: #727272;\n\u0009\u0009\u0009color: #fff;\n\u0009\u0009\u0009outline: 0;\n \u0009\u0009\u0009border: none;\n \u0009\u0009\u0009cursor: pointer;\n\u0009\u0009}\n\n\u0009\u0009button.Gray:hover\n\u0009\u0009{\n\u0009\u0009\u0009background-color: #898888;\n\u0009\u0009}\n\n\u0009\u0009button.Gray:active\n\u0009\u0009{\n\u0009\u0009\u0009background-color: #636161;\n\u0009\u0009}\n\n\u0009</style>\n\n\u0009<!--This is the script tag-->\n\u0009<script type="text/javascript">\n\u0009\u0009function ButtonClick(){\n\u0009\u0009\u0009// Example of comments in JavaScript\n\u0009\u0009\u0009window.alert("I'm an alert sample!");\n\u0009\u0009}\n\u0009</script>\n</head>\n<body>\n\u0009<!--This is the body section-->\n\u0009<div class="Center">\n\u0009\u0009<h1>NAME OF SITE</h1>\n\u0009</div>\n\u0009<div class="Center Blue">\n\u0009\u0009\u0009<h2>I'm h2 Header! Edit me in <h2></h2>\n\u0009\u0009\u0009<p>\n\u0009\u0009\u0009\u0009I'm a paragraph! Edit me in <p>\n\u0009\u0009\u0009\u0009to add your own content and make changes to the style and font.\n\u0009\u0009\u0009\u0009It's easy! Just change the text between <p> ... </p> and change the style in <style>.\n\u0009\u0009\u0009\u0009You can make it as long as you wish. The browser will automatically wrap the lines to accommodate the\n\u0009\u0009\u0009\u0009size of the browser window.\n\u0009\u0009\u0009</p>\n\u0009\u0009\u0009<button class="Gray" onclick="ButtonClick()">Click Me!</button>\n\u0009</div>\n</body>\n</html>\n
sample_code.ini = # Example of a .gitconfig file\n\n[core]\n\u0009repositoryformatversion = 0\n\u0009filemode = false\n\u0009bare = false\n\u0009logallrefupdates = true\n\u0009symlinks = false\n\u0009ignorecase = true\n\u0009hideDotFiles = dotGitOnly\n\n# Defines the master branch\n[branch "master"]\n\u0009remote = origin\n\u0009merge = refs/heads/master\n
sample_code.java = package org.primefaces.extensions.component.monacoeditor;\n\nimport java.util.Locale;\nimport java.util.Map;\n\nimport jakarta.faces.component.behavior.ClientBehaviorHolder;\nimport jakarta.faces.component.html.HtmlInputTextarea;\nimport jakarta.faces.context.FacesContext;\n\nimport org.primefaces.component.api.PrimeClientBehaviorHolder;\nimport org.primefaces.component.api.Widget;\nimport org.primefaces.extensions.model.monacoeditor.EditorOptions;\nimport org.primefaces.extensions.model.monacoeditor.EditorStandaloneTheme;\nimport org.primefaces.util.LocaleUtils;\n\n/**\n * Base component for both the standalone and diff monaco code editor widget, in its framed and inline variants.\n *\n * @since 11.1.0\n */\n@SuppressWarnings("java:S110")\npublic abstract class MonacoEditorCommon<TEditorOpts> extends HtmlInputTextarea implements ClientBehaviorHolder, PrimeClientBehaviorHolder, Widget {\n\n public static final String COMPONENT_FAMILY = "org.primefaces.extensions.component";\n\n static final boolean DEFAULT_AUTO_RESIZE = false;\n static final String DEFAULT_BASENAME = "";\n static final String DEFAULT_DIRECTORY = "";\n static final boolean DEFAULT_DISABLED = false;\n static final String DEFAULT_EXTENSION = "";\n static final String DEFAULT_HEIGHT = "600px";\n static final String DEFAULT_LANGUAGE = "plaintext";\n static final boolean DEFAULT_READONLY = false;\n static final String DEFAULT_SCHEME = "inmemory";\n static final String DEFAULT_TABINDEX = null;\n static final String DEFAULT_WIDTH = "200px";\n\n private Locale appropriateLocale;\n private final Class<TEditorOpts> editorOptionsClass;\n\n protected MonacoEditorCommon(String rendererType, Class<TEditorOpts> editorOptionsClass) {\n this.editorOptionsClass = editorOptionsClass;\n setRendererType(rendererType);\n }\n\n public Locale calculateLocale() {\n if (appropriateLocale == null) {\n final FacesContext context = FacesContext.getCurrentInstance();\n appropriateLocale = LocaleUtils.resolveLocale(context, getLocale(), getClientId(context));\n }\n return appropriateLocale;\n }\n\n public final String getBasename() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.basename, DEFAULT_BASENAME);\n }\n\n @SuppressWarnings("unchecked")\n public final Map<String, EditorStandaloneTheme> getCustomThemes() {\n return (Map<String, EditorStandaloneTheme>) getStateHelper().eval(BaseEditorPropertyKeys.customThemes, null);\n }\n\n public final String getDirectory() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.directory, DEFAULT_DIRECTORY);\n }\n\n public final TEditorOpts getEditorOptions() {\n final TEditorOpts editorOptions = editorOptionsClass.cast(getStateHelper().eval(BaseEditorPropertyKeys.editorOptions, null));\n return editorOptions != null ? editorOptions : newEditorOptions();\n }\n\n public final String getExtension() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.extension, DEFAULT_EXTENSION);\n }\n\n @Override\n public final String getFamily() {\n return COMPONENT_FAMILY;\n }\n\n public final String getHeight() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.height, DEFAULT_HEIGHT);\n }\n\n public final String getOninitialized() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.oninitialized, null);\n }\n\n public final String getOnpaste() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.onpaste, null);\n }\n\n public final String getScheme() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.scheme, DEFAULT_SCHEME);\n }\n\n public Object getLocale() {\n return getStateHelper().eval(BaseEditorPropertyKeys.locale, null);\n }\n\n public final String getLocaleUrl() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.localeUrl, null);\n }\n\n public final String getWidgetVar() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.widgetVar, null);\n }\n\n public final String getWidth() {\n return (String) getStateHelper().eval(BaseEditorPropertyKeys.width, DEFAULT_WIDTH);\n }\n\n public final boolean isAutoResize() {\n return (Boolean) getStateHelper().eval(BaseEditorPropertyKeys.autoResize, DEFAULT_AUTO_RESIZE);\n }\n\n public final void setAutoResize(boolean autoResize) {\n getStateHelper().put(BaseEditorPropertyKeys.autoResize, autoResize);\n }\n\n public final void setBasename(String basename) {\n getStateHelper().put(BaseEditorPropertyKeys.basename, basename);\n }\n\n public final void setCustomThemes(Map<String, EditorStandaloneTheme> customThemes) {\n getStateHelper().put(BaseEditorPropertyKeys.customThemes, customThemes);\n }\n\n public final void setDirectory(String directory) {\n getStateHelper().put(BaseEditorPropertyKeys.directory, directory);\n }\n\n public final void setEditorOptions(EditorOptions editorOptions) {\n getStateHelper().put(BaseEditorPropertyKeys.editorOptions, editorOptions);\n }\n\n public final void setExtension(String extension) {\n getStateHelper().put(BaseEditorPropertyKeys.extension, extension);\n }\n\n public final void setHeight(String height) {\n getStateHelper().put(BaseEditorPropertyKeys.height, height);\n }\n\n public final void setOninitialized(String oninitialized) {\n getStateHelper().put(BaseEditorPropertyKeys.oninitialized, oninitialized);\n }\n\n public final void setOnpaste(String onpaste) {\n getStateHelper().put(BaseEditorPropertyKeys.onpaste, onpaste);\n }\n\n public final void setScheme(String scheme) {\n getStateHelper().put(BaseEditorPropertyKeys.scheme, scheme);\n }\n\n public final void setLocale(Object locale) {\n getStateHelper().put(BaseEditorPropertyKeys.locale, locale);\n }\n\n public final void setLocaleUrl(String localeUrl) {\n getStateHelper().put(BaseEditorPropertyKeys.localeUrl, localeUrl);\n }\n\n public final void setWidgetVar(String widgetVar) {\n getStateHelper().put(BaseEditorPropertyKeys.widgetVar, widgetVar);\n }\n\n public final void setWidth(String width) {\n getStateHelper().put(BaseEditorPropertyKeys.width, width);\n }\n\n @Override\n public Object saveState(FacesContext context) {\n // reset component for MyFaces view pooling\n appropriateLocale = null;\n\n return super.saveState(context);\n }\n\n private TEditorOpts newEditorOptions() {\n try {\n return editorOptionsClass.getConstructor().newInstance();\n }\n catch (final Exception e) {\n return null;\n }\n }\n}\n
sample_code.javascript = // @ts-check\n\n/**\n * @template T\n * @param {T | null | undefined} value\n * @returns {value is T}\n */\nfunction isNotNullOrUndefined(value) {\n return value !== undefined && value !== null;\n}\n\n/**\n * A simple queue to which promise factories can be added. It makes sure the promises\n * are created / started in the order as they were added.\n * @implements IPromiseQueue\n */\nclass PromiseQueueImpl {\n constructor() {\n /** @type {QueueItem[]} */\n this._queue = [];\n }\n \n /**\n * @template T\n * @param {PromiseFactory<T>} promiseFactory\n * @returns {Promise<T>}\n */\n add(promiseFactory) {\n return this.addAll(promiseFactory)[0];\n }\n \n /**\n * @template T\n * @param {PromiseFactory<T>[]} promiseFactory\n * @returns {Promise<T>[]}\n */\n addAll(...promiseFactory) {\n return promiseFactory\n .filter(isNotNullOrUndefined)\n .map(factory => new Promise((resolve, reject) => {\n this._addQueueItem(factory, resolve, reject);\n }));\n }\n\n /**\n *\n * @param {PromiseFactory<unknown>} factory\n * @param {PromiseCallback} resolve\n * @param {PromiseCallback} reject\n */\n _addQueueItem(factory, resolve, reject) {\n const wasEmpty = this._queue.length === 0;\n this._queue.push({\n factory: factory,\n resolve: resolve,\n reject: reject,\n });\n if (wasEmpty) {\n this._startQueue();\n }\n }\n\n _startQueue() {\n this._processQueue(this._peek());\n }\n\n _onPromiseDone() {\n this._poll();\n this._processQueue(this._peek());\n }\n\n /**\n * @param {QueueItem | undefined} queueItem\n */\n _processQueue(queueItem) {\n if (queueItem) {\n const promise = PromiseQueueImpl._makePromise(queueItem.factory);\n promise\n .then(queueItem.resolve)\n .catch(queueItem.reject)\n .then(() => this._onPromiseDone());\n }\n }\n\n /**\n * @returns {QueueItem | undefined}\n */\n _poll() {\n return this._queue.shift();\n }\n\n /**\n * @returns {QueueItem | undefined}\n */\n _peek() {\n return this._queue[0];\n }\n\n /**\n * @param {PromiseFactory<unknown>} promiseFactory\n * @returns {Promise<unknown>}\n */\n static _makePromise(promiseFactory) {\n try {\n const promise = promiseFactory();\n if (promise !== undefined) {\n return promise;\n }\n }\n catch (e) {\n console.error("[MonacoEditor] Could not create promise", e);\n }\n return Promise.resolve();\n }\n}
sample_code.json = {\n\u0009"type": "team",\n\u0009"test": {\n\u0009\u0009"testPage": "tools/testing/run-tests.htm",\n\u0009\u0009"enabled": true\n\u0009},\n "search": {\n "excludeFolders": [\n\u0009\u0009\u0009".git",\n\u0009\u0009\u0009"node_modules",\n\u0009\u0009\u0009"tools/bin",\n\u0009\u0009\u0009"tools/counts",\n\u0009\u0009\u0009"tools/policheck",\n\u0009\u0009\u0009"tools/tfs_build_extensions",\n\u0009\u0009\u0009"tools/testing/jscoverage",\n\u0009\u0009\u0009"tools/testing/qunit",\n\u0009\u0009\u0009"tools/testing/chutzpah",\n\u0009\u0009\u0009"server.net"\n ]\n },\n\u0009"languages": {\n\u0009\u0009"vs.languages.typescript": {\n\u0009\u0009\u0009"validationSettings": [{\n\u0009\u0009\u0009\u0009"scope":"/",\n\u0009\u0009\u0009\u0009"noImplicitAny":true,\n\u0009\u0009\u0009\u0009"noLib":false,\n\u0009\u0009\u0009\u0009"extraLibs":[],\n\u0009\u0009\u0009\u0009"semanticValidation":true,\n\u0009\u0009\u0009\u0009"syntaxValidation":true,\n\u0009\u0009\u0009\u0009"codeGenTarget":"ES5",\n\u0009\u0009\u0009\u0009"moduleGenTarget":"",\n\u0009\u0009\u0009\u0009"lint": {\n "emptyBlocksWithoutComment": "warning",\n "curlyBracketsMustNotBeOmitted": "warning",\n "comparisonOperatorsNotStrict": "warning",\n "missingSemicolon": "warning",\n "unknownTypeOfResults": "warning",\n "semicolonsInsteadOfBlocks": "warning",\n "functionsInsideLoops": "warning",\n "functionsWithoutReturnType": "warning",\n "tripleSlashReferenceAlike": "warning",\n "unusedImports": "warning",\n "unusedVariables": "warning",\n "unusedFunctions": "warning",\n "unusedMembers": "warning"\n }\n\u0009\u0009\u0009}, \n\u0009\u0009\u0009{\n\u0009\u0009\u0009\u0009"scope":"/client",\n\u0009\u0009\u0009\u0009"baseUrl":"/client",\n\u0009\u0009\u0009\u0009"moduleGenTarget":"amd"\n\u0009\u0009\u0009},\n\u0009\u0009\u0009{\n\u0009\u0009\u0009\u0009"scope":"/server",\n\u0009\u0009\u0009\u0009"moduleGenTarget":"commonjs"\n\u0009\u0009\u0009},\n\u0009\u0009\u0009{\n\u0009\u0009\u0009\u0009"scope":"/build",\n\u0009\u0009\u0009\u0009"moduleGenTarget":"commonjs"\n\u0009\u0009\u0009},\n\u0009\u0009\u0009{\n\u0009\u0009\u0009\u0009"scope":"/node_modules/nake",\n\u0009\u0009\u0009\u0009"moduleGenTarget":"commonjs"\n\u0009\u0009\u0009}],\n\u0009\u0009\u0009"allowMultipleWorkers": true\n\u0009\u0009}\n\u0009}\n}
sample_code.julia = # good style\nfunction fixedpointmap(f; iv, tolerance=1E-7, maxiter=1000)\n # setup the algorithm\n x_old = iv\n normdiff = Inf\n iter = 1\n while normdiff > tolerance && iter <= maxiter\n x_new = f(x_old) # use the passed in map\n normdiff = norm(x_new - x_old)\n x_old = x_new\n iter = iter + 1\n end\n return (value = x_old, normdiff=normdiff, iter=iter) # A named tuple\nend\n\n# define a map and parameters\np = 1.0\n\u03B2 = 0.9\nf(v) = p + \u03B2 * v # note that p and \u03B2 are used in the function!\n\nsol = fixedpointmap(f, iv=0.8, tolerance=1.0E-8) # don't need to pass\nprintln("Fixed point = $(sol.value), and |f(x) - x| = $(sol.normdiff) in $(sol.iter)"*\n " iterations")\n
sample_code.kotlin = const val POINTS_X_PASS: Int = 15\nval EZPassAccounts: MutableMap<Int, Int> = mutableMapOf(1 to 100, 2 to 100, 3 to 100)\nval EZPassReport: Map<Int, Int> = EZPassAccounts\n\n// update points credit\nfun updatePointsCredit(accountId: Int) {\n if (EZPassAccounts.containsKey(accountId)) {\n println("Updating $accountId...")\n EZPassAccounts[accountId] = EZPassAccounts.getValue(accountId) + POINTS_X_PASS\n } else {\n println("Error: Trying to update a non-existing account (id: $accountId)")\n }\n}\n\nfun accountsReport() {\n println("EZ-Pass report:")\n EZPassReport.forEach{\n k, v -> println("ID $k: credit $v")\n }\n}\n\nfun main() {\n accountsReport()\n updatePointsCredit(1)\n updatePointsCredit(1)\n updatePointsCredit(5)\n accountsReport()\n}
sample_code.less = @base: #f938ab;\n\n.box-shadow(@style, @c) when (iscolor(@c)) {\n\u0009border-radius: @style @c;\n}\n\n.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {\n\u0009.box-shadow(@style, rgba(0, 0, 0, @alpha));\n}\n\n.box { \n\u0009color: saturate(@base, 5%);\n\u0009border-color: lighten(@base, 30%);\n\u0009\n\u0009div {\n\u0009\u0009.box-shadow((0 0 5px), 30%);\n\u0009}\n}\n\n#header {\n\u0009h1 {\n\u0009\u0009font-size: 26px;\n\u0009\u0009font-weight: bold;\n\u0009}\n\u0009\n\u0009p { font-size: 12px;\n\u0009\u0009a { text-decoration: none;\n\u0009\u0009\u0009&:hover { border-width: 1px }\n\u0009\u0009}\n\u0009}\n}\n\n@the-border: 1px;\n@base-color: #111;\n@red: #842210;\n\n#header {\n\u0009color: (@base-color * 3);\n\u0009border-left: @the-border;\n\u0009border-right: (@the-border * 2);\n}\n\n#footer {\n\u0009color: (@base-color + #003300);\n\u0009border-color: desaturate(@red, 10%);\n}\n
sample_code.lexon = LEX Retainer Agreement.\nLEXON: 0.2.12\nCOMMENT: A boilerplate retainer agreement for legal representation.\n\u201CAttorney\u201D is a person.\n\u201CClient\u201D is a person.\n\u201CRetainer\u201D is an amount.\n\u201CAdditional Fees\u201D is an amount.\nCLAUSE: Initial Retainer.\nClient pays Retainer to Attorney.\nCLAUSE: Additional Representation.\nClient pays Additional Fees to Attorney.\nCLAUSE: End of Representation.\nThe Attorney may terminate all contracts.\n
sample_code.liquid = class Random < Liquid::Block\n def initialize(tag_name, markup, tokens)\n super\n @rand = markup.to_i\n end\n\n def render(context)\n value = rand(@rand)\n super.sub('^^^', value.to_s) # calling `super` returns the content of the block\n end\nend\n\nLiquid::Template.register_tag('random', Random)\ntext = " {% random 5 %} you have drawn number ^^^, lucky you! {% endrandom %} "\n@template = Liquid::Template.parse(text)\[email protected] # will return "you have drawn number 1, lucky you!" in 20% of cases\n
sample_code.lua = \ -- defines a factorial function\n function fact (n)\n if n == 0 then\n return 1\n else\n return n * fact(n-1)\n end\n end\n \n print("enter a number:")\n a = io.read("*number") -- read a number\n print(fact(a))
sample_code.m3 = MODULE Person;\n\nREVEAL T = Public BRANDED \nOBJECT \n name: TEXT; (* These two variables *)\n age: INTEGER; (* are private. *)\nOVERRIDES\n getAge := Age;\n init := Init;\nEND;\n\nPROCEDURE Age(self: T): INTEGER =\n BEGIN\n RETURN self.age;\n END Age;\n\nPROCEDURE Init(self: T; name: TEXT; age: INTEGER): T =\n BEGIN\n self.name := name;\n self.age := age;\n RETURN self;\n END Init;\n\nBEGIN\nEND Person.
sample_code.markdown = # Header 1 #\n## Header 2 ##\n### Header 3 ### (Hashes on right are optional)\n## Markdown plus h2 with a custom ID ## {#id-goes-here}\n[Link back to H2](#id-goes-here)\n\n```js\nvar x = "string";\nfunction f() {\n return x;\n}\n```\n\n<!-- html madness -->\n<div class="custom-class" markdown="1">\n <div>\n nested div\n </div>\n <script type='text/x-koka'>\n function( x: int ) { return x*x; }\n </script>\n This is a div _with_ underscores\n and a & <b class="bold">bold</b> element.\n <style>\n body { font: "Consolas" }\n </style>\n</div>\n\n* Bullet lists are easy too\n- Another one\n+ Another one\n\nThis is a paragraph, which is text surrounded by\nwhitespace. Paragraphs can be on one\nline (or many), and can drone on for hours.\n\nNow some inline markup like _italics_, **bold**,\nand `code()`. Note that underscores\nin_words_are ignored.\n\n````application/json\n { value: ["or with a mime type"] }\n````\n\n> Blockquotes are like quoted text in email replies\n>> And, they can be nested\n\n1. A numbered list\n2. Which is numbered\n3. With periods and a space\n\nAnd now some code:\n\n // Code is just text indented a bit\n which(is_easy) to_remember();\n\nAnd a block\n\n~~~\n// Markdown extra adds un-indented code blocks too\n\nif (this_is_more_code == true && !indented) {\n // tild wrapped code blocks, also not indented\n}\n~~~\n\nText with\ntwo trailing spaces\n(on the right)\ncan be used\nfor things like poems\n\n### Horizontal rules\n\n* * * *\n****\n--------------------------\n\n\n\n## Markdown plus tables ##\n\n| Header | Header | Right |\n| ------ | ------ | -----: |\n| Cell | Cell | $10 |\n| Cell | Cell | $20 |\n\n* Outer pipes on tables are optional\n* Colon used for alignment (right versus left)\n\n## Markdown plus definition lists ##\n\nBottled water\n: $ 1.25\n: $ 1.55 (Large)\n\nMilk\nPop\n: $ 1.75\n\n* Multiple definitions and terms are possible\n* Definitions can include multiple paragraphs too\n\n*[ABBR]: Markdown plus abbreviations (produces an <abbr> tag)
sample_code.mdx = ---\nfrontmatter: data\nyaml: true\n---\n\n[link](https://example.com)\n\n~~~\naasd\nasd\nasd\n~~~\n\n# Hello MDX {1+2}\n\nimport { MyComponent } from './MyComponent'\n\nThis is **bold {'foo' + 1} text**\n\nThis is _emphasis {'foo' + 1} text_\n\nThis is *emphasis {'foo' + 1} text too*\n\n This is an indented *code* block\n\nexport function foo() {\n console.log('asd', 1)\n if(true) {\n return 'yep'\n }\n return 'nope'\n}\n\n\nThis is regular content\n\n- this is a list\n\n* this is also a list\n\n+ me too!\n\n1. pizza\n2. fries\n3. ice cream\n\n----\n\n_________\n\n***\\\n~~~css\nbody {\n color: red;\n}\n~~~\n\n> - this is a list\n>\n> * this is also a list\n>\n> + me too!\n>\n> 1. pizza\n> 2. fries\n> 3. ice cream\n>\n> ---\n>\n> _________\n>\n> ***\n>\n> ```css\n> body {\n> color: red;\n> }\n> ```\n\n> This is a blockquote\n>\n>> This is a nested {'blockquote'}\n\n{'foo' + 1 + 2 + {} + 12}\n\n{/* this is a comment */}\n\n<MyComponent contenteditable className="text-green-700" id='foo' width={100 + 100}>\n\n This is **also** markdown.\n\n</MyComponent>
sample_code.mips = # A[i] = A[i/2] + 1;\n lw $t0, 0($gp) # fetch i\n srl $t1, $t0, 1 # i/2\n sll $t1, $t1, 2 # turn i/2 into a byte offset (*4)\n add $t1, $gp, $t1 # &A[i/2] - 28\n lw $t1, 28($t1) # fetch A[i/2]\n addi $t1, $t1, 1 # A[i/2] + 1\n sll $t2, $t0, 2 # turn i into a byte offset\n add $t2, $t2, $gp # &A[i] - 28\n sw $t1, 28($t2) # A[i] = ...\n# A[i+1] = -1;\n addi $t1, $zero, -1 # -1\n sw $t1, 32($t2) # A[i+1] = -1\n
sample_code.msdax = \ = CALCULATE(SUM(Sales[SalesAmount]), PREVIOUSQUARTER(Calendar[DateKey]))
sample_code.mysql = CREATE TABLE shop (\n article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,\n dealer CHAR(20) DEFAULT '' NOT NULL,\n price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,\n PRIMARY KEY(article, dealer));\nINSERT INTO shop VALUES\n (1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),\n (3,'C',1.69),(3,'D',1.25),(4,'D',19.95);
sample_code.objective-c = //\n// Copyright (c) Microsoft Corporation. All rights reserved.\n//\n\n#import "UseQuotes.h"\n#import <Use/GTLT.h> \n\n/*\n\u0009Multi \n\u0009Line\n\u0009Comments \n*/\n@implementation Test\n\n- (void) applicationWillFinishLaunching:(NSNotification *)notification\n{\n}\n\n- (IBAction)onSelectInput:(id)sender\n{\n NSString* defaultDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0];\n \n NSOpenPanel* panel = [NSOpenPanel openPanel];\n [panel setAllowedFileTypes:[[NSArray alloc] initWithObjects:@"ipa", @"xcarchive", @"app", nil]];\n \n [panel beginWithCompletionHandler:^(NSInteger result)\n {\n if (result == NSFileHandlingPanelOKButton)\n [self.inputTextField setStringValue:[panel.URL path]];\n }];\n return YES;\n\n int hex = 0xFEF1F0F;\n\u0009 float ing = 3.14;\n\u0009 ing = 3.14e0;\n\u0009 ing = 31.4e-2;\n}\n\n-(id) initWithParams:(id<anObject>) aHandler withDeviceStateManager:(id<anotherObject>) deviceStateManager\n{\n // add a tap gesture recognizer\n UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];\n NSMutableArray *gestureRecognizers = [NSMutableArray array];\n [gestureRecognizers addObject:tapGesture];\n [gestureRecognizers addObjectsFromArray:scnView.gestureRecognizers];\n scnView.gestureRecognizers = gestureRecognizers;\n\n\u0009return tapGesture;\n\u0009return nil;\n}\n\n@end\n
sample_code.pascal = program GreetingsNumberOfTimes;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n System.SysUtils;\n\nvar\n greetingsMessage: string;\n numberOfTimes, i: integer;\n\nbegin\n try\n { TODO -oUser -cConsole Main : Insert code here }\n greetingsMessage := 'Hello World!';\n numberOfTimes := 10;\n\n for i := 1 to numberOfTimes do\n begin\n Writeln(greetingsMessage);\n end;\n except\n on E: Exception do\n Writeln(E.ClassName, ': ', E.Message);\n end;\nend.\n
sample_code.pascaligo = type storage is int\ntype parameter is\n Increment of int\n| Decrement of int\n| Reset\ntype return is list (operation) * storage\n// Two entrypoints\nfunction add (const store : storage; const delta : int) : storage is\n store + delta\nfunction sub (const store : storage; const delta : int) : storage is\n store - delta\n(* Main access point that dispatches to the entrypoints according to\n the smart contract parameter. *)\nfunction main (const action : parameter; const store : storage) : return is\n ((nil : list (operation)), // No operations\n case action of\n Increment (n) -> add (store, n)\n | Decrement (n) -> sub (store, n)\n | Reset -> 0\n end)\n
sample_code.perl = #!/usr/bin/perl\nuse strict;\nuse warnings;\n\nuse Path::Tiny;\n\nmy $dir = path('foo','bar'); # foo/bar\n\n# Iterate over the content of foo/bar\nmy $iter = $dir->iterator;\nwhile (my $file = $iter->()) {\n\n # See if it is a directory and skip\n next if $file->is_dir();\n\n # Print out the file name and path\n print "$file\\n";\n}
sample_code.pgsql = BEGIN\n SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;\n EXCEPTION\n WHEN NO_DATA_FOUND THEN\n RAISE EXCEPTION 'employee % not found', myname;\n WHEN TOO_MANY_ROWS THEN\n RAISE EXCEPTION 'employee % not unique', myname;\nEND;
sample_code.php = <?php\n// The next line contains a syntax error:\nif () {\n\u0009return "The parser recovers from this type of syntax error";\n}\n?>\n<html>\n<head>\n\u0009<title>Example page</title>\n</head>\n\n<body>\n\n<script type="text/javascript">\n\u0009// Some PHP embedded inside JS\n\u0009// Generated <?=date('l, F jS, Y')?>\n\u0009\n\u0009var server_token = <?=rand(5, 10000)?>\n\u0009if (typeof server_token === 'number') {\n\u0009\u0009alert('token: ' + server_token);\n\u0009}\n</script>\n\n<div>\nHello\n<? if (isset($user)) { ?>\n\u0009<b><?=$user?></b>\n<? } else { ?>\n\u0009<i>guest</i>\n<? } ?>\n!\n</div>\n\n<?php\n\n\u0009/* Example PHP file\n\u0009multiline comment\n\u0009*/\n\n\u0009$cards = array("ah", "ac", "ad", "as",\n\u0009\u0009"2h", "2c", "2d", "2s",\n\u0009\u0009"3h", "3c", "3d", "3s",\n\u0009\u0009"4h", "4c", "4d", "4s",\n\u0009\u0009"5h", "5c", "5d", "5s",\n\u0009\u0009"6h", "6c", "6d", "6s",\n\u0009\u0009"7h", "7c", "7d", "7s",\n\u0009\u0009"8h", "8c", "8d", "8s",\n\u0009\u0009"9h", "9c", "9d", "9s",\n\u0009\u0009"th", "tc", "td", "ts",\n\u0009\u0009"jh", "jc", "jd", "js",\n\u0009\u0009"qh", "qc", "qd", "qs",\n\u0009\u0009"kh", "kc", "kd", "ks");\n\n\u0009srand(time());\n\n\u0009for($i = 0; $i < 52; $i++) {\n\u0009\u0009$count = count($cards);\n\u0009\u0009$random = (rand()%$count);\n\n\u0009\u0009if($cards[$random] == "") {\n\u0009\u0009\u0009$i--;\n\u0009\u0009} else {\n\u0009\u0009\u0009$deck[] = $cards[$random];\n\u0009\u0009\u0009$cards[$random] = "";\n\u0009\u0009}\n\u0009}\n\n\u0009srand(time());\n\u0009$starting_point = (rand()%51);\n\u0009print("Starting point for cut cards is: $starting_point<p>");\n\n\u0009// display shuffled cards (EXAMPLE ONLY)\n\u0009for ($index = 0; $index < 52; $index++) {\n\u0009\u0009if ($starting_point == 52) { $starting_point = 0; }\n\u0009\u0009print("Uncut Point: <strong>$deck[$index]</strong> ");\n\u0009\u0009print("Starting Point: <strong>$deck[$starting_point]</strong><br>");\n\u0009\u0009$starting_point++;\n\u0009}\n?>\n\n</body>\n</html>
sample_code.pla = .ob out1 out2 out3\n--1-- - wait 110000\n.ilb in1 in0 wait ack nack\n.symbolic state<3> state<2>;aaa bbb; # comment\n
sample_code.plaintext = Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus aliquet sapien, sed rhoncus leo ullamcorper ornare. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus feugiat eleifend nisl, aliquet rhoncus quam scelerisque vel. Morbi eu pellentesque ex. Nam suscipit maximus leo blandit cursus. Aenean sollicitudin nisi luctus, ornare nibh viverra, laoreet ex. Donec eget nibh sit amet dolor ornare elementum. Morbi sollicitudin enim vitae risus pretium vestibulum. Ut pretium hendrerit libero, non vulputate ante volutpat et. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam malesuada turpis vitae est porttitor, id tincidunt neque dignissim. Integer rhoncus vestibulum justo in iaculis. Praesent nec augue ut dui scelerisque gravida vel id velit. Donec vehicula feugiat mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\n\nPraesent diam lorem, luctus quis ullamcorper non, consequat quis orci. Ut vel massa vel nunc sagittis porttitor a vitae ante. Quisque euismod lobortis imperdiet. Vestibulum tincidunt vehicula posuere. Nulla facilisi. Donec sodales imperdiet risus id ullamcorper. Nulla luctus orci tortor, vitae tincidunt urna aliquet nec. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam consequat dapibus massa. Sed ac pharetra magna, in imperdiet neque. Nullam nunc nisi, consequat vel nunc et, sagittis aliquam arcu. Aliquam non orci magna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed id sem ut sem pulvinar rhoncus. Aenean venenatis nunc eget mi ornare, vitae maximus lacus varius. Quisque quis vestibulum justo.\n\nDonec euismod luctus volutpat. Donec sed lacinia enim. Vivamus aliquam elit cursus, convallis diam at, volutpat turpis. Sed lacinia nisl in auctor dapibus. Nunc turpis mi, mattis ut rhoncus id, lacinia sed lectus. Donec sodales tellus quis libero gravida pretium et quis magna. Etiam ultricies mollis purus, eget consequat velit. Duis vitae nibh vitae arcu tincidunt congue. Maecenas ut velit in ipsum condimentum dictum quis eget urna. Sed mattis nulla arcu, vitae mattis ligula dictum at.\n\nPraesent at dignissim dolor. Donec quis placerat sem. Cras vitae placerat sapien, eu sagittis ex. Mauris nec luctus risus. Cras imperdiet semper neque suscipit auctor. Mauris nisl massa, commodo sit amet dignissim id, malesuada sed ante. Praesent varius sapien eget eros vehicula porttitor.\n\nMauris auctor nunc in quam tempor, eget consectetur nisi rhoncus. Donec et nulla imperdiet, gravida dui at, accumsan velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin sollicitudin condimentum auctor. Sed lacinia eleifend nisi, id scelerisque leo laoreet sit amet. Morbi congue augue a malesuada pulvinar. Curabitur nec ante finibus, commodo orci vel, aliquam libero. Morbi molestie purus non nunc placerat fermentum. Pellentesque commodo ligula sed pretium aliquam. Praesent ut nibh ex. Vivamus vestibulum velit in leo suscipit, vitae pellentesque urna vulputate. Suspendisse pretium placerat ligula eu ullamcorper. Nam eleifend mi tellus, ut tristique ante ultricies vitae. Quisque venenatis dapibus tellus sit amet mattis. Donec erat arcu, elementum vel nisl at, sagittis vulputate nisi.
sample_code.postiats = // http://www.ats-lang.org/\n(* Say Hello! once *)\nval () = print"Hello!\\n"\n//\n(* Say Hello! 3 times *)\nval () = 3*delay(print"Hello!")\nval () = print_newline((*void*))\n//\n\n//\n(* Build a list of 3 *)\nval xs = $list{int}(0, 1, 2)\n//\nval x0 = xs[0] // legal\nval x1 = xs[1] // legal\nval x2 = xs[2] // legal\nval x3 = xs[3] // illegal\n//\n\n//\nextern\nfun{} f0 (): int\nextern\nfun{} f1 (int): int\nextern\nfun{} repeat_f0f1 (int): int\n//\nimplement\n{}(*tmp*)\nrepeat_f0f1(n) =\n if n = 0\n then f0()\n else f1(repeat_f0f1(n-1))\n // end of [if]\n//\nfun\ntimes (\n m:int, n:int\n) : int = // m*n\n repeat_f0f1 (m) where\n{\n implement f0<> () = 0\n implement f1<> (x) = x + n\n}\n//\nfun\npower (\n m:int, n:int\n) : int = // m^n\n repeat_f0f1 (n) where\n{\n implement f0<> () = 1\n implement f1<> (x) = m * x\n}\n//\nval () =\nprintln! ("5*5 = ", times(5,5))\nval () =\nprintln! ("5^2 = ", power(5,2))\nval () =\nprintln! ("2^10 = ", power(2,10))\nval () =\nprintln! ("3^10 = ", power(3,10))\n//\n
sample_code.powerquery = let\n Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],\n SplitColumnDelimiter = Table.SplitColumn(Source,"Input",Splitter.SplitTextByDelimiter(","),13),\n Unpivot = Table.Unpivot(SplitColumnDelimiter,{"Input.1", "Input.2", "Input.3", "Input.4",\n "Input.5", "Input.6", "Input.7", "Input.8", "Input.9", "Input.10", "Input.11", "Input.12"\n , "Input.13"},"Attribute","Value"),\n RemovedColumns = Table.RemoveColumns(Unpivot,{"Attribute"}),\n DuplicatesRemoved = Table.Distinct(RemovedColumns),\n GroupedRows = Table.Group(DuplicatesRemoved, {"RowID"}, {{"Count of Distinct Values"\n , each Table.RowCount(_), type number}})\nin\n GroupedRows
sample_code.powershell = $SelectedObjectNames=@();\n$XenCenterNodeSelected = 0;\n#the object info array contains hashmaps, each of which represent a parameter set and describe a target in the XenCenter resource list\nforeach($parameterSet in $ObjInfoArray)\n{\n\u0009if ($parameterSet["class"] -eq "blank")\n\u0009{\n\u0009\u0009#When the XenCenter node is selected a parameter set is created for each of your connected servers with the class and objUuid keys marked as blank\n\u0009\u0009if ($XenCenterNodeSelected)\n\u0009\u0009{\n\u0009\u0009\u0009continue\n\u0009\u0009}\n\u0009\u0009$XenCenterNodeSelected = 1;\n\u0009\u0009$SelectedObjectNames += "XenCenter"\n\u0009}\n\u0009elseif ($parameterSet["sessionRef"] -eq "null")\n\u0009{\n\u0009\u0009#When a disconnected server is selected there is no session information, we get null for everything except class\n\u0009}\n\u0009\u0009$SelectedObjectNames += "a disconnected server"\n\u0009else\n\u0009{\n\u0009\u0009Connect-XenServer -url $parameterSet["url"] -opaqueref $parameterSet["sessionRef"]\n\u0009\u0009#Use $class to determine which server objects to get\n\u0009\u0009#-properties allows us to filter the results to just include the selected object\n\u0009\u0009$exp = "Get-XenServer:{0} -properties @{{uuid='{1}'}}" -f $parameterSet["class"], $parameterSet["objUuid"]\n\u0009\u0009$obj = Invoke-Expression $exp\n\u0009\u0009$SelectedObjectNames += $obj.name_label;\n\u0009} \n}
sample_code.proto = syntax = "proto3";\nimport public "other.proto";\n\n/* SearchRequest represents a search query, with pagination options to\n * indicate which results to include in the response. */\n\nmessage SearchRequest {\n required string query = 1;\n optional int32 page_number = 2; // Which page number do we want?\n optional int32 result_per_page = 3; // Number of results to return per page.\n}\n
sample_code.pug = doctype 5\nhtml(lang="en")\n head\n title= pageTitle\n script(type='text/javascript')\n if (foo) {\n bar()\n }\n body\n // Disclaimer: You will need to turn insertSpaces to true in order for the\n syntax highlighting to kick in properly (especially for comments)\n Enjoy :)\n h1 Pug - node template engine\n #container\n if youAreUsingPug\n p You are amazing\n else\n p Get on it!
sample_code.python = import banana\n\n\nclass Monkey:\n # Bananas the monkey can eat.\n capacity = 10\n def eat(self, n):\n """Make the monkey eat n bananas!"""\n self.capacity -= n * banana.size\n\n def feeding_frenzy(self):\n self.eat(9.25)\n return "Yum yum"\n
sample_code.qsharp = // Run this cell using Ctrl+Enter (\u2318+Enter on Mac)\n// Then run the next cell to see the output\n\nopen Microsoft.Quantum.Diagnostics;\n\noperation QubitsDemo () : Unit {\n // This line allocates a qubit in state |0\u27E9\n use q = Qubit();\n Message("State |0\u27E9:");\n\n // This line prints out the state of the quantum computer\n // Since only one qubit is allocated, only its state is printed\n DumpMachine();\n\n // This line changes the qubit from state |0\u27E9 to state |1\u27E9\n X(q);\n\n Message("State |1\u27E9:");\n DumpMachine();\n\n // This line changes the qubit to state |-\u27E9 = (1/sqrt(2))(|0\u27E9 - |1\u27E9)\n // That is, this puts the qubit into a superposition\n // 1/sqrt(2) is approximately 0.707107\n H(q);\n\n Message("State |-\u27E9:");\n DumpMachine();\n\n // This line changes the qubit to state |-i\u27E9 = (1/sqrt(2))(|0\u27E9 - i|1\u27E9)\n S(q);\n\n Message("State |-i\u27E9:");\n DumpMachine();\n\n // This will put the qubit into an uneven superposition,\n // where the amplitudes of |0\u27E9 and |1\u27E9 have different moduli\n Rx(2.0, q);\n Ry(1.0, q);\n\n Message("Uneven superposition state:");\n DumpMachine();\n\n // This line returns the qubit to state |0\u27E9\n Reset(q);\n}\n
sample_code.r = # \u00A9 Microsoft. All rights reserved.\n\n#' Add together two numbers.\n#' \n#' @param x A number.\n#' @param y A number.\n#' @return The sum of \\code{x} and \\code{y}.\n#' @examples\n#' add(1, 1)\n#' add(10, 1)\nadd <- function(x, y) {\n x + y\n}\n\nadd(1, 2)\nadd(1.0, 2.0)\nadd(-1, -2)\nadd(-1.0, -2.0)\nadd(1.0e10, 2.0e10)\n\n\n#' Concatenate together two strings.\n#' \n#' @param x A string.\n#' @param y A string.\n#' @return The concatenated string built of \\code{x} and \\code{y}.\n#' @examples\n#' strcat("one", "two")\nstrcat <- function(x, y) {\n paste(x, y)\n}\n\npaste("one", "two")\npaste('one', 'two')\npaste(NULL, NULL)\npaste(NA, NA)\n\npaste("multi-\n line",\n 'multi-\n line')\n
sample_code.razor = @{\n var total = 0;\n var totalMessage = "";\n @* a multiline\n razor comment embedded in csharp *@\n if (IsPost) {\n\n // Retrieve the numbers that the user entered.\n var num1 = Request["text1"];\n var num2 = Request["text2"];\n\n // Convert the entered strings into integers numbers and add.\n total = num1.AsInt() + num2.AsInt();\n\u0009\u0009<italic><bold>totalMessage = "Total = " + total;</bold></italic>\n }\n}\n\n<!DOCTYPE html>\n<html lang="en">\n <head>\n <title>Add Numbers</title>\n <meta charset="utf-8" />\n </head>\n<body>\n <p>Enter two whole numbers and then click <strong>Add</strong>.</p>\n <form action="" method="post">\n <p><label for="text1">First Number:</label>\n <input type="text" name="text1" />\n </p>\n <p><label for="text2">Second Number:</label>\n <input type="text" name="text2" />\n </p>\n <p><input type="submit" value="Add" /></p>\n </form>\n\n\u0009@* now we call the totalMessage method \n\u0009 (a multi line razor comment outside code) *@\n\n <p>@totalMessage</p>\n \n <p>@(totalMessage+"!")</p>\n \n An email address (with escaped at character): name@@domain.com\n \n</body>\n</html>\n
sample_code.redis = EXISTS mykey\nAPPEND mykey "Hello"\nAPPEND mykey " World"\nGET mykey
sample_code.redshift = create view tables_vw as\nselect distinct(id) table_id\n,trim(datname) db_name\n,trim(nspname) schema_name\n,trim(relname) table_name\nfrom stv_tbl_perm\njoin pg_class on pg_class.oid = stv_tbl_perm.id\njoin pg_namespace on pg_namespace.oid = relnamespace\njoin pg_database on pg_database.oid = stv_tbl_perm.db_id;\n
sample_code.restructuredtext = =================\nMy Project Readme\n=================\n-------------------------\nClever subtitle goes here\n-------------------------\n\nIntroduction\n============\n\nThis is an example reStructuredText document that starts at the very top\nwith a title and a sub-title. There is one primary header, Introduction.\nThere is one example subheading below.\nThe document is just plain text so it is easily readable even before\nbeing converted to HTML, man page, PDF or other formats.\n\nSubheading\n----------\n\nThe basic syntax is not that different from Markdown, but it also\nhas many more powerful features that Markdown doesn't have. We aren't\ntaking advantage of those yet though.\n\n- Bullet points\n- Are intuitive\n- And simple too\n
sample_code.ruby = #-------------------------------------------------------------------------\n# Copyright (c) Microsoft. All rights reserved.\n#--------------------------------------------------------------------------\n\nmodule Azure\n module Blob\n class Blob\n \n def initialize\n @properties = {}\n @metadata = {}\n yield self if block_given?\n end\n\n attr_accessor :name\n attr_accessor :snapshot\n attr_accessor :properties\n attr_accessor :metadata\n end\n end\nend
sample_code.rust = fn main() {\n let greetings = ["Hello", "Hola", "Bonjour",\n "Ciao", "\u3053\u3093\u306B\u3061\u306F", "\uC548\uB155\uD558\uC138\uC694",\n "Cze\u015B\u0107", "Ol\u00E1", "\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435",\n "Ch\u00E0o b\u1EA1n", "\u60A8\u597D", "Hallo",\n "Hej", "Ahoj", "\u0633\u0644\u0627\u0645"];\n\n for (num, greeting) in greetings.iter().enumerate() {\n print!("{} : ", greeting);\n match num {\n 0 => println!("This code is editable and runnable!"),\n 1 => println!("\u00A1Este c\u00F3digo es editable y ejecutable!"),\n 2 => println!("Ce code est modifiable et ex\u00E9cutable !"),\n 3 => println!("Questo codice \u00E8 modificabile ed eseguibile!"),\n 4 => println!("\u3053\u306E\u30B3\u30FC\u30C9\u306F\u7DE8\u96C6\u3057\u3066\u5B9F\u884C\u51FA\u6765\u307E\u3059\uFF01"),\n 5 => println!("\uC5EC\uAE30\uC5D0\uC11C \uCF54\uB4DC\uB97C \uC218\uC815\uD558\uACE0 \uC2E4\uD589\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4!"),\n 6 => println!("Ten kod mo\u017Cna edytowa\u0107 oraz uruchomi\u0107!"),\n 7 => println!("Este c\u00F3digo \u00E9 edit\u00E1vel e execut\u00E1vel!"),\n 8 => println!("\u042D\u0442\u043E\u0442 \u043A\u043E\u0434 \u043C\u043E\u0436\u043D\u043E \u043E\u0442\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0438 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C!"),\n 9 => println!("B\u1EA1n c\u00F3 th\u1EC3 edit v\u00E0 run code tr\u1EF1c ti\u1EBFp!"),\n 10 => println!("\u8FD9\u6BB5\u4EE3\u7801\u662F\u53EF\u4EE5\u7F16\u8F91\u5E76\u4E14\u80FD\u591F\u8FD0\u884C\u7684\uFF01"),\n 11 => println!("Dieser Code kann bearbeitet und ausgef\u00FChrt werden!"),\n 12 => println!("Den h\u00E4r koden kan redigeras och k\u00F6ras!"),\n 13 => println!("Tento k\u00F3d m\u016F\u017Eete upravit a spustit"),\n 14 => println!("\u0627\u06CC\u0646 \u06A9\u062F \u0642\u0627\u0628\u0644\u06CC\u062A \u0648\u06CC\u0631\u0627\u06CC\u0634 \u0648 \u0627\u062C\u0631\u0627 \u062F\u0627\u0631\u062F!"),\n _ => {},\n }\n }\n}\n
sample_code.sb = begin:\nTextWindow.Write("Enter a number: ")\nnum = TextWindow.ReadNumber()\nremainder = Math.Remainder(num, 2)\nIf (remainder = 0) Then\n TextWindow.WriteLine("The number is Even")\nElse\n TextWindow.WriteLine("The number is Odd")\nEndIf\nGoto begin
sample_code.scala = package examples\n\n/** Quick sort, imperative style */\nobject sort {\n\n /** Nested methods can use and even update everything\n * visible in their scope (including local variables or\n * arguments of enclosing methods).\n */\n def sort(a: Array[Int]) {\n\n def swap(i: Int, j: Int) {\n val t = a(i); a(i) = a(j); a(j) = t\n }\n\n def sort1(l: Int, r: Int) {\n val pivot = a((l + r) / 2)\n var i = l\n var j = r\n while (i <= j) {\n while (a(i) < pivot) i += 1\n while (a(j) > pivot) j -= 1\n if (i <= j) {\n swap(i, j)\n i += 1\n j -= 1\n }\n }\n if (l < j) sort1(l, j)\n if (j < r) sort1(i, r)\n }\n\n if (a.length > 0)\n sort1(0, a.length - 1)\n }\n\n def println(ar: Array[Int]) {\n def print1 = {\n def iter(i: Int): String =\n ar(i) + (if (i < ar.length-1) "," + iter(i+1) else "")\n if (ar.length == 0) "" else iter(0)\n }\n Console.println("[" + print1 + "]")\n }\n\n def main(args: Array[String]) {\n val ar = Array(6, 2, 8, 5, 1)\n println(ar)\n sort(ar)\n println(ar)\n }\n\n}\n
sample_code.scheme = ;;; make-matrix creates a matrix (a vector of vectors).\n(define make-matrix\n (lambda (rows columns)\n (do ((m (make-vector rows))\n (i 0 (+ i 1)))\n ((= i rows) m)\n (vector-set! m i (make-vector columns)))))\n\n;;; matrix? checks to see if its argument is a matrix.\n;;; It isn't foolproof, but it's generally good enough.\n(define matrix?\n (lambda (x)\n (and (vector? x)\n (> (vector-length x) 0)\n (vector? (vector-ref x 0)))))\n\n;; matrix-rows returns the number of rows in a matrix.\n(define matrix-rows\n (lambda (x)\n (vector-length x)))\n\n;; matrix-columns returns the number of columns in a matrix.\n(define matrix-columns\n (lambda (x)\n (vector-length (vector-ref x 0))))\n\n;;; matrix-ref returns the jth element of the ith row.\n(define matrix-ref\n (lambda (m i j)\n (vector-ref (vector-ref m i) j)))\n\n;;; matrix-set! changes the jth element of the ith row.\n(define matrix-set!\n (lambda (m i j x)\n (vector-set! (vector-ref m i) j x)))\n\n;;; mul is the generic matrix/scalar multiplication procedure\n(define mul\n (lambda (x y)\n ;; mat-sca-mul multiplies a matrix by a scalar.\n (define mat-sca-mul\n (lambda (m x)\n (let* ((nr (matrix-rows m))\n (nc (matrix-columns m))\n (r (make-matrix nr nc)))\n (do ((i 0 (+ i 1)))\n ((= i nr) r)\n (do ((j 0 (+ j 1)))\n ((= j nc))\n (matrix-set! r i j\n (* x (matrix-ref m i j))))))))\n\n ;; mat-mat-mul multiplies one matrix by another, after verifying\n ;; that the first matrix has as many columns as the second\n ;; matrix has rows.\n (define mat-mat-mul\n (lambda (m1 m2)\n (let* ((nr1 (matrix-rows m1))\n (nr2 (matrix-rows m2))\n (nc2 (matrix-columns m2))\n (r (make-matrix nr1 nc2)))\n (if (not (= (matrix-columns m1) nr2))\n (match-error m1 m2))\n (do ((i 0 (+ i 1)))\n ((= i nr1) r)\n (do ((j 0 (+ j 1)))\n ((= j nc2))\n (do ((k 0 (+ k 1))\n (a 0\n (+ a\n (* (matrix-ref m1 i k)\n (matrix-ref m2 k j)))))\n ((= k nr2)\n (matrix-set! r i j a))))))))\n\n ;; type-error is called to complain when mul receives an invalid\n ;; type of argument.\n (define type-error\n (lambda (what)\n (error 'mul\n "~s is not a number or matrix"\n what)))\n\n ;; match-error is called to complain when mul receives a pair of\n ;; incompatible arguments.\n (define match-error\n (lambda (what1 what2)\n (error 'mul\n "~s and ~s are incompatible operands"\n what1\n what2)))\n\n ;; body of mul; dispatch based on input types\n (cond\n ((number? x)\n (cond\n ((number? y) (* x y))\n ((matrix? y) (mat-sca-mul y x))\n (else (type-error y))))\n ((matrix? x)\n (cond\n ((number? y) (mat-sca-mul x y))\n ((matrix? y) (mat-mat-mul x y))\n (else (type-error y))))\n (else (type-error x)))))
sample_code.scss = $baseFontSizeInPixels: 14;\n\n@function px2em ($font_size, $base_font_size: $baseFontSizeInPixels) { \n @return ($font_size / $base_font_size) + em; \n}\n\nh1 {\n font-size: px2em(36, $baseFontSizeInPixels);\n}\nh2 {\n font-size: px2em(28, $baseFontSizeInPixels);\n}\n.class {\n font-size: px2em(14, $baseFontSizeInPixels);\n}\n\nnav {\n ul {\n margin: 0;\n padding: 0;\n list-style: none;\n }\n\n li { display: inline-block; }\n\n a {\n display: block;\n padding: 6px 12px;\n text-decoration: none;\n }\n \n @each $animal in puma, sea-slug, egret, salamander {\n .#{$animal}-icon {\n background-image: url('/images/#{$animal}.png');\n }\n }\n}
sample_code.shell = #!/bin/bash\n# Simple line count example, using bash\n#\n# Bash tutorial: http://linuxconfig.org/Bash_scripting_Tutorial#8-2-read-file-into-bash-array\n# My scripting link: http://www.macs.hw.ac.uk/~hwloidl/docs/index.html#scripting\n#\n# Usage: ./line_count.sh file\n# -----------------------------------------------------------------------------\n\n# Link filedescriptor 10 with stdin\nexec 10<&0\n# stdin replaced with a file supplied as a first argument\nexec < $1\n# remember the name of the input file\nin=$1\n\n# init\nfile="current_line.txt"\nlet count=0\n\n# this while loop iterates over all lines of the file\nwhile read LINE\ndo\n # increase line counter\n ((count++))\n # write current line to a tmp file with name $file (not needed for counting)\n echo $LINE > $file\n # this checks the return code of echo (not needed for writing; just for demo)\n if [ $? -ne 0 ]\n then echo "Error in writing to file /home/runner/work/primefaces-extensions/primefaces-extensions/showcase/pom.xml; check its permissions!"\n fi\ndone\n\necho "Number of lines: $count"\necho "The last line of the file is: `cat /home/runner/work/primefaces-extensions/primefaces-extensions/showcase/pom.xml`"\n\n# Note: You can achieve the same by just using the tool wc like this\necho "Expected number of lines: `wc -l $in`"\n\n# restore stdin from filedescriptor 10\n# and close filedescriptor 10\nexec 0<&10 10<&-
sample_code.sol = pragma solidity ^0.4.11;\n\n/// @title Voting with delegation.\ncontract Ballot {\n // This declares a new complex type which will\n // be used for variables later.\n // It will represent a single voter.\n struct Voter {\n uint weight; // weight is accumulated by delegation\n bool voted; // if true, that person already voted\n address delegate; // person delegated to\n uint vote; // index of the voted proposal\n }\n\n // This is a type for a single proposal.\n struct Proposal {\n bytes32 name; // short name (up to 32 bytes)\n uint voteCount; // number of accumulated votes\n }\n\n address public chairperson;\n\n // This declares a state variable that\n // stores a `Voter` struct for each possible address.\n mapping(address => Voter) public voters;\n\n // A dynamically-sized array of `Proposal` structs.\n Proposal[] public proposals;\n\n /// Create a new ballot to choose one of `proposalNames`.\n function Ballot(bytes32[] proposalNames) {\n chairperson = msg.sender;\n voters[chairperson].weight = 1;\n\n // For each of the provided proposal names,\n // create a new proposal object and add it\n // to the end of the array.\n for (uint i = 0; i < proposalNames.length; i++) {\n // `Proposal({...})` creates a temporary\n // Proposal object and `proposals.push(...)`\n // appends it to the end of `proposals`.\n proposals.push(Proposal({\n name: proposalNames[i],\n voteCount: 0\n }));\n }\n }\n\n // Give `voter` the right to vote on this ballot.\n // May only be called by `chairperson`.\n function giveRightToVote(address voter) {\n // If the argument of `require` evaluates to `false`,\n // it terminates and reverts all changes to\n // the state and to Ether balances. It is often\n // a good idea to use this if functions are\n // called incorrectly. But watch out, this\n // will currently also consume all provided gas\n // (this is planned to change in the future).\n require((msg.sender == chairperson) && !voters[voter].voted && (voters[voter].weight == 0));\n voters[voter].weight = 1;\n }\n\n /// Delegate your vote to the voter `to`.\n function delegate(address to) {\n // assigns reference\n Voter sender = voters[msg.sender];\n require(!sender.voted);\n\n // Self-delegation is not allowed.\n require(to != msg.sender);\n\n // Forward the delegation as long as\n // `to` also delegated.\n // In general, such loops are very dangerous,\n // because if they run too long, they might\n // need more gas than is available in a block.\n // In this case, the delegation will not be executed,\n // but in other situations, such loops might\n // cause a contract to get "stuck" completely.\n while (voters[to].delegate != address(0)) {\n to = voters[to].delegate;\n\n // We found a loop in the delegation, not allowed.\n require(to != msg.sender);\n }\n\n // Since `sender` is a reference, this\n // modifies `voters[msg.sender].voted`\n sender.voted = true;\n sender.delegate = to;\n Voter delegate = voters[to];\n if (delegate.voted) {\n // If the delegate already voted,\n // directly add to the number of votes\n proposals[delegate.vote].voteCount += sender.weight;\n } else {\n // If the delegate did not vote yet,\n // add to her weight.\n delegate.weight += sender.weight;\n }\n }\n\n /// Give your vote (including votes delegated to you)\n /// to proposal `proposals[proposal].name`.\n function vote(uint proposal) {\n Voter sender = voters[msg.sender];\n require(!sender.voted);\n sender.voted = true;\n sender.vote = proposal;\n\n // If `proposal` is out of the range of the array,\n // this will throw automatically and revert all\n // changes.\n proposals[proposal].voteCount += sender.weight;\n }\n\n /// @dev Computes the winning proposal taking all\n /// previous votes into account.\n function winningProposal() constant\n returns (uint winningProposal)\n {\n uint winningVoteCount = 0;\n for (uint p = 0; p < proposals.length; p++) {\n if (proposals[p].voteCount > winningVoteCount) {\n winningVoteCount = proposals[p].voteCount;\n winningProposal = p;\n }\n }\n }\n\n // Calls winningProposal() function to get the index\n // of the winner contained in the proposals array and then\n // returns the name of the winner\n function winnerName() constant\n returns (bytes32 winnerName)\n {\n winnerName = proposals[winningProposal()].name;\n }\n}
sample_code.sparql = \ SELECT ?x ?name\n {\n ?x foaf:mbox <mailto:alice@example> .\n ?x foaf:knows ?a1 .\n ?a1 foaf:knows ?a2 .\n ?a2 foaf:name ?name .\n }\n
sample_code.sql = CREATE TABLE dbo.EmployeePhoto\n(\n EmployeeId INT NOT NULL PRIMARY KEY,\n Photo VARBINARY(MAX) FILESTREAM NULL,\n MyRowGuidColumn UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL\n UNIQUE DEFAULT NEWID()\n);\n\nGO\n\n/*\ntext_of_comment\n/* nested comment */\n*/\n\n-- line comment\n\nCREATE NONCLUSTERED INDEX IX_WorkOrder_ProductID\n ON Production.WorkOrder(ProductID)\n WITH (FILLFACTOR = 80,\n PAD_INDEX = ON,\n DROP_EXISTING = ON);\nGO\n\nWHILE (SELECT AVG(ListPrice) FROM Production.Product) < $300\nBEGIN\n UPDATE Production.Product\n SET ListPrice = ListPrice * 2\n SELECT MAX(ListPrice) FROM Production.Product\n IF (SELECT MAX(ListPrice) FROM Production.Product) > $500\n BREAK\n ELSE\n CONTINUE\nEND\nPRINT 'Too much for the market to bear';\n\nMERGE INTO Sales.SalesReason AS [Target]\nUSING (VALUES ('Recommendation','Other'), ('Review', 'Marketing'), ('Internet', 'Promotion'))\n AS [Source] ([NewName], NewReasonType)\nON [Target].[Name] = [Source].[NewName]\nWHEN MATCHED\nTHEN UPDATE SET ReasonType = [Source].NewReasonType\nWHEN NOT MATCHED BY TARGET\nTHEN INSERT ([Name], ReasonType) VALUES ([NewName], NewReasonType)\nOUTPUT $action INTO @SummaryOfChanges;\n\nSELECT ProductID, OrderQty, SUM(LineTotal) AS Total\nFROM Sales.SalesOrderDetail\nWHERE UnitPrice < $5.00\nGROUP BY ProductID, OrderQty\nORDER BY ProductID, OrderQty\nOPTION (HASH GROUP, FAST 10);\n
sample_code.st = CONFIGURATION DefaultCfg\n VAR_GLOBAL\n Start_Stop AT %IX0.0: BOOL; (* This is a comment *)\n END_VAR\n TASK NewTask (INTERVAL := T#20ms);\n PROGRAM Main WITH NewTask : PLC_PRG;\nEND_CONFIGURATION\n\nPROGRAM demo\n VAR_EXTERNAL\n Start_Stop: BOOL;\n END_VAR\n VAR\n a : REAL; // Another comment\n todTest: TIME_OF_DAY := TOD#12:55;\n END_VAR\n a := csq(12.5);\n TON1(IN := TRUE, PT := T#2s);\n 16#FAC0 2#1001_0110\n IF TON1.Q AND a > REAL#100 THEN\n Start_Stop := TRUE;\n END_IF\nEND_PROGRAM;\n\n/* Get a square of the circle */\nFUNCTION csq : REAL\n VAR_INPUT\n r: REAL;\n END_VAR\n VAR CONSTANT\n c_pi: REAL := 3.14;\n END_VAR\n csq := ABS(c_pi * (r * 2));\nEND_FUNCTION
sample_code.swift = import Foundation\n\nprotocol APIControllerProtocol {\n func didReceiveAPIResults(results: NSArray)\n}\n\nclass APIController {\n var delegate: APIControllerProtocol\n\n init(delegate: APIControllerProtocol) {\n self.delegate = delegate\n }\n\n func get(path: String) {\n let url = NSURL(string: path)\n let session = NSURLSession.sharedSession()\n let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in\n println("Task completed")\n if(error != nil) {\n // If there is an error in the web request, print it to the console\n println(error.localizedDescription)\n }\n var err: NSError?\n if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {\n if(err != nil) {\n // If there is an error parsing JSON, print it to the console\n println("JSON Error \\(err!.localizedDescription)")\n }\n if let results: NSArray = jsonResult["results"] as? NSArray {\n self.delegate.didReceiveAPIResults(results)\n }\n }\n })\n\n // The task is just an object with all these properties set\n // In order to actually make the web request, we need to "resume"\n task.resume()\n }\n\n func searchItunesFor(searchTerm: String) {\n // The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs\n let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)\n\n // Now escape anything else that isn't URL-friendly\n if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {\n let urlPath = "https://itunes.apple.com/search?term=\\(escapedSearchTerm)&media=music&entity=album"\n }\n }\n\n}
sample_code.systemverilog = // File : tb_top.sv\nmodule tb_top ();\n\n\u0009reg clk;\n\u0009reg resetn;\n\u0009reg d;\n\u0009wire q;\n\n\u0009// Instantiate the design\n\u0009d_ff d_ff0 (\u0009.clk (clk),\n\u0009\u0009 \u0009\u0009.resetn (resetn),\n\u0009\u0009 \u0009\u0009.d (d),\n\u0009\u0009 \u0009\u0009.q (q));\n\n\u0009// Create a clock\n\u0009always #10 clk <= ~clk;\n\n\u0009initial begin\n\u0009\u0009resetn <= 0;\n\u0009\u0009d <= 0;\n\n\u0009\u0009#10 resetn <= 1;\n\u0009\u0009#5 d <= 1;\n\u0009\u0009#8 d <= 0;\n\u0009\u0009#2 d <= 1;\n\u0009\u0009#10 d <= 0;\n\u0009end\nendmodule\n
sample_code.tcl = proc find {{basedir .} {filterScript {}}} {\n set oldwd [pwd]\n cd $basedir\n set cwd [pwd]\n set filenames [glob -nocomplain * .*]\n set files {}\n set filt [string length $filterScript]\n foreach filename $filenames {\n if {!$filt || [eval $filterScript [list $filename]]} {\n lappend files [file join $cwd $filename]\n }\n if {[file isdirectory $filename]} {\n set files [concat $files [find $filename $filterScript]]\n }\n }\n cd $oldwd\n return $files\n}\n
sample_code.twig = <!DOCTYPE html>\n<html>\n <head>\n <meta charset="UTF-8">\n <title>{% block title %}Welcome!{% endblock %}</title>\n {% block stylesheets %}{% endblock %}\n </head>\n <body>\n {% block body %}{% endblock %}\n {% block javascripts %}{% endblock %}\n </body>\n</html>\n
sample_code.typescript = /* Game of Life\n * Implemented in TypeScript\n * To learn more about TypeScript, please visit http://www.typescriptlang.org/\n */\n\nnamespace Conway {\n\n\u0009export class Cell {\n\u0009\u0009public row: number;\n\u0009\u0009public col: number;\n\u0009\u0009public live: boolean;\n\n\u0009\u0009constructor(row: number, col: number, live: boolean) {\n\u0009\u0009\u0009this.row = row;\n\u0009\u0009\u0009this.col = col;\n\u0009\u0009\u0009this.live = live;\n\u0009\u0009}\n\u0009}\n\n\u0009export class GameOfLife {\n\u0009\u0009private gridSize: number;\n\u0009\u0009private canvasSize: number;\n\u0009\u0009private lineColor: string;\n\u0009\u0009private liveColor: string;\n\u0009\u0009private deadColor: string;\n\u0009\u0009private initialLifeProbability: number;\n\u0009\u0009private animationRate: number;\n\u0009\u0009private cellSize: number;\n\u0009\u0009private context: CanvasRenderingContext2D;\n\u0009\u0009private world;\n\n\n\u0009\u0009constructor() {\n\u0009\u0009\u0009this.gridSize = 50;\n\u0009\u0009\u0009this.canvasSize = 600;\n\u0009\u0009\u0009this.lineColor = '#cdcdcd';\n\u0009\u0009\u0009this.liveColor = '#666';\n\u0009\u0009\u0009this.deadColor = '#eee';\n\u0009\u0009\u0009this.initialLifeProbability = 0.5;\n\u0009\u0009\u0009this.animationRate = 60;\n\u0009\u0009\u0009this.cellSize = 0;\n\u0009\u0009\u0009this.world = this.createWorld();\n\u0009\u0009\u0009this.circleOfLife();\n\u0009\u0009}\n\n\u0009\u0009public createWorld() {\n\u0009\u0009\u0009return this.travelWorld( (cell : Cell) => {\n\u0009\u0009\u0009\u0009cell.live = Math.random() < this.initialLifeProbability;\n\u0009\u0009\u0009\u0009return cell;\n\u0009\u0009\u0009});\n\u0009\u0009}\n\n\u0009\u0009public circleOfLife() : void {\n\u0009\u0009\u0009this.world = this.travelWorld( (cell: Cell) => {\n\u0009\u0009\u0009\u0009cell = this.world[cell.row][cell.col];\n\u0009\u0009\u0009\u0009this.draw(cell);\n\u0009\u0009\u0009\u0009return this.resolveNextGeneration(cell);\n\u0009\u0009\u0009});\n\u0009\u0009\u0009setTimeout( () => {this.circleOfLife()}, this.animationRate);\n\u0009\u0009}\n\n\u0009\u0009public resolveNextGeneration(cell : Cell) {\n\u0009\u0009\u0009var count = this.countNeighbors(cell);\n\u0009\u0009\u0009var newCell = new Cell(cell.row, cell.col, cell.live);\n\u0009\u0009\u0009if(count < 2 || count > 3) newCell.live = false;\n\u0009\u0009\u0009else if(count == 3) newCell.live = true;\n\u0009\u0009\u0009return newCell;\n\u0009\u0009}\n\n\u0009\u0009public countNeighbors(cell : Cell) {\n\u0009\u0009\u0009var neighbors = 0;\n\u0009\u0009\u0009for(var row = -1; row <=1; row++) {\n\u0009\u0009\u0009\u0009for(var col = -1; col <= 1; col++) {\n\u0009\u0009\u0009\u0009\u0009if(row == 0 && col == 0) continue;\n\u0009\u0009\u0009\u0009\u0009if(this.isAlive(cell.row + row, cell.col + col)) {\n\u0009\u0009\u0009\u0009\u0009\u0009neighbors++;\n\u0009\u0009\u0009\u0009\u0009}\n\u0009\u0009\u0009\u0009}\n\u0009\u0009\u0009}\n\u0009\u0009\u0009return neighbors;\n\u0009\u0009}\n\n\u0009\u0009public isAlive(row : number, col : number) {\n\u0009\u0009\u0009if(row < 0 || col < 0 || row >= this.gridSize || col >= this.gridSize) return false;\n\u0009\u0009\u0009return this.world[row][col].live;\n\u0009\u0009}\n\n\u0009\u0009public travelWorld(callback) {\n\u0009\u0009\u0009var result = [];\n\u0009\u0009\u0009for(var row = 0; row < this.gridSize; row++) {\n\u0009\u0009\u0009\u0009var rowData = [];\n\u0009\u0009\u0009\u0009for(var col = 0; col < this.gridSize; col++) {\n\u0009\u0009\u0009\u0009\u0009rowData.push(callback(new Cell(row, col, false)));\n\u0009\u0009\u0009\u0009}\n\u0009\u0009\u0009\u0009result.push(rowData);\n\u0009\u0009\u0009}\n\u0009\u0009\u0009return result;\n\u0009\u0009}\n\n\u0009\u0009public draw(cell : Cell) {\n\u0009\u0009\u0009if(this.context == null) this.context = this.createDrawingContext();\n\u0009\u0009\u0009if(this.cellSize == 0) this.cellSize = this.canvasSize/this.gridSize;\n\n\u0009\u0009\u0009this.context.strokeStyle = this.lineColor;\n\u0009\u0009\u0009this.context.strokeRect(cell.row * this.cellSize, cell.col*this.cellSize, this.cellSize, this.cellSize);\n\u0009\u0009\u0009this.context.fillStyle = cell.live ? this.liveColor : this.deadColor;\n\u0009\u0009\u0009this.context.fillRect(cell.row * this.cellSize, cell.col*this.cellSize, this.cellSize, this.cellSize);\n\u0009\u0009}\n\n\u0009\u0009public createDrawingContext() {\n\u0009\u0009\u0009var canvas = <HTMLCanvasElement> document.getElementById('conway-canvas');\n\u0009\u0009\u0009if(canvas == null) {\n\u0009\u0009\u0009\u0009\u0009canvas = document.createElement('canvas');\n\u0009\u0009\u0009\u0009\u0009canvas.id = 'conway-canvas';\n\u0009\u0009\u0009\u0009\u0009canvas.width = this.canvasSize;\n\u0009\u0009\u0009\u0009\u0009canvas.height = this.canvasSize;\n\u0009\u0009\u0009\u0009\u0009document.body.appendChild(canvas);\n\u0009\u0009\u0009}\n\u0009\u0009\u0009return canvas.getContext('2d');\n\u0009\u0009}\n\u0009}\n}\n\nvar game = new Conway.GameOfLife();\n
sample_code.typespec = import "@typespec/http";\n\nusing TypeSpec.Http;\n\nmodel Store {\n name: string;\n address: Address;\n}\n\nmodel Address {\n street: string;\n city: string;\n}\n\n@route("/stores")\ninterface Stores {\n list(@query filter: string): Store[];\n read(@path id: Store): Store;\n}
sample_code.vb = Imports System\nImports System.Collections.Generic\n\nModule Module1\n\n Sub Main()\n Dim a As New M8Ball\n\n Do While True\n\n Dim q As String = ""\n Console.Write("ask me about the future... ")\n q = Console.ReadLine()\n\n If q.Trim <> "" Then\n Console.WriteLine("the answer is... {0}", a.getAnswer(q))\n Else\n Exit Do\n End If\n Loop\n\n End Sub\n\nEnd Module\n\nClass M8Ball\n\n Public Answers As System.Collections.Generic.Dictionary(Of Integer, String)\n\n Public Sub New()\n Answers = New System.Collections.Generic.Dictionary(Of Integer, String)\n Answers.Add(0, "It is certain")\n Answers.Add(1, "It is decidedly so")\n Answers.Add(2, "Without a doubt")\n Answers.Add(3, "Yes, definitely")\n Answers.Add(4, "You may rely on ")\n Answers.Add(5, "As I see it, yes")\n Answers.Add(6, "Most likely")\n Answers.Add(7, "Outlook good")\n Answers.Add(8, "Signs point to yes")\n Answers.Add(9, "Yes")\n Answers.Add(10, "Reply hazy, try again")\n Answers.Add(11, "Ask again later")\n Answers.Add(12, "Better not tell you now")\n Answers.Add(13, "Cannot predict now")\n Answers.Add(14, "Concentrate and ask again")\n Answers.Add(15, "Don't count on it")\n Answers.Add(16, "My reply is no")\n Answers.Add(17, "My sources say no")\n Answers.Add(18, "Outlook not so")\n Answers.Add(19, "Very doubtful")\n End Sub\n\n Public Function getAnswer(theQuestion As String) As String\n Dim r As New Random\n Return Answers(r.Next(0, 19))\n End Function\n\nEnd Class\n
sample_code.verilog = `include "first_counter.v"\nmodule first_counter_tb();\n// Declare inputs as regs and outputs as wires\nreg clock, reset, enable;\nwire [3:0] counter_out;\n\n// Initialize all variables\ninitial begin\n $display ("time\\t clk reset enable counter");\n $monitor ("%g\\t %b %b %b %b",\n\u0009 $time, clock, reset, enable, counter_out);\n clock = 1; // initial value of clock\n reset = 0; // initial value of reset\n enable = 0; // initial value of enable\n #5 reset = 1; // Assert the reset\n #10 reset = 0; // De-assert the reset\n #10 enable = 1; // Assert enable\n #100 enable = 0; // De-assert enable\n #5 $finish; // Terminate simulation\nend\n\n// Clock generator\nalways begin\n #5 clock = ~clock; // Toggle clock every 5 ticks\nend\n\n// Connect DUT to test bench\nfirst_counter U_counter (\nclock,\nreset,\nenable,\ncounter_out\n);\n\nendmodule\n
sample_code.xml = <?xml version="1.0"?>\n<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">\n <connectionStrings>\n <add name="MyDB" \n connectionString="value for the deployed Web.config file" \n xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>\n </connectionStrings>\n <system.web>\n <customErrors defaultRedirect="GenericError.htm"\n mode="RemoteOnly" xdt:Transform="Replace">\n <error statusCode="500" redirect="InternalError.htm"/>\n </customErrors>\n </system.web>\n</configuration>
sample_code.yaml = %TAG ! tag:clarkevans.com,2002:\n--- !shape\n # Use the ! handle for presenting\n # tag:clarkevans.com,2002:circle\n- !circle\n center: &ORIGIN {x: 73, y: 129}\n radius: 7\n- !line\n start: *ORIGIN\n finish: { x: 89, y: 102 }\n- !label\n start: *ORIGIN\n color: 0xFFEEBB\n text: Pretty vector drawing.\n