text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.apimanagement.models;

import com.azure.resourcemanager.apimanagement.fluent.models.PortalDelegationSettingsInner;

/** An immutable client-side representation of PortalDelegationSettings. */
public interface PortalDelegationSettings {
    /**
     * Gets the id property: Fully qualified resource Id for the resource.
     *
     * @return the id value.
     */
    String id();

    /**
     * Gets the name property: The name of the resource.
     *
     * @return the name value.
     */
    String name();

    /**
     * Gets the type property: The type of the resource.
     *
     * @return the type value.
     */
    String type();

    /**
     * Gets the url property: A delegation Url.
     *
     * @return the url value.
     */
    String url();

    /**
     * Gets the validationKey property: A base64-encoded validation key to validate, that a request is coming from Azure
     * API Management.
     *
     * @return the validationKey value.
     */
    String validationKey();

    /**
     * Gets the subscriptions property: Subscriptions delegation settings.
     *
     * @return the subscriptions value.
     */
    SubscriptionsDelegationSettingsProperties subscriptions();

    /**
     * Gets the userRegistration property: User registration delegation settings.
     *
     * @return the userRegistration value.
     */
    RegistrationDelegationSettingsProperties userRegistration();

    /**
     * Gets the inner com.azure.resourcemanager.apimanagement.fluent.models.PortalDelegationSettingsInner object.
     *
     * @return the inner object.
     */
    PortalDelegationSettingsInner innerModel();
}

redpajama_set_name: RedPajamaGithub


text:
package fpgatidbits.PlatformWrapper

import Chisel._

// platform wrapper for PYNQ

object PYNQZ1Params extends PlatformWrapperParams {
  val platformName = "PYNQZ1"
  val memAddrBits = 32
  val memDataBits = 64
  val memIDBits = 6
  val memMetaBits = 1
  val numMemPorts = 4
  val sameIDInOrder = true
  val typicalMemLatencyCycles = 32
  val burstBeats = 8  // TODO why cap bursts at 8? AXI can do more
  val coherentMem = false // TODO add CC version of PYNQZ1 as well
}

class PYNQZ1Wrapper(instFxn: PlatformWrapperParams => GenericAccelerator)
  extends AXIPlatformWrapper(PYNQZ1Params, instFxn) {
  val platformDriverFiles = baseDriverFiles ++ Array[String](
    "platform-xlnk.cpp", "xlnkdriver.hpp"
  )
  setName("PYNQZ1Wrapper")
  setModuleName("PYNQZ1Wrapper")
}


text:
'use strict';

import angular, { IController } from 'angular';

class TimeoutModalController implements IController {
	public handleClickOK(): void {
		window.location.href = '/authentication';
	}
}

angular.module('core').controller('TimeoutModalController', TimeoutModalController);


text:
<idea-plugin>
  <extensions defaultExtensionNs="org.intellij.groovy">
    <membersContributor implementation="org.jetbrains.plugins.groovy.ext.spock.SpockMemberContributor"/>
  </extensions>

  <extensions defaultExtensionNs="com.intellij">
    <testFramework implementation="org.jetbrains.plugins.groovy.ext.spock.SpockTestFramework" order="first"/>
    <pom.declarationSearcher implementation="org.jetbrains.plugins.groovy.ext.spock.SpockPomDeclarationSearcher"/>
    <cantBeStatic implementation="org.jetbrains.plugins.groovy.ext.spock.SpockCantBeStaticExtension"/>
  </extensions>
</idea-plugin>


text:
<?php

namespace DataLoader\Db\Table\Row;
use Zend_Db_Table_Row_Abstract as ParentAbstract;

/**
 * @category    TicketEvolution
 * @package     TicketEvolution\Db
 * @subpackage  Table
 * @copyright   Copyright (c) 2013 J Cobb. (http://jcobb.org)
 * @license     http://choosealicense.com/licenses/bsd-3-clause/ BSD (3-Clause) License
 */
abstract class AbstractRow extends ParentAbstract
{
    /**
     * Allows pre-insert logic to be applied to row.
     * Subclasses may override this method.
     *
     * It is used here to ensure that we set the info for the created & modified
     * informational columns
     *
     * @return void
     */
    protected function _insert()
    {
        $this->_setModificationInfo();
        $this->_setCreatedInfo();
    }

    /**
     * Allows pre-update logic to be applied to row.
     * Subclasses may override this method.
     *
     * It is used here to ensure that we set the info for the modified
     * informational columns and do not mess with the created info column(s)
     *
     * @return void
     */
    protected function _update()
    {
        $this->_setModificationInfo();
        $this->_protectCreatedInfo();
    }

    /**
     * Allows pre-delete logic to be applied to row.
     * Subclasses may override this method.
     *
     * It is used here to ensure that we set the info for the modified
     * informational columns and do not mess with the created info column(s)
     * and to ensure that all we really do is set the status of this row to
     * inactive rather than actually deleting the row.
     *
     * @return void
     */
    protected function _delete()
    {
        $this->_setModificationInfo();
        $this->_protectCreatedInfo();

        // Get the "status" column and set it to 0 (false)
        $statusColumn = $this->_getTable()->getStatusColumn();
        $this->__set($statusColumn, 0);
    }

    /**
     * Ensures that created info is set
     *
     * @return void
     */
    protected function _setCreatedInfo()
    {
        // Make sure we don't try and set an empty createdDate
        // We don't need have to check if it exists because MySQL will add it
        // automatically but we will for consistency
        if (!isset($this->_data['createdDate'])
           || empty($this->_data['createdDate'])) {
            $this->__set('createdDate', date('c'));
        }
    }

    /**
     * Ensures that modification info is set
     *
     * @return void
     */
    protected function _setModificationInfo()
    {
        // Make sure we have a lastModifiedDate
        if (!isset($this->_data['lastModifiedDate'])
           || empty($this->_data['lastModifiedDate'])) {
            $this->__set('lastModifiedDate', date('c'));
        }
    }

    /**
     * Ensures that we do not change created information.
     *
     * @return void
     */
    protected function _protectCreatedInfo()
    {
        $this->__unset('createdDate');
    }

}


text:
package net.my4x.utils;

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import net.my4x.utils.model.SVGFile;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.xml.sax.SAXException;

public class SVGUtils {

	public SVGFile parse(final InputStream input) {

		try {
			final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder;
			dBuilder = dbFactory.newDocumentBuilder();
			return new SVGFile(dBuilder.parse(input));

		} catch (final ParserConfigurationException e) {
			throw new RuntimeException(e);
		} catch (final SAXException e) {
			throw new RuntimeException(e);
		} catch (final IOException e) {
			throw new RuntimeException(e);
		}

	}

	public static void svgToPng(final InputStream svgIn, final OutputStream pngOut) throws TranscoderException,
			IOException {
		final PNGTranscoder t = new PNGTranscoder();

		// Create the transcoder input.
		final TranscoderInput input = new TranscoderInput(svgIn);

		// Create the transcoder output.
		final TranscoderOutput output = new TranscoderOutput(pngOut);

		// Save the image.
		t.transcode(input, output);
	}

}


text:
Client library for Quicksold REST API

## Installation and Usage
```bash
npm install --save @datafire/quicksold_location
```
```js
let quicksold_location = require('@datafire/quicksold_location').create();

.then(data => {
  console.log(data);
});
```

## Description

## Actions

### wgs84ToOsgb36UsingGET
wgs84ToOsgb36

```js
quicksold_location.wgs84ToOsgb36UsingGET({
  "latitude": "",
  "longitude": ""
}, context)
```

#### Input
* input `object`
  * latitude **required** `string`: latitude
  * longitude **required** `string`: longitude

#### Output
* output [ApiResponse](#apiresponse)

## Definitions

### ApiResponse
* ApiResponse `object`
  * data `object`
  * error `string`
  * errors `object`
  * message `string`
  * path `string`
  * status `integer`
  * timestamp `integer`


text:
<?php
namespace Hx\Route;

interface InputParamInterface {

	/**
	 * Get array value
	 */
	public function getData();

	/**
	 * Get indexed based array
	 */
	public function getArgs();
}
?>


text:
@interface PodsDummy_Pods_AnalyticsTests : NSObject
@end
@implementation PodsDummy_Pods_AnalyticsTests
@end


text:
package us.kbase.auth2.service;

import java.util.Set;

import us.kbase.auth2.lib.identity.IdentityProviderConfig;

public interface AuthConfig {

	//TODO JAVADOC

	SLF4JAutoLogger getLogger();
	Set<IdentityProviderConfig> getIdentityProviderConfigs();
	String getMongoHost();
	String getMongoDatabase();
	String getMongoUser();
	char[] getMongoPwd();
}


text:
<!DOCTYPE html>
<html lang="<?=$lang?>" class="no-js">

<meta charset="utf-8"/>
<title><?=get_title($title)?></title>

<?php if(isset($favicon)): ?><link rel="shortcut icon" href="<?=$favicon?>"/><?php endif; ?>

<?php foreach($stylesheets as $val): ?>
<link rel="stylesheet" type="text/css" href="<?=$val?>" />
<?php endforeach; ?>

    <?=$header?>
    <?=$main?>
    <?=$footer?>

<?php if(isset($jquery)):?><?php endif;?>

<?php if(isset($javascript_include)): foreach($javascript_include as $val): ?>

<?php endforeach; endif; ?>

<?php if(isset($google_analytics)): ?>

<?php endif; ?>


text:
package org.apache.poi.ss.formula.functions;

import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.ValueEval;

/**
 * Convenience base class for any function which must take three or four
 * arguments
 *
 * @author Josh Micich
 */
abstract class Var3or4ArgFunction implements Function3Arg, Function4Arg {

	public final ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
		switch (args.length) {
			case 3:
				return evaluate(srcRowIndex, srcColumnIndex, args[0], args[1], args[2]);
			case 4:
				return evaluate(srcRowIndex, srcColumnIndex, args[0], args[1], args[2], args[3]);
		}
		return ErrorEval.VALUE_INVALID;
	}
}


text:
package com.frameworkset.orm.platform;

/*

 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.frameworkset.orm.engine.model.Domain;
import com.frameworkset.orm.engine.model.SchemaType;

/**
 * SAP DB Platform implementation.
 *
 * @author Martin Poeschl
 * @version $Id: PlatformSapdbImpl.java,v 1.4 2004/02/22 06:27:19 jmcnally Exp $
 */
public class PlatformSapdbImpl extends PlatformDefaultImpl
{
    /**
     * Default constructor.
     */
    public PlatformSapdbImpl()
    {
        super();
        initialize();
    }

    /**
     * Initializes db specific domain mapping.
     */
    private void initialize()
    {
        setSchemaDomainMapping(new Domain(SchemaType.BIT, "FIXED", "1", "0"));
        setSchemaDomainMapping(new Domain(SchemaType.TINYINT, "CHAR BYTE"));
        setSchemaDomainMapping(new Domain(SchemaType.BIGINT, "FIXED", "38", "0"));
        setSchemaDomainMapping(new Domain(SchemaType.DOUBLE, "DOUBLE PRECISION"));
        setSchemaDomainMapping(new Domain(SchemaType.NUMERIC, "DECIMAL"));
        setSchemaDomainMapping(new Domain(SchemaType.LONGVARCHAR, "LONG VARCHAR"));
        setSchemaDomainMapping(new Domain(SchemaType.BINARY, "CHAR(254) BYTE"));
        setSchemaDomainMapping(new Domain(SchemaType.VARBINARY, "LONG BYTE"));
        setSchemaDomainMapping(new Domain(SchemaType.LONGVARBINARY, "LONG BYTE"));
        setSchemaDomainMapping(new Domain(SchemaType.JAVA_OBJECT, "LONG BYTE"));
        setSchemaDomainMapping(new Domain(SchemaType.BLOB, "LONG BYTE"));
        setSchemaDomainMapping(new Domain(SchemaType.CLOB, "LONG UNICODE"));
        setSchemaDomainMapping(new Domain(SchemaType.BOOLEANINT, "SMALLINT"));
        setSchemaDomainMapping(new Domain(SchemaType.BOOLEANCHAR, "CHAR"));
    }

    /**
     * @see Platform#getNativeIdMethod()
     */
    public String getNativeIdMethod()
    {
        return Platform.SEQUENCE;
    }

    /**
     * @see Platform#getAutoIncrement()
     */
    public String getAutoIncrement()
    {
        return "DEFAULT SERIAL";
    }

}


text:
<!DOCTYPE html>

        <title>Timestamp microservice</title>

        Example usage:

            https://freecodecamp-lubien-timestamp.herokuapp.com/December%2015,%202015

            https://freecodecamp-lubien-timestamp.herokuapp.com/1450137600

        Example output:

            { "unix": 1450137600, "natural": "December 15, 2015" }


text:
title: Unity - Timer using co-routine
tags: unity
shortdesc: Advanced Timer usable as a coroutine for Unity.
---

Here is a simple and powerful **Timer class**.

Features:

- A duration (it will wait n seconds then execute the piece of code)
- Repeat this timer until the object is destroyed or stopped
- The callback, a ``System.Action`` delegate to execute some code with a very simple syntax

Enjoy :).

[See on Gist](https://gist.github.com/valryon/9915075)

```csharp
// 2014 - Pixelnest Studio
using System;
using System.Collections;
using UnityEngine;

/// <summary>
/// Ready to use timers for coroutines
/// </summary>
/// <summary>
  /// Ready to use timers for coroutines
  /// </summary>
  public class Timer
  {
    /// <summary>
    /// Simple timer, no reference, wait and then execute something
    /// </summary>
    /// <param name="duration"></param>
    /// <param name="callback"></param>
    /// <returns></returns>
    public static IEnumerator Start(float duration, Action callback)
    {
      return Start(duration, false, callback);
    }

    /// <summary>
    /// Simple timer, no reference, wait and then execute something
    /// </summary>
    /// <param name="duration"></param>
    /// <param name="repeat"></param>
    /// <param name="callback"></param>
    /// <returns></returns>
    public static IEnumerator Start(float duration, bool repeat, Action callback)
    {
      do
      {
        yield return new WaitForSeconds(duration);

        if (callback != null)
          callback();

      } while (repeat);
    }

    public static IEnumerator StartRealtime(float time, System.Action callback)
    {
      float start = Time.realtimeSinceStartup;
      while (Time.realtimeSinceStartup < start + time)
      {
        yield return null;
      }

      if (callback != null) callback();
    }

    public static IEnumerator NextFrame(Action callback)
    {
      yield return new WaitForEndOfFrame();

      if (callback != null)
        callback();
    }
  }
```

Exemple

```csharp
const float duration = 3f;

// Simple creation: can't be stopped even if lopping
//--------------------------------------------
StartCoroutine(Timer.Start(duration, true, () =>
{
  // Do something at the end of the 3 seconds (duration)
  //...
}));

// Launch the timer
StartCoroutine(t.Start());

// Ask to stop it next frame
t.Stop();
```


text:
jest.mock("../../../db/getDB", () => ({
  getDB: () => ({
    getInstallation: () => Promise.resolve({ repos: {} }),
  }),
}))

const mockContents = jest.fn(() => Promise.resolve("// empty"))
const mockUserRepoAccess = jest.fn(() => Promise.resolve(true))
jest.mock("../../../github/lib/github_helpers", () => ({
  canUserWriteToRepo: mockUserRepoAccess,
  getGitHubFileContents: mockContents,
  doesPRExist: () => Promise.resolve(true),
}))

const mockRunner = jest.fn(() => Promise.resolve("OK"))
jest.mock("../../../danger/danger_runner", () => ({
  runDangerForInstallation: mockRunner,
}))

import { readFileSync } from "fs"
import { resolve } from "path"
import { dangerRunForRules } from "../../../danger/danger_run"
import { setupForRequest } from "../github_runner"
import { runPRRun } from "../handlers/pr"

const apiFixtures = resolve(__dirname, "fixtures")
const fixture = (file: string) => JSON.parse(readFileSync(resolve(apiFixtures, file), "utf8"))

jest.mock("../createPRDSL", () => ({ createPRDSL: () => Promise.resolve({}) }))

it("runs a Dangerfile for a PR with a local", async () => {
  mockContents.mockImplementationOnce(() => Promise.resolve("fail('dangerfile')"))
  mockContents.mockImplementationOnce(() => Promise.resolve("fail('dangerfile')"))
  mockContents.mockImplementationOnce(() => Promise.resolve("fail('dangerfile')"))
  mockContents.mockImplementationOnce(() => Promise.resolve("fail('dangerfile')"))

  const body = fixture("pull_request_opened.json")
  const settings = await setupForRequest({ body, headers: { "X-GitHub-Delivery": "12345" } } as any, {})

  const run = dangerRunForRules(
    "pull_request",
    "opened",
    {
      pull_request: "dangerfile.pr",
    },
    body
  )[0]

  await runPRRun("eventName", [run], settings, "token", body.pull_request)
  const call = mockRunner.mock.calls[0]
  expect(mockRunner).toBeCalled()
  expect(call[1]).toEqual(["fail('dangerfile')"])
  expect(call[2]).toEqual(["dangerfile.pr"])
})

describe("when someone edits the dangerfile", () => {
  beforeEach(() => {
    mockRunner.mockReset()
  })

  it("fails a run when a Dangerfile is edited by someone without access", async () => {
    mockContents.mockImplementationOnce(() => Promise.resolve("// safe"))
    mockContents.mockImplementationOnce(() => Promise.resolve("// unsafe"))
    mockUserRepoAccess.mockImplementationOnce(() => Promise.resolve(false))

    const body = fixture("pull_request_opened.json")
    const settings = await setupForRequest({ body, headers: { "X-GitHub-Delivery": "12345" } } as any, {})

    const run = dangerRunForRules(
      "pull_request",
      "opened",
      {
        pull_request: "dangerfile.no.access.pr",
      },
      body
    )[0]

    const results = await runPRRun("eventName", [run], settings, "token", body.pull_request)
    expect(mockRunner).not.toBeCalled()
    expect(results!.messages[0].message).toContain("Not running Danger rules")
  })

  it("runs a Dangerfile when edited by someone with access", async () => {
    mockContents.mockImplementationOnce(() => Promise.resolve("// safe"))
    mockContents.mockImplementationOnce(() => Promise.resolve("// unsafe"))
    mockUserRepoAccess.mockImplementationOnce(() => Promise.resolve(true))

    const body = fixture("pull_request_opened.json")
    const settings = await setupForRequest({ body, headers: { "X-GitHub-Delivery": "12345" } } as any, {})

    const run = dangerRunForRules(
      "pull_request",
      "opened",
      {
        pull_request: "dangerfile.no.access.pr",
      },
      body
    )[0]

    await runPRRun("eventName", [run], settings, "token", body.pull_request)
    expect(mockRunner).toBeCalled()
  })
})


text:
var should = require('should');
var sinon = require('sinon');
var knockout = require('../knockout-2.3.0');
var MainViewModel = require('./Contacts').MainViewModel;
var NewContactViewModel = require('./Contacts').NewContactViewModel;

describe('MainViewModel', function () {
    it('test should call getContacts and update contacts', function () {
        // Setup
        var ironman = {}, hulk = {};
        var service = { getContacts: function () { } };
        var mock = sinon.mock(service);
        mock.expects('getContacts').callsArgWith(0, [ironman, hulk]).once();

        // Exercise
        var viewModel = new MainViewModel(knockout, service);
        viewModel.updateContacts();

        // Verify
        mock.verify();
        viewModel.contacts().should.be.ok;
        viewModel.contacts().length.should.equal(2);
        viewModel.contacts()[0].should.equal(ironman);
        viewModel.contacts()[1].should.equal(hulk);
    });
});

describe('NewContactViewModel', function () {
    it('test should call addContact', function () {
        // Setup
        var service = { addContact: function () { } };
        var mock = sinon.mock(service);
        var firstName = 'Thor', lastName = 'Odinson', email = 'thor@avengers.com';
        mock.expects('addContact').withArgs(firstName, lastName, email).once();

        // Exercise
        var viewModel = new NewContactViewModel(knockout, service);
        viewModel.firstName(firstName);
        viewModel.lastName(lastName);
        viewModel.email(email);
        viewModel.add();

        // Verify
        mock.verify();
    });

    it('test should clear properties', function () {
        // Setup
        var service = { addContact: function () { } };

        // Exercise
        var viewModel = new NewContactViewModel(knockout, service);
        viewModel.firstName('Thor');
        viewModel.lastName('Odinson');
        viewModel.email('thor@avengers.com');
        viewModel.add();

        // Verify
        viewModel.firstName().should.not.be.ok;
        viewModel.lastName().should.not.be.ok;
        viewModel.email().should.not.be.ok;
    });

    it('test should call MainViewModel.updateContacts', function () {
        // Setup
        var service = { addContact: function (firstName, lastName, email, callback) { callback(); } };
        var mainViewModel = { updateContacts: function () { } };
        var mock = sinon.mock(mainViewModel);
        mock.expects('updateContacts').once();

        // Exercise
        var viewModel = new NewContactViewModel(knockout, service, mainViewModel);
        viewModel.firstName('Thor');
        viewModel.lastName('Odinson');
        viewModel.email('thor@avengers.com');
        viewModel.add();

        // Verify
        mock.verify();
    });
});


text:
package org.w3c.domts.level2.core;

import org.w3c.dom.*;

import org.w3c.domts.DOMTestCase;
import org.w3c.domts.DOMTestDocumentBuilderFactory;

/**
 *     The "removeAttributeNS(namespaceURI,localName)" removes an attribute by
 *    local name and namespace URI.  If the removed attribute has a
 *    default value it is immediately replaced.  The replacing attribute has the same
 *    namespace URI and local name, as well as the original prefix.
 *
 *    Retrieve the attribute named "emp:local" from emp:address
 *    node, then remove the "emp:local"
 *    attribute by invoking the "removeAttributeNS(namespaceURI,localName)" method.
 *    The "emp:local" attribute has a default value defined in the
 *    DTD file, that value should immediately replace the old
 *    value.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#ID-ElRemAtNS
* @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=238
*/
public final class removeAttributeNS02 extends DOMTestCase {

   /**
    * Constructor.
    * @param factory document factory, may not be null
    * @throws org.w3c.domts.DOMTestIncompatibleException Thrown if test is not compatible with parser configuration
    */
   public removeAttributeNS02(final DOMTestDocumentBuilderFactory factory)  throws org.w3c.domts.DOMTestIncompatibleException {

      org.w3c.domts.DocumentBuilderSetting[] settings =
          new org.w3c.domts.DocumentBuilderSetting[] {
org.w3c.domts.DocumentBuilderSetting.namespaceAware,
org.w3c.domts.DocumentBuilderSetting.validating
        };
        DOMTestDocumentBuilderFactory testFactory = factory.newInstance(settings);
        setFactory(testFactory);

    //
    //   check if loaded documents are supported for content type
    //
    String contentType = getContentType();
    preload(contentType, "staffNS", true);
    }

   /**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
   public void runTest() throws Throwable {
      Document doc;
      NodeList elementList;
      Node testAddr;
      Attr addrAttr;
      String attr;
      String namespaceURI;
      String localName;
      String prefix;
      doc = (Document) load("staffNS", true);
      elementList = doc.getElementsByTagName("emp:address");
      testAddr = elementList.item(0);
      ((Element) /*Node */testAddr).removeAttributeNS("http://www.nist.gov", "local1");
      elementList = doc.getElementsByTagName("emp:address");
      testAddr = elementList.item(0);
      addrAttr = ((Element) /*Node */testAddr).getAttributeNodeNS("http://www.nist.gov", "local1");
      attr = ((Element) /*Node */testAddr).getAttributeNS("http://www.nist.gov", "local1");
      namespaceURI = addrAttr.getNamespaceURI();
      localName = addrAttr.getLocalName();
      prefix = testAddr.getPrefix();
      assertEquals("attr", "FALSE", attr);
      assertEquals("uri", "http://www.nist.gov", namespaceURI);
      assertEquals("lname", "local1", localName);
      assertEquals("prefix", "emp", prefix);
      }
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
   public String getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/removeAttributeNS02";
   }
   /**
    * Runs this test from the command line.
    * @param args command line arguments
    */
   public static void main(final String[] args) {
        DOMTestCase.doMain(removeAttributeNS02.class, args);
   }
}


text:
package io.cucumber.core.runner;

import io.cucumber.core.stepexpression.ExpressionArgument;
import io.cucumber.plugin.event.Argument;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

final class DefinitionArgument implements Argument {

    private final ExpressionArgument argument;
    private final io.cucumber.cucumberexpressions.Group group;

    private DefinitionArgument(ExpressionArgument argument) {
        this.argument = argument;
        this.group = argument.getGroup();
    }

    static List<Argument> createArguments(List<io.cucumber.core.stepexpression.Argument> match) {
        List<Argument> args = new ArrayList<>();
        for (io.cucumber.core.stepexpression.Argument argument : match) {
            if (argument instanceof ExpressionArgument) {
                ExpressionArgument expressionArgument = (ExpressionArgument) argument;
                args.add(new DefinitionArgument(expressionArgument));
            }
        }
        return args;
    }

    @Override
    public String getParameterTypeName() {
        return argument.getParameterTypeName();
    }

    @Override
    public String getValue() {
        return group == null ? null : group.getValue();
    }

    @Override
    public int getStart() {
        return group == null ? -1 : group.getStart();
    }

    @Override
    public int getEnd() {
        return group == null ? -1 : group.getEnd();
    }

    @Override
    public io.cucumber.plugin.event.Group getGroup() {
        return group == null ? null : new Group(group);
    }

    private static final class Group implements io.cucumber.plugin.event.Group {

        private final io.cucumber.cucumberexpressions.Group group;
        private final List<io.cucumber.plugin.event.Group> children;

        private Group(io.cucumber.cucumberexpressions.Group group) {
            this.group = group;
            children = group.getChildren().stream()
                    .map(Group::new)
                    .collect(Collectors.toList());
        }

        @Override
        public Collection<io.cucumber.plugin.event.Group> getChildren() {
            return children;
        }

        @Override
        public String getValue() {
            return group.getValue();
        }

        @Override
        public int getStart() {
            return group.getStart();
        }

        @Override
        public int getEnd() {
            return group.getEnd();
        }

    }

}


text:
package se.pesd.jdbc.test;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import COM.safe.fmeobjects.FMEException;
import COM.safe.fmeobjects.FMEGenerateInfo;
import COM.safe.fmeobjects.FMEObjects;
import COM.safe.fmeobjects.IFMESession;
import COM.safe.fmeobjects.IFMEStringArray;

public class TestDriver {

	public static void main(String[] args) throws SQLException, FMEException {
		Properties prop = new Properties();
		prop.setProperty("user", "åäö");
		Driver d = new se.pesd.jdbc.sysinfo.Driver();
		Connection conn = d.connect("jdbc:sepesd:sysinfo", prop);

		//ResultSet result = conn.getMetaData().getTables("", "", "", null);

		Statement stmnt = conn.createStatement();
		stmnt.execute("select * from \"sysinfo\".\"charset\"");
		ResultSet result = stmnt.getResultSet();
		ResultSetMetaData metadata = result.getMetaData();
		for (int i = 0; i < metadata.getColumnCount(); i++) {
			System.out.printf("%s ", metadata.getColumnName(i+1));
		}
		System.out.println();
		while(result.next()) {
			System.out.printf("%-4d ", result.getRow());
			for (int i = 1; i <= metadata.getColumnCount(); i++) {
				Object o = result.getString(i);
				if(result.wasNull())
					System.out.printf("null ");
				else
					System.out.printf("%s (%s) ",  o, o.getClass().getName());
			}
			System.out.println();
		}

		FMEGenerateInfo info = new FMEGenerateInfo();
		System.out.println();
		System.out.printf("%s\n%s\n", info.parameterFileName, info.workspaceFileName);

		IFMESession session = FMEObjects.createSession();
		IFMEStringArray properties = session.createStringArray();
		session.getAllProperties(properties);
		for (int i = 0; i < properties.entries(); i++)
			System.out.println(properties.getElement(i));

	}

}


text:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

use AppBundle\Entity\User;

class AuthorizationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('email')->add('password');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(['data_class' => User::class, 'validation_groups' => ['authorization']]);
    }
}


text:
<!DOCTYPE html>

  <title>navbar</title>
  <?php $this->load->view('general.php'); ?>

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

            </button>

 Home

Activities

Stories

Chat

About Us

                <?php if (($this->session->userdata('first_name'))== true){?>

<?= $this->session->userdata('first_name'); ?>

My profile

My activiy

My stories

Logout

                <?php }else{ ?>
                <li class="dropdown <?php if(isset($posts['errors'])){ echo"open";} ?>">Sign In

                                <form class="" action="/index.php/Activity/login" method="post">
                                <input type="hidden" name="<?= $this->security->get_csrf_token_name() ?>" value="<?= $this->security->get_csrf_hash() ?>" />

                                        Email
                                        <input class="form-control" name="email" id="username" type="text">

                                        Password
                                        <input class="form-control" name="password" id="password" type="password">

                                      <?php if(isset($posts['errors'])){
                                          echo"
".$posts['errors']."
";
                                      } ?>
                                    <button type="submit" name="loginSubmit" id="btnLogin" class="btn btn-success btn-sm">Login</button>
                                </form>

                <?php }
                if (($this->session->userdata('first_name'))== true){ ?>

Logout

                <?php }else{ ?>

Register

                <?php } ?>

<?php $this->load->view('activity_bar.php'); ?>

Forget password

We are three new web developers, who share the same passion for solving problems with coding. We met on this special coding school RE/Start Network and we gained priceless knowledge and life experiences. Now we are embarking in our next journey as web developers.

Forgot Password?

Please enter your email or phone number to search for your account.

                    <form id="register-form" action="/index.php/Activity/check_email" role="form" autocomplete="off" class="form" method="post">
                      <input type="hidden" name="<?= $this->security->get_csrf_token_name() ?>" value="<?= $this->security->get_csrf_hash() ?>" />

                          <input id="email" name="email" placeholder="email address" class="form-control"  type="email" autocomplete>

                        <?php if (isset($error)){ echo "
".$error."
"; } ?>

                        <input name="submit" class="btn btn-lg btn-primary btn-block" value="Search" type="submit">

                      <input type="hidden" class="hide" name="token" id="token" value="">
                    </form>

<?php $this->load->view('footer.php'); ?>


text:
<?php

namespace Front\Controller\Checkout;
use Oculus\Engine\Controller;

class Shippingmethod extends Controller {
    public function index() {
        $data = $this->theme->language('checkout/checkout');

        $this->theme->model('account/address');

        if ($this->customer->isLogged() && isset($this->session->data['shipping_address_id'])) {
            $shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
        } elseif (isset($this->session->data['guest'])) {
            $shipping_address = $this->session->data['guest']['shipping'];
        }

        if (!empty($shipping_address)) {

            // Shipping Methods
            $quote_data = array();

            $this->theme->model('setting/module');

            $results = $this->model_setting_module->getModules('shipping');

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->theme->model('shipping/' . $result['code']);

                    $quote = $this->{'model_shipping_' . $result['code']}->getQuote($shipping_address);

                    if ($quote) {
                        $quote_data[$result['code']] = array(
                            'title'      => $quote['title'],
                            'quote'      => $quote['quote'],
                            'sort_order' => $quote['sort_order'],
                            'error'      => $quote['error']
                        );
                    }
                }
            }

            $sort_order = array();

            foreach ($quote_data as $key => $value) {
                $sort_order[$key] = $value['sort_order'];
            }

            array_multisort($sort_order, SORT_ASC, $quote_data);

            $this->session->data['shipping_methods'] = $quote_data;
        }

        if (empty($this->session->data['shipping_methods'])) {
            $data['error_warning'] = sprintf($this->language->get('lang_error_no_shipping'), $this->url->link('content/contact'));
        } else {
            $data['error_warning'] = '';
        }

        if (isset($this->session->data['shipping_methods'])) {
            $data['shipping_methods'] = $this->session->data['shipping_methods'];
        } else {
            $data['shipping_methods'] = array();
        }

        if (isset($this->session->data['shipping_method']['code'])) {
            $data['code'] = $this->session->data['shipping_method']['code'];
        } else {
            $data['code'] = '';
        }

        if (isset($this->session->data['comment'])) {
            $data['comment'] = $this->session->data['comment'];
        } else {
            $data['comment'] = '';
        }

        $data = $this->theme->listen(__CLASS__, __FUNCTION__, $data);

        $this->response->setOutput($this->theme->view('checkout/shipping_method', $data));
    }

    public function validate() {
        $this->theme->language('checkout/checkout');

        $json = array();

        // Validate if shipping is required. If not the customer should not have reached this page.
        if (!$this->cart->hasShipping()) {
            $json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
        }

        // Validate if shipping address has been set.
        $this->theme->model('account/address');

        if ($this->customer->isLogged() && isset($this->session->data['shipping_address_id'])) {
            $shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
        } elseif (isset($this->session->data['guest'])) {
            $shipping_address = $this->session->data['guest']['shipping'];
        }

        if (empty($shipping_address)) {
            $json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
        }

        // Validate cart has products and has stock.
        if ((!$this->cart->hasProducts() && empty($this->session->data['giftcards'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
            $json['redirect'] = $this->url->link('checkout/cart');
        }

        // Validate minimum quantity requirments.
        $products = $this->cart->getProducts();

        foreach ($products as $product) {
            $product_total = 0;

            foreach ($products as $product_2) {
                if ($product_2['product_id'] == $product['product_id']) {
                    $product_total+= $product_2['quantity'];
                }
            }

            if ($product['minimum'] > $product_total) {
                $json['redirect'] = $this->url->link('checkout/cart');

                break;
            }
        }

        if (!$json) {
            if (!isset($this->request->post['shipping_method'])) {
                $json['error']['warning'] = $this->language->get('lang_error_shipping');
            } else {
                $shipping = explode('.', $this->request->post['shipping_method']);

                if (!isset($shipping[0]) || !isset($shipping[1]) || !isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {
                    $json['error']['warning'] = $this->language->get('lang_error_shipping');
                }
            }

            if (!$json) {
                $shipping = explode('.', $this->request->post['shipping_method']);

                $this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];

                $this->session->data['comment'] = strip_tags($this->request->post['comment']);
            }
        }

        $json = $this->theme->listen(__CLASS__, __FUNCTION__, $json);

        $this->response->setOutput(json_encode($json));
    }
}


text:
@interface SequenceUtils()

@property (atomic, strong) NSLock *lock;
@property (atomic, assign) NSUInteger idsCounter;

@end

@implementation SequenceUtils

+ (SequenceUtils *)sharedInstance
{
    static SequenceUtils *instance = nil;
    static dispatch_once_t dispatch_once_block;

    dispatch_once(&dispatch_once_block, ^{
        instance = [SequenceUtils new];
        instance.idsCounter = 0;
        instance.lock = [NSLock new];
    });

    return instance;
}

- (NSUInteger)getNextId
{
    [self.lock lock];
    self.idsCounter +=1;
    [self.lock unlock];

    return self.idsCounter;
}

@end


text:
package com.saituo.order.commons.enumeration.entity;

import com.saituo.order.commons.enumeration.ValueEnum;

public enum ComplainCd implements ValueEnum<Integer> {

	NOT_COMPLAIN(0, "未投诉"), COMPLAINED(1, "已投诉");

	ComplainCd(Integer value, String name) {
		this.name = name;
		this.value = value;
	}

	private String name;

	private Integer value;

	/**
	 * 获取资源类型名称
	 *
	 * @return String
	 */
	public String getName() {
		return name;
	}

	/**
	 * 获取资源类型值
	 *
	 * @return Integer
	 */
	public Integer getValue() {
		return value;
	}
}


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "DatastorePool.h"
#include "Nebula.h"
#include "NebulaLog.h"
#include "DatastoreTemplate.h"

#include <stdexcept>

/* -------------------------------------------------------------------------- */
/* There is a default datastore boostrapped by the core:                      */
/* The first 100 IDs are reserved for system datastores. Regular ones start   */
/* from ID 100                                                                */
/* -------------------------------------------------------------------------- */

const string DatastorePool::SYSTEM_DS_NAME = "system";
const int    DatastorePool::SYSTEM_DS_ID   = 0;

const string DatastorePool::DEFAULT_DS_NAME = "default";
const int    DatastorePool::DEFAULT_DS_ID   = 1;

const string DatastorePool::FILE_DS_NAME = "files";
const int    DatastorePool::FILE_DS_ID   = 2;

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

DatastorePool::DatastorePool(
        SqlDB * db,
        const vector<const SingleAttribute *>& _inherit_attrs,
        vector<const SingleAttribute *>& encrypted_attrs) :
    PoolSQL(db, Datastore::table)

{
    ostringstream oss;
    string        error_str;

    vector<const SingleAttribute *>::const_iterator it;

    for (it = _inherit_attrs.begin(); it != _inherit_attrs.end(); it++)
    {
        inherit_attrs.push_back((*it)->value());
    }

    if (get_lastOID() == -1) //lastOID is set in PoolSQL::init_cb
    {
        DatastoreTemplate * ds_tmpl;
        int      rc;
        set<int> cluster_ids;

        cluster_ids.insert(ClusterPool::DEFAULT_CLUSTER_ID);

        // ---------------------------------------------------------------------
        // Create the system datastore
        // ---------------------------------------------------------------------

        oss << "NAME   = " << SYSTEM_DS_NAME << endl
            << "TYPE   = SYSTEM_DS" << endl
            << "TM_MAD = ssh";

        ds_tmpl = new DatastoreTemplate;
        rc = ds_tmpl->parse_str_or_xml(oss.str(), error_str);

        if( rc < 0 )
        {
            goto error_bootstrap;
        }

        allocate(UserPool::ONEADMIN_ID,
                GroupPool::ONEADMIN_ID,
                UserPool::oneadmin_name,
                GroupPool::ONEADMIN_NAME,
                0137,
                ds_tmpl,
                &rc,
                cluster_ids,
                error_str);

        if( rc < 0 )
        {
            goto error_bootstrap;
        }

        // ---------------------------------------------------------------------
        // Create the default datastore
        // ---------------------------------------------------------------------
        oss.str("");

        oss << "NAME   = "   << DEFAULT_DS_NAME << endl
            << "TYPE   = IMAGE_DS" << endl
            << "DS_MAD = fs" << endl
            << "TM_MAD = ssh";

        ds_tmpl = new DatastoreTemplate;
        rc = ds_tmpl->parse_str_or_xml(oss.str(), error_str);

        if( rc < 0 )
        {
            goto error_bootstrap;
        }

        allocate(UserPool::ONEADMIN_ID,
                GroupPool::ONEADMIN_ID,
                UserPool::oneadmin_name,
                GroupPool::ONEADMIN_NAME,
                0137,
                ds_tmpl,
                &rc,
                cluster_ids,
                error_str);

        if( rc < 0 )
        {
            goto error_bootstrap;
        }

        // ---------------------------------------------------------------------
        // Create the default file datastore
        // ---------------------------------------------------------------------
        oss.str("");

        oss << "NAME   = "   << FILE_DS_NAME << endl
            << "TYPE   = FILE_DS" << endl
            << "DS_MAD = fs" << endl
            << "TM_MAD = ssh";

        ds_tmpl = new DatastoreTemplate;
        rc = ds_tmpl->parse_str_or_xml(oss.str(), error_str);

        if( rc < 0 )
        {
            goto error_bootstrap;
        }

        allocate(UserPool::ONEADMIN_ID,
                GroupPool::ONEADMIN_ID,
                UserPool::oneadmin_name,
                GroupPool::ONEADMIN_NAME,
                0137,
                ds_tmpl,
                &rc,
                cluster_ids,
                error_str);

        if( rc < 0 )
        {
            goto error_bootstrap;
        }

        // User created datastores will start from ID 100
        set_lastOID(99);
    }

    // Parse encrypted attributes
    DatastoreTemplate::parse_encrypted(encrypted_attrs);

    return;

error_bootstrap:
    oss.str("");
    oss << "Error trying to create default datastore: " << error_str;
    NebulaLog::log("DATASTORE",Log::ERROR,oss);

    throw runtime_error(oss.str());
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int DatastorePool::allocate(
        int                 uid,
        int                 gid,
        const string&       uname,
        const string&       gname,
        int                 umask,
        DatastoreTemplate * ds_template,
        int *               oid,
        const set<int>      &cluster_ids,
        string&             error_str)
{
    Datastore * ds;

    int    db_oid;
    string name;

    ostringstream oss;

    ds = new Datastore(uid, gid, uname, gname, umask,
            ds_template, cluster_ids);

    // -------------------------------------------------------------------------
    // Check name & duplicates
    // -------------------------------------------------------------------------

    ds->get_template_attribute("NAME", name);

    if ( !PoolObjectSQL::name_is_valid(name, error_str) )
    {
        goto error_name;
    }

    // Check for duplicates
    db_oid = exist(name);

    if( db_oid != -1 )
    {
        goto error_duplicated;
    }

    *oid = PoolSQL::allocate(ds, error_str);

    if ( *oid != -1 )
    {
        Nebula& nd        = Nebula::instance();
        ImageManager * im = nd.get_imagem();

        if (im != 0 ) //Do not monitor during bootstrap
        {
            im->monitor_datastore(*oid);
        }
    }

    return *oid;

error_duplicated:
    oss << "NAME is already taken by DATASTORE " << db_oid << ".";
    error_str = oss.str();

error_name:
    delete ds;
    *oid = -1;

    return *oid;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int DatastorePool::drop(PoolObjectSQL * objsql, string& error_msg)
{
    Datastore * datastore = static_cast<Datastore*>(objsql);

    int rc;

    if( datastore->images_size() > 0 )
    {
        ostringstream oss;
        oss << "Datastore " << datastore->get_oid() << " is not empty.";
        error_msg = oss.str();
        NebulaLog::log("DATASTORE", Log::ERROR, error_msg);

        return -3;
    }

    rc = datastore->drop(db);

    if( rc != 0 )
    {
        error_msg = "SQL DB error";
        rc = -1;
    }

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int DatastorePool::disk_attribute(int ds_id, VirtualMachineDisk * disk)
{
    Datastore * ds = get_ro(ds_id);

    if (ds == 0)
    {
        return -1;
    }

    ds->disk_attribute(disk, inherit_attrs);

    ds->unlock();

    return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml.Data;

namespace MonocleGiraffe.Helpers
{
    public abstract class IncrementalCollection<T> : Portable.Helpers.IncrementalCollection<T>, ISupportIncrementalLoading
    {
        public bool HasMoreItems
        {
            get
            {
                return HasMoreItemsImpl();
            }
        }

        public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            return AsyncInfo.Run((c) => LoadMoreItemsAsync(c, count));
        }

        private async Task<LoadMoreItemsResult> LoadMoreItemsAsync(CancellationToken c, uint count)
        {
            var ret = await LoadMoreAsync(c, count);
            return new LoadMoreItemsResult { Count = count };
        }
    }
}


text:
from kivy.logger import Logger
from kivy.clock import Clock

import netcheck

class Request():
    def __init__(self, payload, callback=None):
        self.payload = payload
        if callback is not None:
            self.callback = callback
        else:
            self.callback = lambda *args, **kwargs: None

MAX_ATTEMPTS=2

class MockTwitter():
    def __init__(self, credentials, toasty=True):
        self.credentials = credentials
        self._auth_state = None
        self._error_msg = 'OMg omg testin'

    def tweet(self, status='test', callback=None):
        t = Request(payload=status, callback=callback)
        t.process = self._process_tweet
        self.request = t
        self._process_request()

    def tweet_photo(self, status, path, callback=None, resize=True, jpeg=False):
        t = Request(payload=status, callback=callback)
        t.process = self._process_tweet
        self.request = t
        self._process_request()

    def _process_tweet(self, tweet):
        Logger.info('Tweeting {}'.format(tweet.payload))
        def fake_response(dt):
            Logger.info('in tweet callback')
            tweet.callback(True, 'Tweet was successful')
        Clock.schedule_once(fake_response, 0.5)

    def _process_request(self):
        if not netcheck.connection_available():
            netcheck.ask_connect(self._connection_callback)
        elif not self._auth_state == 'authenticated':
            self._authenticate()
        else:
            self.request.process(self.request)

    def _connection_callback(self, connected):
        Logger.info('in twitter connection callback: ' + str(connected))
        if connected:
            self._process_request()
        else:
            self._fail()

    def _authenticate(self):
        self._auth_state = 'authenticated'
        self._process_request()

    def _ask_retry(self):
        self.retry_prompt(self._fail_callback)

    def retry_prompt(self, callback):
        ''' monkey patch here to implement a real prompt'''
        callback(False)

    def set_retry_prompt(self, fn):
        self.retry_prompt = fn

    def _fail(self):
        self._auth_state = None
        self._ask_retry()

    def _fail_callback(self, retry):
        Logger.info('in fail callback ' + str(retry))
        if retry:
            self._tries = MAX_ATTEMPTS
            self._process_request()
        else:
            self._processing=False
            self._tries = 0
            self.request.callback(False, self._error_msg)
            self.request = None


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using MarkdownEdit.MarkdownConverters;
using MarkdownEdit.Properties;
using NReco.PdfGenerator;
using static System.String;

namespace MarkdownEdit.Models
{
    public static class Markdown
    {
        private static readonly IMarkdownConverter CommonMarkConverter = new CommonMarkConverter();
        private static readonly IMarkdownConverter GitHubMarkdownConverter = new MarkdigMarkdownConverter();
        private static readonly IMarkdownConverter CustomMarkdownConverter = new CustomMarkdownConverter();

        private const string PandocGithubMarkdownFormatOptions =
            "gfm"
            + "-emoji"
            + "+tex_math_dollars";

        private const string PandocCommonMarkFormatOptions =
            "markdown_strict"
            + "+fenced_code_blocks"
            + "+backtick_code_blocks"
            + "+intraword_underscores"
            + "+strikeout"
            + "+pipe_tables"
            + "+tex_math_dollars";

        private static string PandocMarkdownFormat
            => App.UserSettings.GitHubMarkdown
                ? PandocGithubMarkdownFormatOptions
                : PandocCommonMarkFormatOptions;

        public static string ToHtml(string markdown)
        {
            var ast = AbstractSyntaxTree.GenerateAbstractSyntaxTree(markdown);
            markdown = markdown.ConvertEmojis(ast);
            var converter = GetMarkdownConverter();
            return converter.ConvertToHtml(markdown);
        }

        public static string Wrap(string text)
            => Reformat(text);

        public static string WrapWithLinkReferences(string text)
            => Reformat(text, "--reference-links");

        public static string Unwrap(string text)
            => Reformat(text, "--wrap=none --atx-headers");

        public static string FromHtml(string path)
            => Pandoc(null, $"-f html -t {PandocMarkdownFormat} --wrap=none \"{path}\"");

        public static string FromHtmlText(string text) => Pandoc(text, $"-f html -t {PandocMarkdownFormat} --wrap=none");

        private static IMarkdownConverter GetMarkdownConverter()
        {
            return IsNullOrWhiteSpace(App.UserSettings.CustomMarkdownConverter)
                ? GitHubMarkdownConverter
                : CustomMarkdownConverter;
        }

        public static string FromMicrosoftWord(string path)
            => Pandoc(null, $"-f docx -t {PandocMarkdownFormat} \"{path}\"");

        public static string ToMicrosoftWord(string markdown, string path) =>
            Pandoc(ResolveImageUrls(ToHtml(markdown)), $"-f html -t docx -o \"{path}\"");

        public static byte[] HtmlToPdf(string html)
        {
            var converter = new HtmlToPdfConverter
            {
                CustomWkHtmlPageArgs = " --no-stop-slow-scripts" +
                                       " --javascript-delay 5000" +
                                       " --disable-smart-shrinking"
            };
            return converter.GeneratePdf(ResolveImageUrls(html));
        }

        public static string Pandoc(string text, string args)
        {
            var pandoc = ProcessStartInfo("pandoc.exe", args, text != null);

            return ResultFromExecuteProcess(text, pandoc);
        }

        public static string ResultFromExecuteProcess(string text, ProcessStartInfo startInfo)
        {
            using (var process = Process.Start(startInfo))
            {
                if (process == null)
                {
                    Notify.Alert("Error starting process");
                    return text;
                }
                if (text != null)
                {
                    var utf8 = new StreamWriter(process.StandardInput.BaseStream, Encoding.UTF8);
                    utf8.Write(text);
                    utf8.Close();
                }
                var result = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                if (process.ExitCode != 0)
                {
                    var msg = process.StandardError.ReadToEnd();
                    result = IsNullOrWhiteSpace(msg) ? "empty error response" : msg;
                }
                return result;
            }
        }

        private static string Reformat(string text, string options = "")
        {
            var tuple = SeperateFrontMatter(text);
            var fromFormat = PandocMarkdownFormat;
            var toFormat = fromFormat + "-escaped_line_breaks";
            var result = Pandoc(tuple.Item2, $"-f {fromFormat} -t {toFormat} {options}").Replace(@"\$", "$");
            return tuple.Item1 + result;
        }

        public static ProcessStartInfo ProcessStartInfo(string fileName, string arguments, bool redirectInput)
        {
            return new ProcessStartInfo
            {
                FileName = fileName,
                Arguments = arguments,
                RedirectStandardInput = redirectInput,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8,
                UseShellExecute = false,
                CreateNoWindow = true,
                WorkingDirectory = Utility.AssemblyFolder()
            };
        }

        public static Tuple<string, string> SeperateFrontMatter(string text)
        {
            if (Regex.IsMatch(text, @"^---\s*"))
            {
                var matches = Regex.Matches(text, @"^(?:---)|(?:\.\.\.)\s*$", RegexOptions.Multiline);
                if (matches.Count < 2) return Tuple.Create(Empty, text);
                var match = matches[1];
                var index = match.Index + match.Groups[0].Value.Length + 1;
                while (index < text.Length && char.IsWhiteSpace(text[index])) index += 1;
                index = Math.Min(text.Length, index);
                return Tuple.Create(text.Substring(0, index), text.Substring(index));
            }
            else
            {
                // Hack for non-standard front-matter
                const string formatHack = @"^<\!--\s*MDE\s*-->\s*$";
                var match = Regex.Match(text, formatHack, RegexOptions.Multiline);
                if (match.Success)
                {
                    var index = match.Index + match.Groups[0].Value.Length + 1;
                    while (index < text.Length && char.IsWhiteSpace(text[index])) index += 1;
                    return Tuple.Create(text.Substring(0, index), text.Substring(index));
                }
            }

            return Tuple.Create(Empty, text);
        }

        public static string SuggestFilenameFromTitle(string markdown)
        {
            var result = SeperateFrontMatter(markdown);
            if (IsNullOrEmpty(result.Item1)) return Empty;
            var pattern = new Regex(@"title:\s*(.+)", RegexOptions.Multiline);
            var match = pattern.Match(markdown);
            var title = match.Success ? match.Groups[1].Value : Empty;
            if (IsNullOrEmpty(title)) return Empty;
            var filename = DateTime.Now.ToString("yyyy-MM-dd-") + title.ToSlug(true);
            return filename;
        }

        private static string ResolveImageUrls(string html)
        {
            var filename = Settings.Default.LastOpenFile.StripOffsetFromFileName();
            if (IsNullOrWhiteSpace(filename)) return html;
            var folder = Path.GetDirectoryName(filename);
            if (IsNullOrWhiteSpace(folder)) return html;

            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var images = doc.DocumentNode.SelectNodes("//img");
            if (images == null) return html;
            var modified = false;

            foreach (var image in images)
            {
                var src = image.GetAttributeValue("src", "");
                if (IsNullOrWhiteSpace(src)) continue;
                if (src.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) continue;
                var path = Path.Combine(folder, src);
                image.SetAttributeValue("src", path);
                modified = true;
            }

            return modified ? doc.DocumentNode.WriteTo() : html;
        }

        public static string RemoveYamlFrontMatter(string markdown)
        {
            var tuple = SeperateFrontMatter(markdown);
            return tuple.Item2;
        }
    }
}


text:
<?php

/**
 * Created by PhpStorm.
 * User: gseidel
 * Date: 06.03.18
 * Time: 15:19
 */

namespace Enhavo\Bundle\AppBundle\Reference;

use Doctrine\ORM\Proxy\Proxy;
use Doctrine\Common\Persistence\ObjectRepository;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class SyliusTargetClassResolver implements TargetClassResolverInterface
{
    use ContainerAwareTrait;

    public function resolveClass($object)
    {
        $className = get_class($object);
        if($object instanceof Proxy) {
            $className = get_parent_class($object);
        }

        $resources = $this->container->getParameter('sylius.resources');
        foreach($resources as $type => $resource) {
            if($resource['classes']['model'] == $className) {
                return $type;
            }
        }
        return null;
    }

    public function find($id, $class)
    {
        $repository = $this->getRepository($class);
        if($repository === null) {
            return null;
        }
        return $repository->find($id);
    }

    /**
     * @param $class
     * @return ObjectRepository
     */
    private function getRepository($class)
    {
        $resources = $this->container->getParameter('sylius.resources');
        if(!array_key_exists($class, $resources)) {
            return null;
        }

        $type = explode('.', $class);
        $repositoryService = sprintf('%s.repository.%s', $type[0], $type[1]);
        /** @var ObjectRepository $repository */
        $repository = $this->container->get($repositoryService);
        return $repository;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.jena.query.Syntax (Apache Jena ARQ)</title>
<meta name="date" content="2015-12-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.jena.query.Syntax

Packages that use Syntax

Package
Description

org.apache.jena.query

ARQ - A query engine for Jena, implementing SPARQL.

org.apache.jena.sparql.lang

org.apache.jena.sparql.serializer

org.apache.jena.sparql.util

org.apache.jena.update

Uses of Syntax in org.apache.jena.query

Fields in org.apache.jena.query declared as Syntax

Modifier and Type
Field and Description

static Syntax
Syntax.defaultQuerySyntax

The name of the default query language for query parsing.

static Syntax
Syntax.defaultSyntax

The system default syntax

static Syntax
Syntax.defaultUpdateSyntax

The name of the default update language for update parsing.

static Syntax
Syntax.syntaxAlgebra

static Syntax
Syntax.syntaxARQ

The query syntax for extended SPARQL

static Syntax
Syntax.syntaxSPARQL

The query syntax currently that is standardized, published, SPARQL - the "default SPARQL Query"

static Syntax
Syntax.syntaxSPARQL_10

The syntax that the DAWG working group defined

static Syntax
Syntax.syntaxSPARQL_11

The syntax that the SPARQL working group has defined

Fields in org.apache.jena.query with type parameters of type Syntax

Modifier and Type
Field and Description

static TranslationTable<Syntax>
Syntax.querySyntaxNames

static TranslationTable<Syntax>
Syntax.updateSyntaxNames

Methods in org.apache.jena.query that return Syntax

Modifier and Type
Method and Description

Syntax
Query.getSyntax()

static Syntax
Syntax.guessFileSyntax(String url)

static Syntax
Syntax.guessFileSyntax(String url,
               Syntax defaultSyntax)

Gues the syntax (query and update) based on filename

static Syntax
Syntax.guessQueryFileSyntax(String url)

Guess the query syntax based on file name

static Syntax
Syntax.guessQueryFileSyntax(String url,
                    Syntax defaultSyntax)

Guess the query syntax based on file name

static Syntax
Syntax.guessUpdateFileSyntax(String url)

Guess the update syntax based on file name

static Syntax
Syntax.guessUpdateFileSyntax(String url,
                     Syntax defaultSyntax)

Guess the update syntax based on file name

static Syntax
Syntax.lookup(String s)

static Syntax
Syntax.make(String uri)

Methods in org.apache.jena.query with parameters of type Syntax

Modifier and Type
Method and Description

static Query
QueryFactory.create(String queryString,
      String baseURI,
      Syntax syntax)

Create a query from the given string by calling the parser.

static QueryExecution
QueryExecutionFactory.create(String queryStr,
      Syntax syntax)

Create a QueryExecution

static Query
QueryFactory.create(String queryString,
      Syntax syntax)

Create a query from the given string with the

static QueryExecution
QueryExecutionFactory.create(String queryStr,
      Syntax syntax,
      Dataset dataset)

Create a QueryExecution to execute over the Dataset.

static QueryExecution
QueryExecutionFactory.create(String queryStr,
      Syntax syntax,
      Dataset dataset,
      QuerySolution initialBinding)

Create a QueryExecution over a Dataset given some initial values of variables.

static QueryExecution
QueryExecutionFactory.create(String queryStr,
      Syntax lang,
      Model model)

Create a QueryExecution to execute over the Model.

static QueryExecution
QueryExecutionFactory.create(String queryStr,
      Syntax syntax,
      Model model,
      QuerySolution initialBinding)

Create a QueryExecution to execute over the Model,
 given some initial values of variables.

static QueryExecution
QueryExecutionFactory.create(String queryStr,
      Syntax syntax,
      QuerySolution initialBinding)

Create a QueryExecution given some initial values of variables.

static Syntax
Syntax.guessFileSyntax(String url,
               Syntax defaultSyntax)

Gues the syntax (query and update) based on filename

static Syntax
Syntax.guessQueryFileSyntax(String url,
                    Syntax defaultSyntax)

Guess the query syntax based on file name

static Syntax
Syntax.guessUpdateFileSyntax(String url,
                     Syntax defaultSyntax)

Guess the update syntax based on file name

static Query
QueryFactory.parse(Query query,
     String queryString,
     String baseURI,
     Syntax syntaxURI)

Parse a query from the given string by calling the parser.

static Query
QueryFactory.read(String url,
    FileManager filemanager,
    String baseURI,
    Syntax langURI)

Read a query from a file.

static Query
QueryFactory.read(String url,
    String baseURI,
    Syntax langURI)

Read a query from a file.

static Query
QueryFactory.read(String url,
    Syntax langURI)

Read a query from a file.

void
Query.serialize(org.apache.jena.atlas.io.IndentedLineBuffer buff,
         Syntax outSyntax)

Format the query

void
Query.serialize(org.apache.jena.atlas.io.IndentedWriter writer,
         Syntax outSyntax)

Format the query

void
Query.serialize(OutputStream out,
         Syntax syntax)

Output the query

String
Query.serialize(Syntax syntax)

Convert the query to a string in the given syntax

void
Query.setSyntax(Syntax syntax)

String
Query.toString(Syntax syntax)

Uses of Syntax in org.apache.jena.sparql.lang

Methods in org.apache.jena.sparql.lang with parameters of type Syntax

Modifier and Type
Method and Description

boolean
UpdateParserFactory.accept(Syntax syntax)

Return true if this factory can create a parser for the given syntax

boolean
SPARQLParserFactory.accept(Syntax syntax)

Return true if this factory can create a parser for the given syntax

void
SPARQLParserRegistry.add(Syntax syntax,
   SPARQLParserFactory f)

Register the given parser factory for the specified syntax.

void
UpdateParserRegistry.add(Syntax syntax,
   UpdateParserFactory f)

Register the given parser factory for the specified syntax.

static void
SPARQLParserRegistry.addFactory(Syntax syntax,
          SPARQLParserFactory f)

Register the given parser factory for the specified syntax.

static void
UpdateParserRegistry.addFactory(Syntax syntax,
          UpdateParserFactory f)

Register the given parser factory for the specified syntax.

static boolean
UpdateParser.canParse(Syntax syntaxURI)

static boolean
SPARQLParser.canParse(Syntax syntaxURI)

boolean
SPARQLParserRegistry.containsFactory(Syntax syntax)

Checks whether a parser factory is registered for the given syntax

boolean
UpdateParserRegistry.containsFactory(Syntax syntax)

Checks whether a parser factory is registered for the given syntax

static boolean
SPARQLParserRegistry.containsParserFactory(Syntax syntax)

Checks whether a parser factory is registered for the given syntax

static boolean
UpdateParserRegistry.containsParserFactory(Syntax syntax)

Checks whether a parser factory is registered for the given syntax

UpdateParser
UpdateParserFactory.create(Syntax syntax)

Return a parser for the given syntax

SPARQLParser
SPARQLParserFactory.create(Syntax syntax)

Return a parser for the given syntax

SPARQLParser
SPARQLParserRegistry.createParser(Syntax syntax)

Return a suitable parser for the given syntax

UpdateParser
UpdateParserRegistry.createParser(Syntax syntax)

Return a suitable parser for the given syntax

static UpdateParser
UpdateParser.createParser(Syntax syntaxURI)

static SPARQLParser
SPARQLParser.createParser(Syntax syntaxURI)

static SPARQLParserFactory
SPARQLParserRegistry.findFactory(Syntax syntax)

Return a suitable factory for the given syntax

static UpdateParserFactory
UpdateParserRegistry.findFactory(Syntax syntax)

Return a suitable factory for the given syntax

SPARQLParserFactory
SPARQLParserRegistry.getFactory(Syntax syntax)

Return a suitable parser factory for the given syntax

UpdateParserFactory
UpdateParserRegistry.getFactory(Syntax syntax)

Return a suitable parser factory for the given syntax

static SPARQLParser
SPARQLParserRegistry.parser(Syntax syntax)

Return a suitable parser for the given syntax

static UpdateParser
UpdateParserRegistry.parser(Syntax syntax)

Return a suitable parser for the given syntax

void
SPARQLParserRegistry.remove(Syntax syntax)

Unregister the parser factory associated with the given syntax

void
UpdateParserRegistry.remove(Syntax syntax)

Unregister the parser factory associated with the given syntax

static void
SPARQLParserRegistry.removeFactory(Syntax syntax)

Unregister the parser factory associated with the given syntax

static void
UpdateParserRegistry.removeFactory(Syntax syntax)

Unregister the parser factory associated with the given syntax

Uses of Syntax in org.apache.jena.sparql.serializer

Methods in org.apache.jena.sparql.serializer with parameters of type Syntax

Modifier and Type
Method and Description

boolean
UpdateSerializerFactory.accept(Syntax syntax)

Return true if this factory can create a serializer for the given syntax

boolean
QuerySerializerFactory.accept(Syntax syntax)

Return true if this factory can create a serializer for the given syntax

void
SerializerRegistry.addQuerySerializer(Syntax syntax,
                  QuerySerializerFactory factory)

Adds a query serializer factory for the given syntax

void
SerializerRegistry.addUpdateSerializer(Syntax syntax,
                   UpdateSerializerFactory factory)

Adds an update serializer factory for the given syntax

boolean
SerializerRegistry.containsQuerySerializer(Syntax syntax)

Gets whether a query serializer factory is registered for the given
 syntax

boolean
SerializerRegistry.containsUpdateSerializer(Syntax syntax)

Gets whether an update serializer factory is registered for the given
 syntax

UpdateSerializer
UpdateSerializerFactory.create(Syntax syntax,
      Prologue prologue,
      org.apache.jena.atlas.io.IndentedWriter writer)

Return a serializer for the given syntax

QueryVisitor
QuerySerializerFactory.create(Syntax syntax,
      Prologue prologue,
      org.apache.jena.atlas.io.IndentedWriter writer)

Return a serializer for the given syntax

QueryVisitor
QuerySerializerFactory.create(Syntax syntax,
      SerializationContext context,
      org.apache.jena.atlas.io.IndentedWriter writer)

Returns a serializer for the given syntax using an existing serialization
 context, this method should only be called for serializing sub-queries
 where the outer context must be honoured

QuerySerializerFactory
SerializerRegistry.getQuerySerializerFactory(Syntax syntax)

Gets the query serializer factory for the given syntax which may be null
 if there is none registered

UpdateSerializerFactory
SerializerRegistry.getUpdateSerializerFactory(Syntax syntax)

Gets the update serializer factory for the given syntax which may be null
 if there is none registered

void
SerializerRegistry.removeQuerySerializer(Syntax syntax)

Removes the query serializer factory for the given syntax

void
SerializerRegistry.removeUpdateSerializer(Syntax syntax)

Removes the update serializer factory for the given syntax

Uses of Syntax in org.apache.jena.sparql.util

Methods in org.apache.jena.sparql.util with parameters of type Syntax

Modifier and Type
Method and Description

static void
QueryOutputUtils.printQuery(org.apache.jena.atlas.io.IndentedWriter out,
          Query query,
          Syntax syntax)

Uses of Syntax in org.apache.jena.update

Methods in org.apache.jena.update with parameters of type Syntax

Modifier and Type
Method and Description

static UpdateRequest
UpdateFactory.create(String string,
      String baseURI,
      Syntax syntax)

Create an UpdateRequest by parsing from a string.

static UpdateRequest
UpdateFactory.create(String string,
      Syntax syntax)

Create an UpdateRequest by parsing from a string.

static void
UpdateFactory.parse(UpdateRequest request,
     String updateString,
     String baseURI,
     Syntax syntax)

static void
UpdateFactory.parse(UpdateRequest request,
     String updateString,
     Syntax syntax)

static void
UpdateAction.parseExecute(UsingList usingList,
            DatasetGraph dataset,
            InputStream input,
            Binding inputBinding,
            String baseURI,
            Syntax syntax)

Parse update operations into a GraphStore by parsing from an InputStream.

static void
UpdateAction.parseExecute(UsingList usingList,
            DatasetGraph dataset,
            InputStream input,
            QuerySolution inputBinding,
            String baseURI,
            Syntax syntax)

Parse update operations into a GraphStore by parsing from an InputStream.

static void
UpdateAction.parseExecute(UsingList usingList,
            DatasetGraph dataset,
            InputStream input,
            String baseURI,
            Syntax syntax)

Parse update operations into a GraphStore by parsing from an InputStream.

static void
UpdateAction.parseExecute(UsingList usingList,
            DatasetGraph dataset,
            InputStream input,
            Syntax syntax)

Parse update operations into a GraphStore by parsing from an InputStream.

static void
UpdateAction.parseExecute(UsingList usingList,
            DatasetGraph dataset,
            String fileName,
            Binding inputBinding,
            String baseURI,
            Syntax syntax)

Parse update operations into a GraphStore by reading it from a file

static void
UpdateAction.parseExecute(UsingList usingList,
            DatasetGraph dataset,
            String fileName,
            QuerySolution inputBinding,
            String baseURI,
            Syntax syntax)

Parse update operations into a GraphStore by reading it from a file

static void
UpdateAction.parseExecute(UsingList usingList,
            DatasetGraph dataset,
            String fileName,
            String baseURI,
            Syntax syntax)

Parse update operations into a GraphStore by reading it from a file

static void
UpdateAction.parseExecute(UsingList usingList,
            DatasetGraph dataset,
            String fileName,
            Syntax syntax)

Parse update operations into a GraphStore by reading it from a file

static UpdateRequest
UpdateFactory.read(InputStream input,
    String baseURI,
    Syntax syntax)

Create an UpdateRequest by parsing from an InputStream.

static UpdateRequest
UpdateFactory.read(InputStream input,
    Syntax syntax)

Create an UpdateRequest by parsing from an InputStream.

static UpdateRequest
UpdateFactory.read(String fileName,
    String baseURI,
    Syntax syntax)

Create an UpdateRequest by reading it from a file

static UpdateRequest
UpdateFactory.read(String fileName,
    Syntax syntax)

Create an UpdateRequest by reading it from a file

static UpdateRequest
UpdateFactory.read(UsingList usingList,
    InputStream input,
    String baseURI,
    Syntax syntax)

Create an UpdateRequest by parsing from an InputStream.

static UpdateRequest
UpdateFactory.read(UsingList usingList,
    InputStream input,
    Syntax syntax)

Create an UpdateRequest by parsing from an InputStream.

static UpdateRequest
UpdateFactory.read(UsingList usingList,
    String fileName,
    String baseURI,
    Syntax syntax)

Create an UpdateRequest by reading it from a file

static UpdateRequest
UpdateFactory.read(UsingList usingList,
    String fileName,
    Syntax syntax)

Create an UpdateRequest by reading it from a file

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Licenced under the Apache License, Version 2.0


text:
namespace PhotoShare.Client.Core.Dtos
{
    public class AlbumRoleDto
    {
        public string Username { get; set; }

        public string AlbumName { get; set; }
    }
}


text:
#include "qabstractfloat_p.h"
#include "qanyuri_p.h"
#include "qboolean_p.h"
#include "qbuiltintypes_p.h"
#include "qcommonnamespaces_p.h"
#include "qcommonvalues_p.h"
#include "qliteral_p.h"
#include "qatomicstring_p.h"

#include "qnodefns_p.h"

QT_BEGIN_NAMESPACE

using namespace QPatternist;

Item NameFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item node(m_operands.first()->evaluateSingleton(context));

    if(node)
    {
        const QXmlName name(node.asNode().name());

        if(name.isNull())
            return CommonValues::EmptyString;
        else
            return AtomicString::fromValue(context->namePool()->toLexical(name));
    }
    else
        return CommonValues::EmptyString;
}

Item LocalNameFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item node(m_operands.first()->evaluateSingleton(context));

    if(node)
    {
        const QXmlName name(node.asNode().name());

        if(name.isNull())
            return CommonValues::EmptyString;
        else
            return AtomicString::fromValue(context->namePool()->stringForLocalName(name.localName()));
    }
    else
        return CommonValues::EmptyString;
}

Item NamespaceURIFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item node(m_operands.first()->evaluateSingleton(context));

    if(node)
    {
        const QXmlName name(node.asNode().name());

        if(name.isNull())
            return CommonValues::EmptyAnyURI;
        else
            return toItem(AnyURI::fromValue(context->namePool()->stringForNamespace(name.namespaceURI())));
    }
    else
        return CommonValues::EmptyAnyURI;
}

Item NumberFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item item(m_operands.first()->evaluateSingleton(context));

    if(!item)
        return CommonValues::DoubleNaN;

    const Item val(cast(item, context));
    Q_ASSERT(val);

    if(val.as<AtomicValue>()->hasError())
        return CommonValues::DoubleNaN;
    else
        return val;
}

Expression::Ptr NumberFN::typeCheck(const StaticContext::Ptr &context,
                                    const SequenceType::Ptr &reqType)
{
    const Expression::Ptr me(FunctionCall::typeCheck(context, reqType));
    const ItemType::Ptr sourceType(m_operands.first()->staticType()->itemType());

    if(BuiltinTypes::xsDouble->xdtTypeMatches(sourceType))
    {
        /* The operand is already xs:double, no need for fn:number(). */
        return m_operands.first()->typeCheck(context, reqType);
    }
    else if(prepareCasting(context, sourceType))
        return me;
    else
    {
        /* Casting to xs:double will never succeed and we would always return NaN.*/
        return wrapLiteral(CommonValues::DoubleNaN, context, this)->typeCheck(context, reqType);
    }
}

bool LangFN::isLangMatch(const QString &candidate, const QString &toMatch)
{
    if(QString::compare(candidate, toMatch, Qt::CaseInsensitive) == 0)
        return true;

    return candidate.startsWith(toMatch, Qt::CaseInsensitive)
           && candidate.length() > toMatch.length()
           && candidate.at(toMatch.length()) == QLatin1Char('-');
}

Item LangFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item langArg(m_operands.first()->evaluateSingleton(context));
    const QString lang(langArg ? langArg.stringValue() : QString());

    const QXmlName xmlLang(StandardNamespaces::xml, StandardLocalNames::lang, StandardPrefixes::xml);
    const QXmlNodeModelIndex langNode(m_operands.at(1)->evaluateSingleton(context).asNode());

    const QXmlNodeModelIndex::Iterator::Ptr ancestors(langNode.iterate(QXmlNodeModelIndex::AxisAncestorOrSelf));
    QXmlNodeModelIndex ancestor(ancestors->next());

    while(!ancestor.isNull())
    {
        const QXmlNodeModelIndex::Iterator::Ptr attributes(ancestor.iterate(QXmlNodeModelIndex::AxisAttribute));
        QXmlNodeModelIndex attribute(attributes->next());

        while(!attribute.isNull())
        {
            Q_ASSERT(attribute.kind() == QXmlNodeModelIndex::Attribute);

            if(attribute.name() == xmlLang)
            {
                if(isLangMatch(attribute.stringValue(), lang))
                    return CommonValues::BooleanTrue;
                else
                    return CommonValues::BooleanFalse;
            }

            attribute = attributes->next();
        }

        ancestor = ancestors->next();
    }

    return CommonValues::BooleanFalse;
}

Item RootFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item arg(m_operands.first()->evaluateSingleton(context));

    if(arg)
        return arg.asNode().root();
    else
        return Item();
}

SequenceType::Ptr RootFN::staticType() const
{
    if(m_operands.isEmpty())
        return makeGenericSequenceType(BuiltinTypes::node, Cardinality::exactlyOne());
    else
        return makeGenericSequenceType(BuiltinTypes::node, m_operands.first()->staticType()->cardinality().toWithoutMany());
}

QT_END_NAMESPACE


text:
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"

require File.expand_path("../dummy/config/environment.rb",  __FILE__)
require "rails/test_help"

Rails.backtrace_cleaner.remove_silencers!

# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

# Load fixtures from the engine
if ActiveSupport::TestCase.method_defined?(:fixture_path=)
  ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
end

require "capybara"
require "capybara/rails"

class ActiveSupport::IntegrationCase < ActiveSupport::TestCase
  include Capybara::DSL
  include Rails.application.routes.url_helpers
end


text:
require File.expand_path("../spec_helper", File.dirname(__FILE__))
require 'minitest/autorun'
require 'docodoco_jp'
require 'yaml'

DocodocoJp::api_host = "localhost:9292"

describe DocodocoJp do
  before do
    test_yaml = YAML.load_file(File.expand_path("../../fixtures/test_apikey.yml", File.dirname(__FILE__)))
    @key1 = test_yaml["apikey1"]
    @key2 = test_yaml["apikey2"]
  end

  describe "configure" do
    it "default_config" do
      docodoco_jp = DocodocoJp.new(@key1, @key2)
      assert_equal DocodocoJp.default_config, docodoco_jp.config
    end
    it "custom_config" do
      options = {
        ssl: false,
        faraday_log: true,
        charset: "euc_jp",
        response_type: :json
      }
      docodoco_jp = DocodocoJp.new(@key1, @key2, options)
      assert_equal options, docodoco_jp.config
    end
  end

  describe "check_user_api" do
    it "normality" do
      docodoco_jp = DocodocoJp.new(@key1, @key2, {ssl: false})
      result, _ = docodoco_jp.check_user()
      assert_equal result, true
    end

    it "invalid user" do
      docodoco_jp = DocodocoJp.new("--fuga--", "--hoge--", {ssl: false})
      result, _ = docodoco_jp.check_user()
      assert_equal false, result
    end

    it "normality with error" do
      docodoco_jp = DocodocoJp.new(@key1, @key2, {ssl: false})
      result, _ = docodoco_jp.check_user!()
      assert_equal true, result
    end

    it "invalid user with error" do
      docodoco_jp = DocodocoJp.new("--fuga--", "--hoge--", {ssl: false})
      assert_raises(DocodocoJp::ApiKeyInvalid) {
        _, _ = docodoco_jp.check_user!()
      }
    end
  end

  describe "search_api" do
    it "normality" do
      docodoco_jp = DocodocoJp.new(@key1, @key2, {ssl: false})
      result = docodoco_jp.search()
      result.keys.each do |key|
        assert_equal true, SEARCH_API_RESPONSE_KEYS.include?(key)
      end
    end

    it "invalid ipaddr" do
      assert_raises(DocodocoJp::IPv4ValidationError) {
        docodoco_jp = DocodocoJp.new(@key1, @key2, {ssl: false})
        _ = docodoco_jp.search("hogehoge")
      }
    end
  end
end

__END__


text:
.browsehappy {
  margin: 0.2em 0;
  background: #ccc;
  color: #000;
  padding: 0.2em 0;
}

.btn-file {
  position: relative;
  overflow: hidden;
}
.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  font-size: 100px;
  text-align: right;
  filter: alpha(opacity=0);
  opacity: 0;
  outline: none;
  background: white;
  cursor: inherit;
  display: block;
}

tr {
  border:none;
}
.row_number {
  color: #ff7f4f;
  margin-right: 10px;
  height:20px;
}

.text_colored {
  font-family: Consolas,monaco,monospace;
}
body {
  padding: 0;
}

/* Everything but the jumbotron gets side spacing for mobile first views */
.header,
.marketing,
.footer {
  padding-left: 15px;
  padding-right: 15px;
}

/* Custom page header */
.header {
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 10px;
}
/* Make the masthead heading the same height as the navigation */
.header h3 {
  margin-top: 0;
  margin-bottom: 0;
  line-height: 40px;
  padding-bottom: 19px;
}

/* Custom page footer */
.footer {
  padding-top: 19px;
  color: #777;
  border-top: 1px solid #e5e5e5;
}

.container-narrow > hr {
  margin: 30px 0;
}

/* Main marketing message and sign up button */
.jumbotron {
  text-align: center;
  border-bottom: 1px solid #e5e5e5;
}
.jumbotron .btn {
  font-size: 21px;
  padding: 14px 24px;
}

/* Supporting marketing content */
.marketing {
  margin: 40px 0;
}
.marketing p + h4 {
  margin-top: 28px;
}

/* Responsive: Portrait tablets and up */
@media screen and (min-width: 768px) {
  .container {
    max-width: 730px;
  }

  /* Remove the padding we set earlier */
  .header,
  .marketing,
  .footer {
    padding-left: 0;
    padding-right: 0;
  }
  /* Space out the masthead */
  .header {
    margin-bottom: 30px;
  }
  /* Remove the bottom border on the jumbotron for visual effect */
  .jumbotron {
    border-bottom: 0;
  }
}


text:
'use strict';

angular.module('creamApp')
    .controller('ActionController', function ($scope, $state, Action, ActionSearch, ParseLinks) {

        $scope.actions = [];
        $scope.predicate = 'id';
        $scope.reverse = true;
        $scope.page = 1;
        $scope.loadAll = function() {
            Action.query({page: $scope.page - 1, size: 20, sort: [$scope.predicate + ',' + ($scope.reverse ? 'asc' : 'desc'), 'id']}, function(result, headers) {
                $scope.links = ParseLinks.parse(headers('link'));
                $scope.totalItems = headers('X-Total-Count');
                $scope.actions = result;
            });
        };
        $scope.loadPage = function(page) {
            $scope.page = page;
            $scope.loadAll();
        };
        $scope.loadAll();

        $scope.search = function () {
            ActionSearch.query({query: $scope.searchQuery}, function(result) {
                $scope.actions = result;
            }, function(response) {
                if(response.status === 404) {
                    $scope.loadAll();
                }
            });
        };

        $scope.refresh = function () {
            $scope.loadAll();
            $scope.clear();
        };

        $scope.clear = function () {
            $scope.action = {
                sujet: null,
                description: null,
                dateDebut: null,
                dateFin: null,
                typeAction: null,
                user: null,
                id: null
            };
        };
    });


text:
DOCKER_NETWORK=java_tests_network_$$
AMQP_HOST1=amqp-host1
AMQP_HOST2=amqp-host2
AMQP_CONTAINER_NAME1=amqp-host1-$$
AMQP_CONTAINER_NAME2=amqp-host2-$$
JAVA_CONTAINER_NAME=java-tests-host-$$
JAVA_HOST=java-tests-host
TMP_DIR=
SUDO=
MRG_VERSIONS="3.2.0 3.0.0 0.34 0.36"
MVN_IMAGE_VERSIONS="3-jdk-7 3-jdk-8"
RESULTS_MSG="RESULTS:\n"

trap "stop_and_remove_left_containers && exit 1" SIGINT SIGTERM

function stop_and_remove_left_containers() {
    for container in $(${SUDO} docker ps -a --filter "status=running" --format "{{.Names}}") ; do
        if [ ${container} == ${AMQP_CONTAINER_NAME1} ] || ${container} == ${AMQP_CONTAINER_NAME2} ] || [ ${container} == ${JAVA_CONTAINER_NAME} ] ; then
            echo "Stopping container: ${container}"
            ${SUDO} docker stop ${container}
        fi
    done
    for container in $(${SUDO} docker ps -a --filter "status=exited" --format "{{.Names}}") ; do
        if [ ${container} == ${AMQP_CONTAINER_NAME1} ] || ${container} == ${AMQP_CONTAINER_NAME2} ] || [ ${container} == ${JAVA_CONTAINER_NAME} ] ; then
            echo "Removing container: ${container}"
            ${SUDO} docker rm ${container}
        fi
    done
    ${SUDO} docker network rm ${DOCKER_NETWORK}
}

function print_help() {
    local MY_NAME="$(basename $0 .sh)"
    echo "Usage: ${MY_NAME}.sh [OPTION]..."
    echo ""
    echo " optional"
    echo ""
    echo "  --mrg-version=VERSION    Use specific MRG version (e.g. 3.2.0)"
    echo "  --mvn-version=VERSION    Use specific Maven Docker image version (e.g. 3-jdk-8)"
    echo "  --use-sudo               Execute every docker command under sudo"
    echo "  --help, -h, -?           Print this help and exit"
}

function extract_parameter_value_from_string {
    echo "${1#*=}"
    return 0
}

function parse_cmdline_parameters() {
    for i in "$@" ; do
        case $i in
        --mrg-version=*)
            MRG_VERSIONS=$(extract_parameter_value_from_string $1);;
        --mvn-version=*)
            MVN_IMAGE_VERSIONS=$(extract_parameter_value_from_string $1);;
        --use-sudo)
            SUDO="sudo";;
        --help | -h | -?)
            print_help; exit 0;;
        "");;
        *)
            echo "Unknown parameter '$i'";
            exit 2;;
        esac
        shift
    done
}

function startup() {
    TMP_DIR=$(mktemp -d)
}

function create_network() {
    ${SUDO} docker network create --subnet=192.168.0.0/16 --driver bridge ${DOCKER_NETWORK}
}

# param: $1 - image version
function start_qpidd_container() {
    ${SUDO} docker run -d --net=${DOCKER_NETWORK} --name=${AMQP_CONTAINER_NAME1} --hostname=${AMQP_HOST1} scholzj/java-client-tests:$1
    RESULTS_MSG+="MRG: $1, "

    ${SUDO} docker run -d --net=${DOCKER_NETWORK} --name=${AMQP_CONTAINER_NAME2} --hostname=${AMQP_HOST2} scholzj/java-client-tests:$1
    RESULTS_MSG+="MRG: $1, "
}

# param: $1 - image version
function start_tests_container() {
    local AMQP_CONTAINER_NAME_IP_ADDRESS1=$(${SUDO} docker inspect --format "{{ .NetworkSettings.Networks.${DOCKER_NETWORK}.IPAddress }}" ${AMQP_CONTAINER_NAME1})
    local AMQP_CONTAINER_NAME_IP_ADDRESS2=$(${SUDO} docker inspect --format "{{ .NetworkSettings.Networks.${DOCKER_NETWORK}.IPAddress }}" ${AMQP_CONTAINER_NAME2})
    ${SUDO} docker run -d -it --net=${DOCKER_NETWORK} --add-host ${AMQP_HOST1}:${AMQP_CONTAINER_NAME_IP_ADDRESS1} --add-host ${AMQP_HOST2}:${AMQP_CONTAINER_NAME_IP_ADDRESS2} --name=${JAVA_CONTAINER_NAME} --hostname=${JAVA_HOST} maven:$1 bash
    RESULTS_MSG+="MAVEN IMAGE: $1, "
}

# create and copy maven's settings.xml file with proxy settings into the docker image
function prepare_maven_on_container() {
    cat > ${TMP_DIR}/settings.xml <<EOF
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                  http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <proxies>
    <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>webproxy.deutsche-boerse.de</host>
      <port>8080</port>
      <nonProxyHosts>cmqaart.deutsche-boerse.de</nonProxyHosts>
    </proxy>
  </proxies>
</settings>
EOF
    ${SUDO} docker cp ${TMP_DIR}/settings.xml ${JAVA_CONTAINER_NAME}:/root/.m2/
}

# get source code into the docker container
function prepare_sources_on_container() {
    ${SUDO} docker exec ${JAVA_CONTAINER_NAME} bash -c "cd && git config --global http.proxy http://webproxy.deutsche-boerse.de:8080 && git clone https://github.com/scholzj/amqp-transaction-monkey.git amqp-transaction-monkey"
}

# param: $1 - maven pom xml name
function execute_tests() {
    local AMQP_CONTAINER_NAME_IP_ADDRESS1=$(${SUDO} docker inspect --format "{{ .NetworkSettings.Networks.${DOCKER_NETWORK}.IPAddress }}" ${AMQP_CONTAINER_NAME1})
    local AMQP_CONTAINER_NAME_IP_ADDRESS2=$(${SUDO} docker inspect --format "{{ .NetworkSettings.Networks.${DOCKER_NETWORK}.IPAddress }}" ${AMQP_CONTAINER_NAME2})

    ${SUDO} docker exec ${JAVA_CONTAINER_NAME} bash -c "cd && cd amqp-transaction-monkey && mvn package && java -jar target/transaction-monkey-0.1-SNAPSHOT.jar --first-broker-host ${AMQP_CONTAINER_NAME_IP_ADDRESS1} --first-broker-port 5672 --first-broker-username admin --first-broker-password admin --first-broker-queue broadcast.user1.rtgQueue --second-broker-host ${AMQP_CONTAINER_NAME_IP_ADDRESS2} --second-broker-port 5672 --second-broker-username admin --second-broker-password admin --second-broker-queue broadcast.user1.rtgQueue --enable-amqp10-routing --enable-amqp010-routing --enable-xa-amqp010-routing --enable-amqp10-rollback --enable-amqp010-rollback --enable-xa-amqp010-rollback --transaction-count=1000000 --feed-messages"
    local RETURN_CODE=$?
    RESULTS_MSG+="POM.XML: $1,"
    if [ ${RETURN_CODE} -eq 0 ] ; then
        RESULTS_MSG+=" RESULT: SUCCESS\n"
    else
        RESULTS_MSG+=" RESULT: FAILURE\n"
    fi
}

function cleanup() {
    rm -rf ${TMP_DIR}
    ${SUDO} docker stop ${AMQP_CONTAINER_NAME1}
    ${SUDO} docker rm ${AMQP_CONTAINER_NAME1}
    ${SUDO} docker stop ${AMQP_CONTAINER_NAME2}
    ${SUDO} docker rm ${AMQP_CONTAINER_NAME2}
    ${SUDO} docker stop ${JAVA_CONTAINER_NAME}
    ${SUDO} docker rm ${JAVA_CONTAINER_NAME}
    ${SUDO} docker network rm ${DOCKER_NETWORK}
}

# params: $1 - QPID container id, $2 - Maven container id, $3 - name of maven pom.xml on test container
function execute_single_run() {
    local QPIDD_CONTAINER_VERSION=$1
    local MAVEN_CONTAINER_VERSION=$2
    local TESTS_POM_XML_NAME=$3
    startup
    create_network && \
    start_qpidd_container ${QPIDD_CONTAINER_VERSION} && \
    start_tests_container ${MAVEN_CONTAINER_VERSION} && \
    prepare_maven_on_container && \
    prepare_sources_on_container && \
    execute_tests ${TESTS_POM_XML_NAME}
    cleanup
}

function execute_all_runs() {
    for mvn_version in ${MVN_IMAGE_VERSIONS} ; do
        for mrg_version in ${MRG_VERSIONS} ; do
            case ${mrg_version} in
              3.*)  execute_single_run ${mrg_version} ${mvn_version} mrg-${mrg_version}.xml ;;
              *) execute_single_run ${mrg_version} ${mvn_version} qpid-${mrg_version}.xml ;;
            esac
        done
    done
}

function print_results() {
    echo -e ${RESULTS_MSG}
}

parse_cmdline_parameters "$@"
execute_all_runs
print_results


text:
GraphicSize
===========

Simple C++ code to retrieve image dimensions from JPEG, GIF, or PNG files.

This code was taken from an old post on CPlusPlus.com (http://www.cplusplus.com/forum/beginner/45217/). I have modified it to get it working and use it in my own works.

I am unable to reach the original poster, so licensing may be an issue. Use at your own risk.

This is very much alpha code. Please feel free to contact me with any problems.

The only necessary file is GraphicSize.cpp. The rest is for testing and building. There are no dependancies beyond your standard compiler libraries.