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

<title>calculatrice Class Hierarchy</title>
<meta name="date" content="2017-05-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

Hierarchy For Package calculatrice

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

calculatrice.Main (implements calculatrice.MainConstants)

calculatrice.MainTokenManager (implements calculatrice.MainConstants)

calculatrice.SimpleCharStream

java.lang.Throwable (implements java.io.Serializable)

java.lang.Error

calculatrice.TokenMgrError

java.lang.Exception

calculatrice.ParseException

calculatrice.Token (implements java.io.Serializable)

Interface Hierarchy

calculatrice.MainConstants

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.lorentzos.swipecards;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends Activity {

    private EditText username;
    private EditText password;
    private Firebase firebaseRef;
    Map<String, Object> users;
    private Button login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Firebase.setAndroidContext(this);
        setupVariables();
    }

    public void authenticateLogin(View view) {
        String usernameString = username.getText().toString();
        String passwordString = password.getText().toString();

        if (users.containsKey(usernameString)) {
            // check password
            if (((Map<String, Object>) users.get(usernameString)).get("password").
                    equals(passwordString)) {
                Toast.makeText(getApplicationContext(), "Welcome, " + usernameString,
                        Toast.LENGTH_SHORT).show();

                if ((Long) ((Map<String, Object>) users.get(usernameString)).get("threshold") == -1) {
                    // First time, profile the user
                    Intent i = new Intent(this, ProfileUserActivity.class);
                    i.putExtra("username", usernameString);
                    startActivity(i);
                } else {
                    Log.d("LoginActivity", "Not first time, go to Dashboard");
                    // Not first time, go right to the action
                    Intent i = new Intent(this, DashboardActivity.class);
                    i.putExtra("username", usernameString);
                    startActivity(i);
                }
            } else {
                Toast.makeText(getApplicationContext(), "Invalid password",
                        Toast.LENGTH_SHORT).show();
            }
        } else {
            // not in there, add
            if (passwordString.length() < 6) {
                Toast.makeText(getApplicationContext(), "Password too short, must be at least 6 characters!",
                        Toast.LENGTH_SHORT).show();
            } else {
                Map<String, Object> newUser = new HashMap<String, Object>();
                newUser.put("password", passwordString);
                newUser.put("threshold", -1);
                firebaseRef.child("users").child(usernameString).setValue(newUser);
                Toast.makeText(getApplicationContext(), "New account created!",
                        Toast.LENGTH_SHORT).show();
                Intent i = new Intent(this, ProfileUserActivity.class);
                i.putExtra("username", usernameString);
                startActivity(i);
            }
        }
    }

    private void setupVariables() {
        username = (EditText) findViewById(R.id.usernameET);
        password = (EditText) findViewById(R.id.passwordET);
        login = (Button) findViewById(R.id.loginBtn);
        firebaseRef = new Firebase("https://babystep.firebaseio.com");

        firebaseRef.child("users").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                users = (Map<String, Object>) snapshot.getValue();
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.woocommerce.beans.coupon;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.builder.ToStringBuilder;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.woocommerce.beans.common.Links;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "id",
    "code",
    "date_created",
    "date_modified",
    "discount_type",
    "description",
    "amount",
    "expiry_date",
    "usage_count",
    "individual_use",
    "product_ids",
    "exclude_product_ids",
    "usage_limit",
    "usage_limit_per_user",
    "limit_usage_to_x_items",
    "free_shipping",
    "product_categories",
    "excluded_product_categories",
    "exclude_sale_items",
    "minimum_amount",
    "maximum_amount",
    "email_restrictions",
    "used_by",
    "_links"
})
public class WooCoupon {

    @JsonProperty("id")
    private Long id;
    @JsonProperty("code")
    private String code;
    @JsonProperty("date_created")
    private String dateCreated;
    @JsonProperty("date_modified")
    private String dateModified;
    @JsonProperty("discount_type")
    private String discountType;
    @JsonProperty("description")
    private String description;
    @JsonProperty("amount")
    private String amount;
    @JsonProperty("expiry_date")
    private String expiryDate;
    @JsonProperty("usage_count")
    private Long usageCount;
    @JsonProperty("individual_use")
    private Boolean individualUse;
    @JsonProperty("product_ids")
    private List<Object> productIds = null;
    @JsonProperty("exclude_product_ids")
    private List<Object> excludeProductIds = null;
    @JsonProperty("usage_limit")
    private Object usageLimit;
    @JsonProperty("usage_limit_per_user")
    private Object usageLimitPerUser;
    @JsonProperty("limit_usage_to_x_items")
    private Long limitUsageToXItems;
    @JsonProperty("free_shipping")
    private Boolean freeShipping;
    @JsonProperty("product_categories")
    private List<Long> productCategories = null;
    @JsonProperty("excluded_product_categories")
    private List<Object> excludedProductCategories = null;
    @JsonProperty("exclude_sale_items")
    private Boolean excludeSaleItems;
    @JsonProperty("minimum_amount")
    private String minimumAmount;
    @JsonProperty("maximum_amount")
    private String maximumAmount;
    @JsonProperty("email_restrictions")
    private List<Object> emailRestrictions = null;
    @JsonProperty("used_by")
    private List<Object> usedBy = null;
    @JsonProperty("_links")
    private Links links;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("id")
    public Long getId() {
        return id;
    }

    @JsonProperty("id")
    public void setId(Long id) {
        this.id = id;
    }

    @JsonProperty("code")
    public String getCode() {
        return code;
    }

    @JsonProperty("code")
    public void setCode(String code) {
        this.code = code;
    }

    @JsonProperty("date_created")
    public String getDateCreated() {
        return dateCreated;
    }

    @JsonProperty("date_created")
    public void setDateCreated(String dateCreated) {
        this.dateCreated = dateCreated;
    }

    @JsonProperty("date_modified")
    public String getDateModified() {
        return dateModified;
    }

    @JsonProperty("date_modified")
    public void setDateModified(String dateModified) {
        this.dateModified = dateModified;
    }

    @JsonProperty("discount_type")
    public String getDiscountType() {
        return discountType;
    }

    @JsonProperty("discount_type")
    public void setDiscountType(String discountType) {
        this.discountType = discountType;
    }

    @JsonProperty("description")
    public String getDescription() {
        return description;
    }

    @JsonProperty("description")
    public void setDescription(String description) {
        this.description = description;
    }

    @JsonProperty("amount")
    public String getAmount() {
        return amount;
    }

    @JsonProperty("amount")
    public void setAmount(String amount) {
        this.amount = amount;
    }

    @JsonProperty("expiry_date")
    public String getExpiryDate() {
        return expiryDate;
    }

    @JsonProperty("expiry_date")
    public void setExpiryDate(String expiryDate) {
        this.expiryDate = expiryDate;
    }

    @JsonProperty("usage_count")
    public Long getUsageCount() {
        return usageCount;
    }

    @JsonProperty("usage_count")
    public void setUsageCount(Long usageCount) {
        this.usageCount = usageCount;
    }

    @JsonProperty("individual_use")
    public Boolean getIndividualUse() {
        return individualUse;
    }

    @JsonProperty("individual_use")
    public void setIndividualUse(Boolean individualUse) {
        this.individualUse = individualUse;
    }

    @JsonProperty("product_ids")
    public List<Object> getProductIds() {
        return productIds;
    }

    @JsonProperty("product_ids")
    public void setProductIds(List<Object> productIds) {
        this.productIds = productIds;
    }

    @JsonProperty("exclude_product_ids")
    public List<Object> getExcludeProductIds() {
        return excludeProductIds;
    }

    @JsonProperty("exclude_product_ids")
    public void setExcludeProductIds(List<Object> excludeProductIds) {
        this.excludeProductIds = excludeProductIds;
    }

    @JsonProperty("usage_limit")
    public Object getUsageLimit() {
        return usageLimit;
    }

    @JsonProperty("usage_limit")
    public void setUsageLimit(Object usageLimit) {
        this.usageLimit = usageLimit;
    }

    @JsonProperty("usage_limit_per_user")
    public Object getUsageLimitPerUser() {
        return usageLimitPerUser;
    }

    @JsonProperty("usage_limit_per_user")
    public void setUsageLimitPerUser(Object usageLimitPerUser) {
        this.usageLimitPerUser = usageLimitPerUser;
    }

    @JsonProperty("limit_usage_to_x_items")
    public Long getLimitUsageToXItems() {
        return limitUsageToXItems;
    }

    @JsonProperty("limit_usage_to_x_items")
    public void setLimitUsageToXItems(Long limitUsageToXItems) {
        this.limitUsageToXItems = limitUsageToXItems;
    }

    @JsonProperty("free_shipping")
    public Boolean getFreeShipping() {
        return freeShipping;
    }

    @JsonProperty("free_shipping")
    public void setFreeShipping(Boolean freeShipping) {
        this.freeShipping = freeShipping;
    }

    @JsonProperty("product_categories")
    public List<Long> getProductCategories() {
        return productCategories;
    }

    @JsonProperty("product_categories")
    public void setProductCategories(List<Long> productCategories) {
        this.productCategories = productCategories;
    }

    @JsonProperty("excluded_product_categories")
    public List<Object> getExcludedProductCategories() {
        return excludedProductCategories;
    }

    @JsonProperty("excluded_product_categories")
    public void setExcludedProductCategories(List<Object> excludedProductCategories) {
        this.excludedProductCategories = excludedProductCategories;
    }

    @JsonProperty("exclude_sale_items")
    public Boolean getExcludeSaleItems() {
        return excludeSaleItems;
    }

    @JsonProperty("exclude_sale_items")
    public void setExcludeSaleItems(Boolean excludeSaleItems) {
        this.excludeSaleItems = excludeSaleItems;
    }

    @JsonProperty("minimum_amount")
    public String getMinimumAmount() {
        return minimumAmount;
    }

    @JsonProperty("minimum_amount")
    public void setMinimumAmount(String minimumAmount) {
        this.minimumAmount = minimumAmount;
    }

    @JsonProperty("maximum_amount")
    public String getMaximumAmount() {
        return maximumAmount;
    }

    @JsonProperty("maximum_amount")
    public void setMaximumAmount(String maximumAmount) {
        this.maximumAmount = maximumAmount;
    }

    @JsonProperty("email_restrictions")
    public List<Object> getEmailRestrictions() {
        return emailRestrictions;
    }

    @JsonProperty("email_restrictions")
    public void setEmailRestrictions(List<Object> emailRestrictions) {
        this.emailRestrictions = emailRestrictions;
    }

    @JsonProperty("used_by")
    public List<Object> getUsedBy() {
        return usedBy;
    }

    @JsonProperty("used_by")
    public void setUsedBy(List<Object> usedBy) {
        this.usedBy = usedBy;
    }

    @JsonProperty("_links")
    public Links getLinks() {
        return links;
    }

    @JsonProperty("_links")
    public void setLinks(Links links) {
        this.links = links;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
import unittest
from lucene import *

class Test_Bug1842(unittest.TestCase):

    def setUp(self):

        self.analyzer = StandardAnalyzer(Version.LUCENE_CURRENT)
        self.d1 = RAMDirectory()

        w1 = IndexWriter(self.d1, self.analyzer, True,
                         IndexWriter.MaxFieldLength.LIMITED)
        doc1 = Document()
        doc1.add(Field("all", "blah blah blah Gesundheit",
                       Field.Store.NO, Field.Index.ANALYZED,
                       Field.TermVector.YES))
        doc1.add(Field('id', '1',
                       Field.Store.YES, Field.Index.NOT_ANALYZED))
        w1.addDocument(doc1)
        w1.optimize()
        w1.close()

    def tearDown(self):
        pass

    def test_bug1842(self):

        reader = IndexReader.open(self.d1, True)
        searcher = IndexSearcher(self.d1, True)
        q = TermQuery(Term("id", '1'))
        topDocs = searcher.search(q, 50)
        freqvec = reader.getTermFreqVector(topDocs.scoreDocs[0].doc, "all")
        terms = [term.utf8ToString() for term in freqvec.getTerms()]
        terms.sort()
        self.assert_(terms == ['blah', 'gesundheit'])

        freqs = freqvec.getTermFrequencies()
        self.assert_(freqs == [3, 1])

if __name__ == '__main__':
    import lucene
    lucene.initVM()
    unittest.main()


text:
package org.apache.hadoop.yarn.server.resourcemanager;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;

import org.apache.hadoop.thirdparty.protobuf.InvalidProtocolBufferException;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.token.delegation.TestDelegationToken;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMDelegationTokenIdentifierData;
import org.junit.AfterClass;
import org.junit.Assert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
import org.apache.hadoop.security.token.SecretManager;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.yarn.api.ApplicationClientProtocol;
import org.apache.hadoop.yarn.api.protocolrecords.CancelDelegationTokenRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetDelegationTokenRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest;
import org.apache.hadoop.yarn.api.protocolrecords.RenewDelegationTokenRequest;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.ipc.YarnRPC;
import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.NullRMStateStore;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.security.QueueACLsManager;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMDelegationTokenSecretManager;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.hadoop.yarn.util.Records;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestClientRMTokens {

  private static final Logger LOG =
      LoggerFactory.getLogger(TestClientRMTokens.class);

  // Note : Any test case in ResourceManager package that creates a proxy has
  // to be run with enabling hadoop.security.token.service.use_ip. And reset
  // to false at the end of test class. See YARN-5208
  @BeforeClass
  public static void setUp() {
    Configuration conf = new Configuration();
    conf.setBoolean(
        CommonConfigurationKeys.HADOOP_SECURITY_TOKEN_SERVICE_USE_IP, true);
    SecurityUtil.setConfiguration(conf);
  }

  @AfterClass
  public static void tearDown() {
    Configuration conf = new Configuration();
    conf.setBoolean(
        CommonConfigurationKeys.HADOOP_SECURITY_TOKEN_SERVICE_USE_IP, false);
    SecurityUtil.setConfiguration(conf);
  }

  @Before
  public void resetSecretManager() {
    RMDelegationTokenIdentifier.Renewer.setSecretManager(null, null);
  }

  @Test
  public void testDelegationToken() throws IOException, InterruptedException {

    final YarnConfiguration conf = new YarnConfiguration();
    conf.set(YarnConfiguration.RM_PRINCIPAL, "testuser/localhost@apache.org");

    conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
    UserGroupInformation.setConfiguration(conf);

    ResourceScheduler scheduler = createMockScheduler(conf);

    long initialInterval = 10000l;
    long maxLifetime= 20000l;
    long renewInterval = 10000l;

    RMDelegationTokenSecretManager rmDtSecretManager = createRMDelegationTokenSecretManager(
        initialInterval, maxLifetime, renewInterval);
    rmDtSecretManager.startThreads();
    LOG.info("Creating DelegationTokenSecretManager with initialInterval: "
        + initialInterval + ", maxLifetime: " + maxLifetime
        + ", renewInterval: " + renewInterval);

    final ClientRMService clientRMService = new ClientRMServiceForTest(conf,
        scheduler, rmDtSecretManager);
    clientRMService.init(conf);
    clientRMService.start();

    ApplicationClientProtocol clientRMWithDT = null;
    try {

      // Create a user for the renewr and fake the authentication-method
      UserGroupInformation loggedInUser = UserGroupInformation
          .createRemoteUser("testrenewer@APACHE.ORG");
      Assert.assertEquals("testrenewer", loggedInUser.getShortUserName());
      // Default realm is APACHE.ORG
      loggedInUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);

      org.apache.hadoop.yarn.api.records.Token token = getDelegationToken(loggedInUser, clientRMService,
          loggedInUser.getShortUserName());
      long tokenFetchTime = System.currentTimeMillis();
      LOG.info("Got delegation token at: " + tokenFetchTime);

      // Now try talking to RMService using the delegation token
      clientRMWithDT = getClientRMProtocolWithDT(token,
          clientRMService.getBindAddress(), "loginuser1", conf);

      GetNewApplicationRequest request = Records.newRecord(GetNewApplicationRequest.class);

      try {
        clientRMWithDT.getNewApplication(request);
      } catch (IOException e) {
        fail("Unexpected exception" + e);
      }  catch (YarnException e) {
        fail("Unexpected exception" + e);
      }

      // Renew after 50% of token age.
      while(System.currentTimeMillis() < tokenFetchTime + initialInterval / 2) {
        Thread.sleep(500l);
      }
      long nextExpTime = renewDelegationToken(loggedInUser, clientRMService, token);
      long renewalTime = System.currentTimeMillis();
      LOG.info("Renewed token at: " + renewalTime + ", NextExpiryTime: "
          + nextExpTime);

      // Wait for first expiry, but before renewed expiry.
      while (System.currentTimeMillis() > tokenFetchTime + initialInterval
          && System.currentTimeMillis() < nextExpTime) {
        Thread.sleep(500l);
      }
      Thread.sleep(50l);

      // Valid token because of renewal.
      try {
        clientRMWithDT.getNewApplication(request);
      } catch (IOException e) {
        fail("Unexpected exception" + e);
      } catch (YarnException e) {
        fail("Unexpected exception" + e);
      }

      // Wait for expiry.
      while(System.currentTimeMillis() < renewalTime + renewInterval) {
        Thread.sleep(500l);
      }
      Thread.sleep(50l);
      LOG.info("At time: " + System.currentTimeMillis() + ", token should be invalid");
      // Token should have expired.
      try {
        clientRMWithDT.getNewApplication(request);
        fail("Should not have succeeded with an expired token");
      } catch (Exception e) {
        assertEquals(InvalidToken.class.getName(), e.getClass().getName());
        assertTrue(e.getMessage().contains("is expired"));
      }

      // Test cancellation
      // Stop the existing proxy, start another.
      if (clientRMWithDT != null) {
        RPC.stopProxy(clientRMWithDT);
        clientRMWithDT = null;
      }
      token = getDelegationToken(loggedInUser, clientRMService,
          loggedInUser.getShortUserName());
      tokenFetchTime = System.currentTimeMillis();
      LOG.info("Got delegation token at: " + tokenFetchTime);

      // Now try talking to RMService using the delegation token
      clientRMWithDT = getClientRMProtocolWithDT(token,
          clientRMService.getBindAddress(), "loginuser2", conf);

      request = Records.newRecord(GetNewApplicationRequest.class);

      try {
        clientRMWithDT.getNewApplication(request);
      } catch (IOException e) {
        fail("Unexpected exception" + e);
      } catch (YarnException e) {
        fail("Unexpected exception" + e);
      }
      cancelDelegationToken(loggedInUser, clientRMService, token);
      if (clientRMWithDT != null) {
        RPC.stopProxy(clientRMWithDT);
        clientRMWithDT = null;
      }

      // Creating a new connection.
      clientRMWithDT = getClientRMProtocolWithDT(token,
          clientRMService.getBindAddress(), "loginuser2", conf);
      LOG.info("Cancelled delegation token at: " + System.currentTimeMillis());
      // Verify cancellation worked.
      try {
        clientRMWithDT.getNewApplication(request);
        fail("Should not have succeeded with a cancelled delegation token");
      } catch (IOException e) {
      } catch (YarnException e) {
      }

      // Test new version token
      // Stop the existing proxy, start another.
      if (clientRMWithDT != null) {
        RPC.stopProxy(clientRMWithDT);
        clientRMWithDT = null;
      }
      token = getDelegationToken(loggedInUser, clientRMService,
          loggedInUser.getShortUserName());

      byte[] tokenIdentifierContent = token.getIdentifier().array();
      RMDelegationTokenIdentifier tokenIdentifier = new RMDelegationTokenIdentifier();

      DataInputBuffer dib = new DataInputBuffer();
      dib.reset(tokenIdentifierContent, tokenIdentifierContent.length);
      tokenIdentifier.readFields(dib);

      // Construct new version RMDelegationTokenIdentifier with additional field
      RMDelegationTokenIdentifierForTest newVersionTokenIdentifier =
          new RMDelegationTokenIdentifierForTest(tokenIdentifier, "message");

      Token<RMDelegationTokenIdentifier> newRMDTtoken =
          new Token<RMDelegationTokenIdentifier>(newVersionTokenIdentifier,
              rmDtSecretManager);
      org.apache.hadoop.yarn.api.records.Token newToken =
          BuilderUtils.newDelegationToken(
              newRMDTtoken.getIdentifier(),
              newRMDTtoken.getKind().toString(),
              newRMDTtoken.getPassword(),
              newRMDTtoken.getService().toString()
          );

      // Now try talking to RMService using the new version delegation token
      clientRMWithDT = getClientRMProtocolWithDT(newToken,
          clientRMService.getBindAddress(), "loginuser3", conf);

      request = Records.newRecord(GetNewApplicationRequest.class);

      try {
        clientRMWithDT.getNewApplication(request);
      } catch (IOException e) {
        fail("Unexpected exception" + e);
      } catch (YarnException e) {
        fail("Unexpected exception" + e);
      }

    } finally {
      rmDtSecretManager.stopThreads();
      // TODO PRECOMMIT Close proxies.
      if (clientRMWithDT != null) {
        RPC.stopProxy(clientRMWithDT);
      }
    }
  }

  @Test
  public void testShortCircuitRenewCancel()
      throws IOException, InterruptedException {
    InetSocketAddress addr = NetUtils.createSocketAddr(
        InetAddress.getLocalHost().getHostName(), 123, null);
    checkShortCircuitRenewCancel(addr, addr, true);
  }

  @Test
  public void testShortCircuitRenewCancelWildcardAddress()
      throws IOException, InterruptedException {
    InetSocketAddress rmAddr = new InetSocketAddress(123);
    InetSocketAddress serviceAddr = NetUtils.createSocketAddr(
        InetAddress.getLocalHost().getHostName(), rmAddr.getPort(), null);
    checkShortCircuitRenewCancel(
        rmAddr,
        serviceAddr,
        true);
  }

  @Test
  public void testShortCircuitRenewCancelSameHostDifferentPort()
      throws IOException, InterruptedException {
    InetSocketAddress rmAddr = NetUtils.createSocketAddr(
        InetAddress.getLocalHost().getHostName(), 123, null);
    checkShortCircuitRenewCancel(
        rmAddr,
        new InetSocketAddress(rmAddr.getAddress(), rmAddr.getPort()+1),
        false);
  }

  @Test
  public void testShortCircuitRenewCancelDifferentHostSamePort()
      throws IOException, InterruptedException {
    InetSocketAddress rmAddr = NetUtils.createSocketAddr(
        InetAddress.getLocalHost().getHostName(), 123, null);
    checkShortCircuitRenewCancel(
        rmAddr,
        new InetSocketAddress("1.1.1.1", rmAddr.getPort()),
        false);
  }

  @Test
  public void testShortCircuitRenewCancelDifferentHostDifferentPort()
      throws IOException, InterruptedException {
    InetSocketAddress rmAddr = NetUtils.createSocketAddr(
        InetAddress.getLocalHost().getHostName(), 123, null);
    checkShortCircuitRenewCancel(
        rmAddr,
        new InetSocketAddress("1.1.1.1", rmAddr.getPort()+1),
        false);
  }

  @Test
  public void testReadOldFormatFields() throws IOException {
    RMDelegationTokenIdentifier token = new RMDelegationTokenIdentifier(
        new Text("alice"), new Text("bob"), new Text("colin"));
    token.setIssueDate(123);
    token.setMasterKeyId(321);
    token.setMaxDate(314);
    token.setSequenceNumber(12345);
    DataInputBuffer inBuf = new DataInputBuffer();
    DataOutputBuffer outBuf = new DataOutputBuffer();
    token.writeInOldFormat(outBuf);
    outBuf.writeLong(42);   // renewDate
    inBuf.reset(outBuf.getData(), 0, outBuf.getLength());

    RMDelegationTokenIdentifier identifier = null;

    try {
      RMDelegationTokenIdentifierData identifierData =
          new RMDelegationTokenIdentifierData();
      identifierData.readFields(inBuf);
      fail("Should have thrown a "
          + InvalidProtocolBufferException.class.getName()
          + " because the token is not a protobuf");
    } catch (InvalidProtocolBufferException e) {
      identifier = new RMDelegationTokenIdentifier();
      inBuf.reset();
      identifier.readFieldsInOldFormat(inBuf);
      assertEquals(42, inBuf.readLong());
    }

    assertEquals("alice", identifier.getUser().getUserName());
    assertEquals(new Text("bob"), identifier.getRenewer());
    assertEquals("colin", identifier.getUser().getRealUser().getUserName());
    assertEquals(123, identifier.getIssueDate());
    assertEquals(321, identifier.getMasterKeyId());
    assertEquals(314, identifier.getMaxDate());
    assertEquals(12345, identifier.getSequenceNumber());

  }

  @SuppressWarnings("unchecked")
  private void checkShortCircuitRenewCancel(InetSocketAddress rmAddr,
                                            InetSocketAddress serviceAddr,
                                            boolean shouldShortCircuit
      ) throws IOException, InterruptedException {
    Configuration conf = new Configuration();
    conf.setClass(YarnConfiguration.IPC_RPC_IMPL,
        YarnBadRPC.class, YarnRPC.class);

    RMDelegationTokenSecretManager secretManager =
        mock(RMDelegationTokenSecretManager.class);
    RMDelegationTokenIdentifier.Renewer.setSecretManager(secretManager, rmAddr);

    RMDelegationTokenIdentifier ident = new RMDelegationTokenIdentifier(
        new Text("owner"), new Text("renewer"), null);
    Token<RMDelegationTokenIdentifier> token =
        new Token<RMDelegationTokenIdentifier>(ident, secretManager);

    SecurityUtil.setTokenService(token, serviceAddr);
    if (shouldShortCircuit) {
      token.renew(conf);
      verify(secretManager).renewToken(eq(token), eq("renewer"));
      reset(secretManager);
      token.cancel(conf);
      verify(secretManager).cancelToken(eq(token), eq("renewer"));
    } else {
      try {
        token.renew(conf);
        fail();
      } catch (RuntimeException e) {
        assertEquals("getProxy", e.getMessage());
      }
      verify(secretManager, never()).renewToken(any(Token.class), anyString());
      try {
        token.cancel(conf);
        fail();
      } catch (RuntimeException e) {
        assertEquals("getProxy", e.getMessage());
      }
      verify(secretManager, never()).cancelToken(any(Token.class), anyString());
    }
  }

  @SuppressWarnings("rawtypes")
  public static class YarnBadRPC extends YarnRPC {
    @Override
    public Object getProxy(Class protocol, InetSocketAddress addr,
        Configuration conf) {
      throw new RuntimeException("getProxy");
    }

    @Override
    public void stopProxy(Object proxy, Configuration conf) {
      throw new RuntimeException("stopProxy");
    }

    @Override
    public Server getServer(Class protocol, Object instance,
        InetSocketAddress addr, Configuration conf,
        SecretManager<? extends TokenIdentifier> secretManager,
        int numHandlers, String portRangeConfig) {
      throw new RuntimeException("getServer");
    }
  }

  // Get the delegation token directly as it is a little difficult to setup
  // the kerberos based rpc.
  private org.apache.hadoop.yarn.api.records.Token getDelegationToken(
      final UserGroupInformation loggedInUser,
      final ApplicationClientProtocol clientRMService, final String renewerString)
      throws IOException, InterruptedException {
    org.apache.hadoop.yarn.api.records.Token token = loggedInUser
        .doAs(new PrivilegedExceptionAction<org.apache.hadoop.yarn.api.records.Token>() {
          @Override
            public org.apache.hadoop.yarn.api.records.Token run()
                throws YarnException, IOException {
            GetDelegationTokenRequest request = Records
                .newRecord(GetDelegationTokenRequest.class);
            request.setRenewer(renewerString);
            return clientRMService.getDelegationToken(request)
                .getRMDelegationToken();
          }
        });
    return token;
  }

  private long renewDelegationToken(final UserGroupInformation loggedInUser,
      final ApplicationClientProtocol clientRMService,
      final org.apache.hadoop.yarn.api.records.Token dToken)
      throws IOException, InterruptedException {
    long nextExpTime = loggedInUser.doAs(new PrivilegedExceptionAction<Long>() {
      @Override
      public Long run() throws YarnException, IOException {
        RenewDelegationTokenRequest request = Records
            .newRecord(RenewDelegationTokenRequest.class);
        request.setDelegationToken(dToken);
        return clientRMService.renewDelegationToken(request)
            .getNextExpirationTime();
      }
    });
    return nextExpTime;
  }

  private void cancelDelegationToken(final UserGroupInformation loggedInUser,
      final ApplicationClientProtocol clientRMService,
      final org.apache.hadoop.yarn.api.records.Token dToken)
      throws IOException, InterruptedException {
    loggedInUser.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws YarnException, IOException {
        CancelDelegationTokenRequest request = Records
            .newRecord(CancelDelegationTokenRequest.class);
        request.setDelegationToken(dToken);
        clientRMService.cancelDelegationToken(request);
        return null;
      }
    });
  }

  private ApplicationClientProtocol getClientRMProtocolWithDT(
      org.apache.hadoop.yarn.api.records.Token token,
      final InetSocketAddress rmAddress, String user, final Configuration conf) {
    // Maybe consider converting to Hadoop token, serialize de-serialize etc
    // before trying to renew the token.

    UserGroupInformation ugi = UserGroupInformation
        .createRemoteUser(user);
    ugi.addToken(ConverterUtils.convertFromYarn(token, rmAddress));

    final YarnRPC rpc = YarnRPC.create(conf);
    ApplicationClientProtocol clientRMWithDT = ugi
        .doAs(new PrivilegedAction<ApplicationClientProtocol>() {
          @Override
          public ApplicationClientProtocol run() {
            return (ApplicationClientProtocol) rpc.getProxy(ApplicationClientProtocol.class,
                rmAddress, conf);
          }
        });
    return clientRMWithDT;
  }

  class ClientRMServiceForTest extends ClientRMService {

    public ClientRMServiceForTest(Configuration conf,
        ResourceScheduler scheduler,
        RMDelegationTokenSecretManager rmDTSecretManager) {
      super(mock(RMContext.class), scheduler, mock(RMAppManager.class),
          new ApplicationACLsManager(conf),
          QueueACLsManager.getQueueACLsManager(scheduler, conf),
          rmDTSecretManager);
    }

    // Use a random port unless explicitly specified.
    @Override
    InetSocketAddress getBindAddress(Configuration conf) {
      return conf.getSocketAddr(YarnConfiguration.RM_ADDRESS,
          YarnConfiguration.DEFAULT_RM_ADDRESS, 0);
    }

    @Override
    protected void serviceStop() throws Exception {
      if (rmDTSecretManager != null) {
        rmDTSecretManager.stopThreads();
      }
      super.serviceStop();
    }

  }

  private static ResourceScheduler createMockScheduler(Configuration conf) {
    ResourceScheduler mockSched = mock(ResourceScheduler.class);
    doReturn(BuilderUtils.newResource(512, 0)).when(mockSched)
        .getMinimumResourceCapability();
    doReturn(BuilderUtils.newResource(5120, 0)).when(mockSched)
        .getMaximumResourceCapability();
    return mockSched;
  }

  private static RMDelegationTokenSecretManager
      createRMDelegationTokenSecretManager(long secretKeyInterval,
          long tokenMaxLifetime, long tokenRenewInterval) {
    ResourceManager rm = mock(ResourceManager.class);
    RMContext rmContext = mock(RMContext.class);
    when(rmContext.getStateStore()).thenReturn(new NullRMStateStore());
    when(rm.getRMContext()).thenReturn(rmContext);
    when(rmContext.getResourceManager()).thenReturn(rm);

    RMDelegationTokenSecretManager rmDtSecretManager =
        new RMDelegationTokenSecretManager(secretKeyInterval, tokenMaxLifetime,
          tokenRenewInterval, 3600000, rmContext);
    return rmDtSecretManager;
  }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>

#include "../ows/ows.h"

/*
 * Initialize wfs_request structure
 */
wfs_request *wfs_request_init()
{
  wfs_request *wr;

  wr = malloc(sizeof(wfs_request));
  assert(wr);

  wr->request = WFS_REQUEST_UNKNOWN;
  wr->format = WFS_FORMAT_UNKNOWN;
  wr->typename = NULL;
  wr->propertyname = NULL;
  wr->bbox = NULL;
  wr->srs = NULL;

  wr->maxfeatures = -1;
  wr->featureid = NULL;
  wr->filter = NULL;
  wr->operation = NULL;
  wr->handle = NULL;
  wr->resulttype = NULL;
  wr->sortby = NULL;
  wr->sections = NULL;

  wr->insert_results = NULL;
  wr->delete_results = 0;
  wr->update_results = 0;

  return wr;
}

#ifdef OWS_DEBUG
/*
 * Print wfs_request structure
 */
void wfs_request_flush(wfs_request * wr, FILE * output)
{
  assert(wr && output);

  fprintf(output, "[\n");

  fprintf(output, " request -> %i\n", wr->request);
  fprintf(output, " format -> %i\n", wr->format);
  fprintf(output, " maxfeatures -> %i\n", wr->maxfeatures);

  if (wr->typename) {
    fprintf(output, " typename -> ");
    list_flush(wr->typename, output);
    fprintf(output, "\n");
  }

  if (wr->propertyname) {
    fprintf(output, "propertyname -> ");
    mlist_flush(wr->propertyname, output);
    fprintf(output, "\n");
  }

  if (wr->bbox) {
    fprintf(output, "bbox -> ");
    ows_bbox_flush(wr->bbox, output);
    fprintf(output, "\n");
  }

  if (wr->srs) {
    fprintf(output, "srs -> ");
    ows_srs_flush(wr->srs, output);
    fprintf(output, "\n");
  }

  if (wr->featureid) {
    fprintf(output, " featureid -> ");
    mlist_flush(wr->featureid, output);
    fprintf(output, "\n");
  }

  if (wr->filter) {
    fprintf(output, " filter -> ");
    list_flush(wr->filter, output);
    fprintf(output, "\n");
  }

  if (wr->operation) {
    fprintf(output, " operation -> ");
    buffer_flush(wr->operation, output);
    fprintf(output, "\n");
  }

  if (wr->handle) {
    fprintf(output, " handle -> ");
    list_flush(wr->handle, output);
    fprintf(output, "\n");
  }

  if (wr->resulttype) {
    fprintf(output, " resulttype -> ");
    buffer_flush(wr->resulttype, output);
    fprintf(output, "\n");
  }

  if (wr->sortby) {
    fprintf(output, " sortby -> ");
    buffer_flush(wr->sortby, output);
    fprintf(output, "\n");
  }

  if (wr->sections) {
    fprintf(output, " sections -> ");
    list_flush(wr->sections, output);
    fprintf(output, "\n");
  }

  if (wr->insert_results) {
    fprintf(output, " insert_results -> ");
    alist_flush(wr->insert_results, output);
    fprintf(output, "\n");
  }

  fprintf(output, "]\n");
}
#endif

/*
 * Release wfs_request structure
 */
void wfs_request_free(wfs_request * wr)
{
  assert(wr);

  if (wr->typename)       list_free(wr->typename);
  if (wr->propertyname)   mlist_free(wr->propertyname);
  if (wr->bbox)           ows_bbox_free(wr->bbox);
  if (wr->srs)            ows_srs_free(wr->srs);
  if (wr->featureid)      mlist_free(wr->featureid);
  if (wr->filter)         list_free(wr->filter);
  if (wr->operation)      buffer_free(wr->operation);
  if (wr->handle)         list_free(wr->handle);
  if (wr->resulttype)     buffer_free(wr->resulttype);
  if (wr->sortby)         buffer_free(wr->sortby);
  if (wr->sections)       list_free(wr->sections);
  if (wr->insert_results) alist_free(wr->insert_results);

  free(wr);
  wr = NULL;
}

/*
 * Check if version is 1.0.0 or 1.1.0
 */
static void wfs_request_check_version(ows * o, wfs_request * wr, const array * cgi)
{
  assert(o && wr && cgi);

  if (!array_is_key(cgi, "version"))
    memcpy(o->request->version, o->wfs_default_version, sizeof(ows_version));

  if (ows_version_get(o->request->version) != 100 && ows_version_get(o->request->version) != 110)
    ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
              "VERSION parameter is not valid (use 1.0.0 or 1.1.0)", "version");
}

/*
 * Check and fill typename parameter
 * Return a list of layers' names
 */
static list *wfs_request_check_typename(ows * o, wfs_request * wr, list * layer_name)
{
  buffer *b, *n;
  list_node *ln;

  assert(o && wr && layer_name);

  if (array_is_key(o->cgi, "typename")) {
    b = array_get(o->cgi, "typename");
    wr->typename = list_explode(',', b);

    for (ln = wr->typename->first ; ln ; ln = ln->next) {

      n = ows_layer_prefix_to_uri(o->layers, ln->value);
      /* Check if layer exists and have storage */
      if (!n || !ows_layer_match_table(o, n)) {
        list_free(layer_name);
        wfs_error(o, wr, WFS_ERROR_LAYER_NOT_DEFINED, "Unknown layer name", "typename");
        return NULL;
      }

      /* Check if layer is retrievable */
      if ((wr->request == WFS_GET_FEATURE || wr->request == WFS_DESCRIBE_FEATURE_TYPE)
          && !ows_layer_retrievable(o->layers, n)) {
        list_free(layer_name);
        wfs_error(o, wr, WFS_ERROR_LAYER_NOT_RETRIEVABLE,
                  "Not retrievable layer(s), Forbidden operation.", "typename");
        return NULL;
      }

      /* Check if layer is writable, if request is a transaction operation */
      if (wr->operation && !ows_layer_writable(o->layers, n)) {
        list_free(layer_name);
        wfs_error(o, wr, WFS_ERROR_LAYER_NOT_WRITABLE,
                  "Not writable layer(s), Forbidden Transaction Operation", "typename");
        return NULL;
      }

      /* Fill the global layer name list */
      list_add_by_copy(layer_name, n);
    }
  }

  return layer_name;
}

/*
 * Check and fill the featureid parameter
 * Return a list of layers' names if typename parameter is not defined
 */
static list *wfs_request_check_fid(ows * o, wfs_request * wr, list * layer_name)
{
  list *fe;
  mlist *f;
  buffer *b, *layer;
  list_node *ln, *ln_tpn;
  mlist_node *mln = NULL;
  ln = ln_tpn = NULL;

  assert(o && wr && layer_name);

  /* Featureid is not a mandatory parameter */
  if (!array_is_key(o->cgi, "featureid")) return layer_name;

  b = array_get(o->cgi, "featureid");
  f = mlist_explode('(', ')', b);

  if (wr->typename) {
    /* Check if Typename and FeatureId size are similar */
    if (f->size != wr->typename->size) {
      mlist_free(f);
      wfs_error(o, wr, WFS_ERROR_INCORRECT_SIZE_PARAMETER,
                "featureid list and typename lists must have the same size", "");
      return NULL;
    }

    ln_tpn = wr->typename->first;
  }

  for (mln = f->first ; mln ; mln = mln->next) {
    for (ln = mln->value->first ; ln ; ln = ln->next) {
      fe = list_split('.', ln->value, true);

      /* Check the mapping between fid and typename */
      if (wr->typename && !buffer_cmp(fe->last->value, ln_tpn->value->buf)) {
        list_free(layer_name);
        list_free(fe);
        mlist_free(f);
        wfs_error(o, wr, WFS_ERROR_NO_MATCHING, "featureid values and typename values don't match", "");
        return NULL;
      }

      /* Check if featureid is well formed : layer.id */
      if (!fe->first->next) {
        list_free(layer_name);
        list_free(fe);
        mlist_free(f);
        ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE, "featureid must match layer.id", "GetFeature");
        return NULL;
      }

      layer = ows_layer_no_uri_to_uri(o->layers, fe->last->value);

      /* If typename is NULL, fill the layer name list */
      if (!wr->typename && !in_list(layer_name, layer))
        list_add_by_copy(layer_name, layer);

      /* Check if layer exists */
      if (!ows_layer_in_list(o->layers, layer)) {
        list_free(layer_name);
        list_free(fe);
        mlist_free(f);
        wfs_error(o, wr, WFS_ERROR_LAYER_NOT_DEFINED, "Unknown layer name", "GetFeature");
        return NULL;
      }

      /* Check if layer is retrievable if request is getFeature */
      if (wr->request == WFS_GET_FEATURE && !ows_layer_retrievable(o->layers, layer)) {
        list_free(layer_name);
        list_free(fe);
        mlist_free(f);
        wfs_error(o, wr, WFS_ERROR_LAYER_NOT_RETRIEVABLE,
                  "Not-retrievable layer(s), GetFeature Operation not allowed",
                  "GetFeature");
        return NULL;
      }

      /* Check if layer is writable if request is a transaction operation */
      if (wr->operation && !ows_layer_writable(o->layers, layer)) {
        list_free(layer_name);
        list_free(fe);
        mlist_free(f);
        wfs_error(o, wr, WFS_ERROR_LAYER_NOT_WRITABLE,
                  "Not-writable layer(s), Transaction Operation not allowed",
                  "Transaction");
        return NULL;
      }

      list_free(fe);
    }

    if (wr->typename) ln_tpn = ln_tpn->next;
  }

  wr->featureid = f;

  return layer_name;
}

/*
 * Check and fill the bbox and srsName parameter
 */
static void wfs_request_check_srs(ows * o, wfs_request * wr, list * layer_name)
{
  buffer *b;
  list_node *ln;
  int srid, srid_tmp;

  assert(o && wr && layer_name);

  wr->srs = ows_srs_init();

  /* srsName is not a mandatory parameter */
  if (!array_is_key(o->cgi, "srsname")) {

    /* We took the default SRS from the first requested layer */
    srid = ows_srs_get_srid_from_layer(o, layer_name->first->value);

    /* And check if all layers have the same SRS */
    if (wr->typename && wr->typename->first->next) {
      for (ln = layer_name->first->next ; ln ; ln = ln->next) {
        srid_tmp = ows_srs_get_srid_from_layer(o, ln->value);

        if (srid != srid_tmp) {
          ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
                    "Layers in TYPENAME must have the same SRS", "GetFeature");
          return;
        }
      }
    }

    if(!ows_srs_set_from_srid(o, wr->srs, srid)) {
      ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
                "The srsName value use an unsupported value, for requested layer(s)", "GetFeature");
      return;
    }

    if ((wr->format == WFS_GML311 || wr->format == WFS_GML321) && wr->srs->is_degree) {
      wr->srs->is_reverse_axis = true;
      wr->srs->is_long = true;
    } else if (wr->format == WFS_GML311 || wr->format == WFS_GML321) {
      wr->srs->is_long = true;
    } else if (ows_version_get(o->request->version) == 110 && wr->srs->is_degree) {
      wr->srs->is_reverse_axis = true;
      wr->srs->is_long = true;
    } else if (ows_version_get(o->request->version) == 110) {
      wr->srs->is_long = true;
    }

  } else {
    b = array_get(o->cgi, "srsname");
    if (!ows_srs_set_from_srsname(o, wr->srs, b->buf)) {
      ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
                "The srsName value use an unsupported value, for requested layer(s)", "GetFeature");
      return;
    }
  }
}

/*
 * Check and fill the bbox parameter
 */
static void wfs_request_check_bbox(ows * o, wfs_request * wr, list * layer_name)
{
  buffer *b;
  int srid = 4326; /* Default srid if not srs is provided since WFS 1.1.0 */

  assert(o && wr && layer_name && wr->srs);

  if (!array_is_key(o->cgi, "bbox")) return;  /* BBOX is not mandatory */

  b = array_get(o->cgi, "bbox");
  wr->bbox = ows_bbox_init();

  if (ows_version_get(o->request->version) == 100) srid = wr->srs->srid;

  if (!ows_bbox_set_from_str(o, wr->bbox, b->buf, srid)) {
    ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
              "Bad parameters for Bbox, must be Xmin,Ymin,Xmax,Ymax[,crsuri]", "NULL");
    return;
  }

  /* related to BBOX with crsuri and srsName issue like:
     bbox=34.94,-10.52,71.96,32.19,urn:ogc:def:crs:EPSG::4326
  */
  if (wr->srs->is_reverse_axis) wr->bbox->srs->is_reverse_axis = true;
}

/*
 * Check and fill the output parameter
 */
static void wfs_request_check_output(ows * o, wfs_request * wr)
{
  assert(o && wr);

  if (!array_is_key(o->cgi, "outputformat")) {
    /* put the default values according to WFS version and request name */
    if (ows_version_get(o->request->version) == 100) {
      wr->format = WFS_GML212;
    } else
      wr->format = WFS_GML311;
  } else {
         if (    buffer_cmp(array_get(o->cgi, "outputformat"), "GML2")
              || buffer_cmp(array_get(o->cgi, "outputformat"), "text/xml; subtype=gml/2.1.2"))
      wr->format = WFS_GML212;
    else if (    buffer_cmp(array_get(o->cgi, "outputformat"), "GML3")
              || buffer_cmp(array_get(o->cgi, "outputformat"), "text/xml; subtype=gml/3.1.1"))
      wr->format = WFS_GML311;
    else if (    buffer_cmp(array_get(o->cgi, "outputformat"), "JSON")
              || buffer_cmp(array_get(o->cgi, "outputformat"), "application/json"))
      wr->format = WFS_GEOJSON;
    else if (    wr->request == WFS_DESCRIBE_FEATURE_TYPE
              && buffer_cmp(array_get(o->cgi, "outputformat"), "XMLSCHEMA"))  // FIXME: really ?
      wr->format = WFS_XML_SCHEMA;
    else
      wfs_error(o, wr, WFS_ERROR_OUTPUT_FORMAT_NOT_SUPPORTED,
                "OutputFormat is not supported", "GetFeature");
  }
}

/*
 * Check and fill the resultType parameter
 */
static void wfs_request_check_resulttype(ows * o, wfs_request * wr)
{
  buffer *b;
  assert(o && wr);

  wr->resulttype = buffer_init();

  /* default value is 'results' */
  if (!array_is_key(o->cgi, "resulttype")) {
    buffer_add_str(wr->resulttype, "results");
    return;
  }

  b = array_get(o->cgi, "resulttype");

  if (buffer_cmp(b, "results") || buffer_cmp(b, "hits"))
    buffer_copy(wr->resulttype, b);
  else
    ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
              "ResultType isn't valid, must be results or hits", "resultType");
}

/*
 * Check and fill the sortBy parameter
 */
static void wfs_request_check_sortby(ows * o, wfs_request * wr, list * layer_name)
{
  buffer *b;
  list *l, *fe;
  list_node *ln = NULL;

  assert(o && wr);
  /* sortBy is not a mandatory parameter */
  if (!array_is_key(o->cgi, "sortby")) return;

  b = array_get(o->cgi, "sortby");
  wr->sortby = buffer_init();
  l = list_explode(',', b);

  for (ln = l->first ; ln ; ln = ln->next) {
    fe = list_explode(' ', ln->value);
    wfs_request_remove_prop_ns_prefix(o, fe->first->value, layer_name);

    /* Add quotation marks */
    buffer_add_head_str(fe->first->value, "\"");
    buffer_add_str(fe->first->value, "\"");

    /* SQL Order syntax */
    if (fe->last->value && fe->last != fe->first) {
      if (buffer_cmp(fe->last->value, "D") || buffer_cmp(fe->last->value, "DESC")) {
        buffer_empty(fe->last->value);
        buffer_add_str(fe->last->value, "DESC");
      } else {
        buffer_empty(fe->last->value);
        buffer_add_str(fe->last->value, "ASC");
      }
    }

    buffer_copy(wr->sortby, fe->first->value);
    buffer_add_str(wr->sortby, " ");

    if (fe->last->value && fe->last != fe->first)
      buffer_copy(wr->sortby, fe->last->value);
    else buffer_add_str(wr->sortby, "ASC");

    if (ln->next) buffer_add_str(wr->sortby, ",");

    list_free(fe);
  }

  list_free(l);
}

/*
 * Check and fill the maxFeatures parameter
 */
static void wfs_request_check_maxfeatures(ows * o, wfs_request * wr)
{
  int mf;
  buffer *b;

  assert(o && wr);

  /* maxFeatures is not a mandatory parameter */
  if (!array_is_key(o->cgi, "maxfeatures")) return;

  b = array_get(o->cgi, "maxfeatures");
  mf = atoi(b->buf);

  if (mf > 0) wr->maxfeatures = mf;
  else ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
                   "MaxFeatures isn't valid, must be > 0", "GetFeature");
}

/*
 * TODO
 */
buffer *wfs_request_remove_prop_ns_prefix(ows * o, buffer * prop, list * layer_name)
{
  list * ns;
  list_node * ln;

  assert(o && prop && layer_name);

  ns = ows_layer_list_ns_prefix(o->layers, layer_name);

  for (ln = ns->first ; ln ; ln = ln->next) {
    if (buffer_ncmp(ln->value, prop->buf, ln->value->use)) {
      buffer_shift(prop, ln->value->use + 1);  /* +1 for : separator */
      list_free(ns);
      return prop;
    }
  }

  list_free(ns);
  return prop;  /* if ns_prefix don't match, just don't do anything */
}

/*
 * Check and fill the propertyName parameter
 */
static void wfs_request_check_propertyname(ows * o, wfs_request * wr, list * layer_name)
{
  mlist *f;
  buffer *b;
  array *prop_table;
  list_node *ln, *ln_tpn;
  mlist_node *mln = NULL;

  ln = ln_tpn = NULL;

  assert(o && wr && layer_name);

  /* propertyName is not a mandatory parameter */
  if (!array_is_key(o->cgi, "propertyname")) return;

  b = array_get(o->cgi, "propertyname");
  f = mlist_explode('(', ')', b);

  /*check if propertyname size and typename or fid size are similar */
  if (f->size != layer_name->size) {
    mlist_free(f);
    wfs_error(o, wr, WFS_ERROR_INCORRECT_SIZE_PARAMETER,
              "propertyname list size and typename list size must be similar", "GetFeature");
    return;
  }

  for (mln = f->first, ln_tpn = layer_name->first ; mln ; mln = mln->next, ln_tpn = ln_tpn->next) {
    prop_table = ows_psql_describe_table(o, ln_tpn->value);

    for (ln = mln->value->first ; ln ; ln = ln->next) {

      /* if propertyname is an Xpath expression */
      if (check_regexp(ln->value->buf, "\\*\\["))
        ln->value = fe_xpath_property_name(o, ln_tpn->value, ln->value);

      /* check if propertyname values are correct */
      ln->value = wfs_request_remove_prop_ns_prefix(o, ln->value, layer_name);
      if (!buffer_cmp(ln->value, "*") && !array_is_key(prop_table, ln->value->buf)) {
        mlist_free(f);
        ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
                  "PropertyName values not available", "GetFeature");
        return;
      }
    }
  }

  wr->propertyname = f;
}

/*
 * Check and fill the filter parameter
 */
static void wfs_request_check_filter(ows * o, wfs_request * wr)
{
  buffer *b, *filter;
  assert(o && wr);

  if (!array_is_key(o->cgi, "filter")) return; /* Filter is not mandatory */

  b = array_get(o->cgi, "filter");
  filter = buffer_init();
  buffer_copy(filter, b);
  wr->filter = list_explode_start_end('(', ')', filter);

  if (wr->filter->size != wr->typename->size)
    wfs_error(o, wr, WFS_ERROR_INCORRECT_SIZE_PARAMETER,
              "Filter list size and typename list size must be similar", "GetFeature");

  buffer_free(filter);
}

/*
 * Check and fill the operation parameter
 * Only used for GET method and Delete Operation
 */
static void wfs_request_check_operation(ows * o, wfs_request * wr)
{
  assert(o && wr);

  /* OPERATION parameter is mandatory */
  if (!array_is_key(o->cgi, "operation")) {
    ows_error(o, OWS_ERROR_MISSING_PARAMETER_VALUE, "Operation (Delete) must be specified", "Operation");
    return;
  }

  wr->operation = buffer_init();
  buffer_copy(wr->operation, array_get(o->cgi, "operation"));

  if (!buffer_cmp(wr->operation, "Delete")) {
    ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
              "Only Delete operation is supported with GET method, use POST method for insert and update operations",
              "Transaction");
    return;
  }
}

/*
 * Check global parameters validity
 */
static void wfs_request_check_parameters(ows * o, wfs_request * wr)
{
  assert(o && wr);

  if (!array_is_key(o->cgi, "typename") && !array_is_key(o->cgi, "featureid")) {
    ows_error(o, OWS_ERROR_MISSING_PARAMETER_VALUE, "TYPENAME or FEATUREID must be set", "request");
    return;
  }

  /* Test mutually exclusive parameters (FILTER, BBOX and FEATUREID) */
  if (    (array_is_key(o->cgi, "filter") && array_is_key(o->cgi, "bbox"))
       || (array_is_key(o->cgi, "filter") && array_is_key(o->cgi, "featureid"))
       || (array_is_key(o->cgi, "bbox")   && array_is_key(o->cgi, "featureid")))
    wfs_error(o, wr, WFS_ERROR_EXCLUSIVE_PARAMETERS,
              "FILTER, BBOX and FEATUREID are mutually exclusive, just use one of these parameters", "request");
}

/*
 * Check and fill all WFS get_capabilities parameter
 */
static void wfs_request_check_get_capabilities(ows * o, wfs_request * wr, const array * cgi)
{
  buffer *b;
  list *l;
  list_node *ln = NULL;
  bool version = false;

  assert(o && wr && cgi);

  /* If key version is not set, version = higher version */
  if (!array_is_key(cgi, "version")) {
    ows_version_set(o->request->version, 1, 1, 0);
  } else {
    if (ows_version_get(o->request->version) < 110) ows_version_set(o->request->version, 1, 0, 0);
    else if (ows_version_get(o->request->version) > 110) ows_version_set(o->request->version, 1, 1, 0);
  }

  /* 1.1.0 parameter : uses the first valid version */
  if (array_is_key(cgi, "acceptversions")) {
    b = array_get(cgi, "acceptversions");
    l = list_explode(',', b);

    for (ln = l->first ; ln ; ln = ln->next) {
      if (version == false) {
        if (buffer_cmp(ln->value, "1.0.0")) {
          ows_version_set(o->request->version, 1, 0, 0);
          version = true;
        } else if (buffer_cmp(ln->value, "1.1.0")) {
          ows_version_set(o->request->version, 1, 1, 0);
          version = true;
        }
      }
    }

    list_free(l);
    /* if versions weren't 1.0.0 or 1.1.0, raise an error */
    if (version == false) {
      ows_error(o, OWS_ERROR_VERSION_NEGOTIATION_FAILED,
                "VERSION parameter is not valid (use 1.0.0 or 1.1.0)",
                "AcceptVersions");
      return;
    }
  }

  /* FIXME updateSequence is not yet implemented */
  if (array_is_key(cgi, "updatesequence")) {
    b = array_get(cgi, "updatesequence");

    if (!buffer_cmp(b, "0")) {
      ows_error(o, OWS_ERROR_INVALID_UPDATE_SEQUENCE,
                "UPDATESEQUENCE value must be omit or 0, function not (yet) implemented",
                "updateSequence");
      return;
    }
  }

  /* Sections */
  if (array_is_key(cgi, "sections")) {
    b = array_get(cgi, "sections");
    l = list_explode(',', b);
    wr->sections = l;
  }

  /* AcceptFormats */
  if (array_is_key(cgi, "acceptformats")) {
    b = array_get(cgi, "acceptformats");

         if (buffer_cmp(b, "text/xml"))        wr->format = WFS_TEXT_XML;
    else if (buffer_cmp(b, "application/xml")) wr->format = WFS_APPLICATION_XML;
    else ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
                     "Not supported format : use text/xml or application/xml", "acceptFormats");
  }
}

/*
 * Check and fill all WFS describe_feature_type parameter
 */
static void wfs_request_check_describe_feature_type(ows * o, wfs_request * wr, const array * cgi)
{
  list *layer_name;
  ows_layer_node *ln = NULL;
  assert(o && wr && cgi);

  wfs_request_check_output(o, wr); /* OutputFormat */
  if(o->exit) return;

  /* Typename */
  layer_name = list_init();
  layer_name = wfs_request_check_typename(o, wr, layer_name);
  if(o->exit) return;
  list_free(layer_name);

  /* if no Typename parameter is given, retrieve all layers defined in configuration file */
  if (!array_is_key(cgi, "typename")) {
    wr->typename = list_init();

    for (ln = o->layers->first ; ln ; ln = ln->next)
      if (ows_layer_match_table(o, ln->layer->name))
        list_add_by_copy(wr->typename, ln->layer->name_prefix);
  }
}

/*
 * Check anf fill parameters of GetFeature request
 */
static void wfs_request_check_get_feature(ows * o, wfs_request * wr, const array * cgi)
{
  list *layer_name;
  assert(o && wr && cgi);

  wfs_request_check_parameters(o, wr);  /* Check parameters validity */

  layer_name = list_init();

  /* TypeName (required except if there is a FeatureId parameter) */
  if (!o->exit) layer_name = wfs_request_check_typename(o, wr, layer_name);

  /* FeatureId, if no TypeName defined, list of layer_name must be extracted from FeatureId */
  if (!o->exit) layer_name = wfs_request_check_fid(o, wr, layer_name);

  if (!o->exit) wfs_request_check_srs(o, wr, layer_name);          /* srsName */
  if (!o->exit) wfs_request_check_bbox(o, wr, layer_name);         /* BBOX=xmin,ymin,xmax,ymax[,srs] */
  if (!o->exit) wfs_request_check_propertyname(o, wr, layer_name); /* PropertyName */
  if (!o->exit) wfs_request_check_output(o, wr);                   /* outputFormat */
  if (!o->exit) wfs_request_check_resulttype(o, wr);               /* resultType */
  if (!o->exit) wfs_request_check_sortby(o, wr, layer_name);       /* sortBy */
  if (!o->exit) wfs_request_check_maxfeatures(o, wr);              /* maxFeatures */
  if (!o->exit) wfs_request_check_filter(o, wr);                   /* Filter */

  if (layer_name) list_free(layer_name);
}

/*
 * Check anf fill parameters of Transaction request
 */
static void wfs_request_check_transaction(ows * o, wfs_request * wr, const array * cgi)
{
  list *layer_name;
  assert(o && wr && cgi);

  layer_name = list_init();

  if (!o->exit) wfs_request_check_operation(o, wr);                         /* Operation */
  if (!o->exit) wfs_request_check_parameters(o, wr);                        /* General checks */
  if (!o->exit) layer_name = wfs_request_check_typename(o, wr, layer_name); /* Typename */
  if (!o->exit) layer_name = wfs_request_check_fid(o, wr, layer_name);      /* FeatureId */
  if (!o->exit) wfs_request_check_bbox(o, wr, layer_name);                  /* Bbox */
  if (!o->exit) wfs_request_check_filter(o, wr);                            /* Filter */

  list_free(layer_name);
}

/*
 * Check if wfs_request is valid
 */
void wfs_request_check(ows * o, wfs_request * wr, const array * cgi)
{
  buffer *b;
  assert(o && wr && cgi);

  b = array_get(cgi, "request");

  /* Service */
  if (o->request->service != WFS) {
    ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE, "bad service, should be WFS", "SERVICE");
    return;
  }

  /* Version */
  if (!buffer_case_cmp(b, "GetCapabilities")) {
    wfs_request_check_version(o, wr, cgi);
    if (o->exit) return;
  }

  /* Request */
  if (buffer_case_cmp(b, "GetCapabilities")) {
    wr->request = WFS_GET_CAPABILITIES;
    wfs_request_check_get_capabilities(o, wr, cgi);

  } else if (buffer_case_cmp(b, "DescribeFeatureType")) {
    wr->request = WFS_DESCRIBE_FEATURE_TYPE;
    wfs_request_check_describe_feature_type(o, wr, cgi);

  } else if (buffer_case_cmp(b, "GetFeature")) {
    wr->request = WFS_GET_FEATURE;
    wfs_request_check_get_feature(o, wr, cgi);

  } else if (buffer_case_cmp(b, "Transaction")) {
    wr->request = WFS_TRANSACTION;
    if (cgi_method_get()) wfs_request_check_transaction(o, wr, cgi);

  } else ows_error(o, OWS_ERROR_OPERATION_NOT_SUPPORTED,
                     "REQUEST is not supported", "REQUEST");
}

/*
 * Main function to call the right action's function
 */
void wfs(ows * o, wfs_request * wf)
{
  buffer *op;
  assert(o && wf);

  /* Run the request's execution */
  switch (wf->request) {
    case WFS_GET_CAPABILITIES:
      wfs_get_capabilities(o, wf);
      break;

    case WFS_DESCRIBE_FEATURE_TYPE:
      wfs_describe_feature_type(o, wf);
      break;

    case WFS_GET_FEATURE:
      wfs_get_feature(o, wf);
      break;

    case WFS_TRANSACTION:

      if (cgi_method_get()) {
        if (buffer_cmp(wf->operation, "Delete"))
          wfs_delete(o, wf);
        else {
          ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE,
                    "Only Delete Operation is supported with GET method, use POST instead for Insert and Update.",
                    "Transaction");
          return;
        }

      } else {
        if (array_is_key(o->cgi, "operations")) {
          op = array_get(o->cgi, "operations");
          wfs_parse_operation(o, wf, op);
        } else {
          ows_error(o, OWS_ERROR_INVALID_PARAMETER_VALUE, "Operation parameter must be set", "Transaction");
          return;
        }
      }

      break;

    default:  assert(0); /* Should not happen */
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mobilepayment"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mobilepayment.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.mobilepayment.paymentbalance" android:label="@string/app_name" ></activity>
    </application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>


text:
<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
extract($blog_settings);
$c = Page::getCurrentPage();
$dh = Core::make('helper/date');
if (count($cArray) > 0) { ?>

    <?php
    for ($i = 0; $i < count($cArray); $i++ ) {
        $cobj = $cArray[$i];

        extract($blogify->getBlogVars($cobj));

        $content = $controller->getContent($cobj,$blog_settings);
        ?>
             <article class="entry row <?php  echo $entryClasses?>">

<a href="<?php   echo $url; ?>"><?php   echo $blogTitle?>

                    <time class="date" datetime="<?php echo $date?>">
                        <?php echo $dh->formatCustom('M',$blogDate)?>
                        <?php echo $dh->formatCustom('d',$blogDate)?>
                        <?php echo $dh->formatCustom('Y',$blogDate)?>
                    </time>

                        <?php  echo $blogify->closetags($content); ?>

                    <?php   if ($comments) { ?>

<?php   echo $comment_count;?>

                    <?php   } ?>
                    <a class="btn btn-default btnEntry" href="<?php echo $url?>"><?php  echo t('Read More')?>

    <?php
    }
    $u = new User();
    $subscribed = $c->getAttribute('subscription');
    if ($subscribe && $u->isLoggedIn()) {
        if ($subscribed && in_array($u->getUserID(),$subscribed)) {
            $subscribed_status = true;
        }
        ?>

            <a href="<?php   echo $subscribe_link; ?>?blog=<?php   echo $cParentID; ?>&user=<?php   echo $u->getUserID(); ?>" onClick="javascript:;" class="subscribe_to_blog btn btn-default btn-small" data-status="<?php       if ($subscribed_status) { echo 'unsubscribe';} else { echo 'subscribed';}?>"> <?php       if ($subscribed_status) {echo t('Unsubscribe from this Blog'); } else { echo t('Subscribe to this Blog'); }?>

        <?php
    }
    if (!$previewMode && $controller->rss) {
        ?>

                <img src="<?php   echo $rss_img_url; ?>" width="25" alt="iCal feed"/>
                <a href="<?php  echo URL::to('/problog/routes/rss')?>?bID=<?php   echo $blogBockID; ?>&problogRss=true&ordering=<?php   echo $ordering; ?>" id="getFeed"><?php   echo t('get RSS feed'); ?>

            <link href="<?php  echo URL::to('/problog/routes/rss')?>?bID=<?php   echo $blogBockID; ?>&problogRss=true" rel="alternate" type="application/rss+xml" title="<?php   echo t('RSS'); ?>"/>

        <?php
        }
        ?>

<?php    } ?>

<?php   if ($paginate): ?>
    <?php   echo $pagination; ?>
<?php   endif; ?>


text:
using UnityEngine;
using System;
using System.Collections.Generic;

public class AdSwitcherConfig {
	public string Category;
	public AdSwitchType SwitchType;
	public int Interval;
	public List<AdConfig> AdConfigList;
}


text:
import React from "react"
import PropTypes from "prop-types"
import ReactMarkdown from "react-markdown"
import { Parser, HtmlRenderer } from "commonmark"
import { OAS3ComponentWrapFactory } from "../helpers"
import { sanitizer } from "core/components/providers/markdown"

export const Markdown = ({ source }) => {
  if ( source ) {
    const parser = new Parser()
    const writer = new HtmlRenderer()
    const html = writer.render(parser.parse(source || ""))
    const sanitized = sanitizer(html)

    if ( !source || !html || !sanitized ) {
        return null
    }

    return (
      <ReactMarkdown
        source={sanitized}
        className={"renderedMarkdown"}
      />
    )
  }
  return null
}
Markdown.propTypes = {
  source: PropTypes.string
}

export default OAS3ComponentWrapFactory(Markdown)


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Linn. Soc. London 30:402. 1875; C. F. P. von Martius, Fl. bras. 15(2):331. 1876

#### Original name
null

### Remarks
null


text:
def _safe_print(u, errors="replace"):
    """Safely print the given string.

    If you want to see the code points for unprintable characters then you
    can use `errors="xmlcharrefreplace"`.
    """
    s = u.encode(sys.stdout.encoding or "utf-8", errors)
    print(s)


text:
package no.agens.depth.lib;

import android.content.res.ColorStateList;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.RippleDrawable;

public class RippleHelper {
  public static RippleDrawable getPressedColorRippleDrawable(int normalColor, int pressedColor) {
    return new RippleDrawable(getPressedColorSelector(normalColor, pressedColor),
        getColorDrawableFromColor(normalColor), null);
  }

  public static ColorStateList getPressedColorSelector(int normalColor, int pressedColor) {
    return new ColorStateList(new int[][] {
        new int[] { android.R.attr.state_pressed }, new int[] { android.R.attr.state_focused },
        new int[] { android.R.attr.state_activated }, new int[] {}
    }, new int[] {
        pressedColor, pressedColor, pressedColor, normalColor
    });
  }

  public static ColorDrawable getColorDrawableFromColor(int color) {
    return new ColorDrawable(color);
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rhizocarpon riparium var. insulata Szatala

### Remarks
null


text:
package androidx.work;

import android.net.Network;
import android.net.Uri;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.work.impl.utils.taskexecutor.TaskExecutor;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;

/**
 * Setup parameters for a {@link ListenableWorker}.
 */

public final class WorkerParameters {

    private @NonNull UUID mId;
    private @NonNull Data mInputData;
    private @NonNull Set<String> mTags;
    private @NonNull RuntimeExtras mRuntimeExtras;
    private int mRunAttemptCount;
    private @NonNull Executor mBackgroundExecutor;
    private @NonNull TaskExecutor mWorkTaskExecutor;
    private @NonNull WorkerFactory mWorkerFactory;
    private @NonNull ProgressUpdater mProgressUpdater;
    private @NonNull ForegroundUpdater mForegroundUpdater;
    private int mGeneration;

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public WorkerParameters(
            @NonNull UUID id,
            @NonNull Data inputData,
            @NonNull Collection<String> tags,
            @NonNull RuntimeExtras runtimeExtras,
            @IntRange(from = 0) int runAttemptCount,
            @IntRange(from = 0) int generation,
            @NonNull Executor backgroundExecutor,
            @NonNull TaskExecutor workTaskExecutor,
            @NonNull WorkerFactory workerFactory,
            @NonNull ProgressUpdater progressUpdater,
            @NonNull ForegroundUpdater foregroundUpdater) {
        mId = id;
        mInputData = inputData;
        mTags = new HashSet<>(tags);
        mRuntimeExtras = runtimeExtras;
        mRunAttemptCount = runAttemptCount;
        mGeneration = generation;
        mBackgroundExecutor = backgroundExecutor;
        mWorkTaskExecutor = workTaskExecutor;
        mWorkerFactory = workerFactory;
        mProgressUpdater = progressUpdater;
        mForegroundUpdater = foregroundUpdater;
    }

    /**
     * Gets the ID of the {@link WorkRequest} that created this {@link ListenableWorker}.
     *
     * @return The ID of the creating {@link WorkRequest}
     */
    public @NonNull UUID getId() {
        return mId;
    }

    /**
     * Gets the input data.  Note that in the case that there are multiple prerequisites for this
     * {@link ListenableWorker}, the input data has been run through an {@link InputMerger}.
     *
     * @return The input data for this work
     * @see OneTimeWorkRequest.Builder#setInputMerger(Class)
     */
    public @NonNull Data getInputData() {
        return mInputData;
    }

    /**
     * Gets a {@link java.util.Set} of tags associated with this Worker's {@link WorkRequest}.
     *
     * @return The {@link java.util.Set} of tags associated with this Worker's {@link WorkRequest}
     * @see WorkRequest.Builder#addTag(String)
     */
    public @NonNull Set<String> getTags() {
        return mTags;
    }

    /**
     * Gets the list of content {@link android.net.Uri}s that caused this Worker to execute.  See
     * @code JobParameters#getTriggeredContentUris()} for relevant {@code JobScheduler} code.
     *
     * @return The list of content {@link android.net.Uri}s that caused this Worker to execute
     * @see Constraints.Builder#addContentUriTrigger(android.net.Uri, boolean)
     */
    @RequiresApi(24)
    public @NonNull List<Uri> getTriggeredContentUris() {
        return mRuntimeExtras.triggeredContentUris;
    }

    /**
     * Gets the list of content authorities that caused this Worker to execute.  See
     * {@code JobParameters#getTriggeredContentAuthorities()} for relevant {@code JobScheduler}
     * code.
     *
     * @return The list of content authorities that caused this Worker to execute
     */
    @RequiresApi(24)
    public @NonNull List<String> getTriggeredContentAuthorities() {
        return mRuntimeExtras.triggeredContentAuthorities;
    }

    /**
     * Gets the {@link android.net.Network} to use for this Worker.  This method returns
     * {@code null} if there is no network needed for this work request.
     *
     * @return The {@link android.net.Network} specified by the OS to be used with this Worker
     */
    @RequiresApi(28)
    public @Nullable Network getNetwork() {
        return mRuntimeExtras.network;
    }

    /**
     * Gets the current run attempt count for this work.  Note that for periodic work, this value
     * gets reset between periods.
     *
     * @return The current run attempt count for this work.
     */
    @IntRange(from = 0)
    public int getRunAttemptCount() {
        return mRunAttemptCount;
    }

    /**
     * Gets the generation of this Worker.
     * <p>
     * A work has multiple generations, if it was updated via
     * {@link WorkManager#updateWork(WorkRequest)} or
     * {@link WorkManager#enqueueUniquePeriodicWork(String,
     * ExistingPeriodicWorkPolicy, PeriodicWorkRequest)} using
     * {@link ExistingPeriodicWorkPolicy#UPDATE}.
     * This worker can possibly be of an older generation rather than latest known,
     * if an update has happened while this worker is running.
     *
     * @return a generation of this work.
     */
    @IntRange(from = 0)
    public int getGeneration() {
        return mGeneration;
    }

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public @NonNull Executor getBackgroundExecutor() {
        return mBackgroundExecutor;
    }

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public @NonNull TaskExecutor getTaskExecutor() {
        return mWorkTaskExecutor;
    }

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public @NonNull WorkerFactory getWorkerFactory() {
        return mWorkerFactory;
    }

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public @NonNull ProgressUpdater getProgressUpdater() {
        return mProgressUpdater;
    }

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public @NonNull ForegroundUpdater getForegroundUpdater() {
        return mForegroundUpdater;
    }

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public @NonNull RuntimeExtras getRuntimeExtras() {
        return mRuntimeExtras;
    }

    /**
     * Extra runtime information for Workers.
     *
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static class RuntimeExtras {
        public @NonNull List<String> triggeredContentAuthorities = Collections.emptyList();
        public @NonNull List<Uri> triggeredContentUris = Collections.emptyList();

        @RequiresApi(28)
        @Nullable
        public Network network;
    }
}


text:
<?php
namespace LancerHe\Http\Request;

/**
 * Class RequestAbstract 抽象HTTP请求类
 *
 * @package LancerHe\Http\Request
 * @author  Lancer He <lancer.he@gmail.com>
 */
abstract class RequestAbstract {
    /**
     * 获取CURL Handler
     *
     * @return resource
     */
    abstract public function getHandler();

    /**
     * 获取response信息
     *
     * @return mixed
     */
    abstract public function getResponse();

    /**
     * 获取request信息
     *
     * @return mixed
     */
    abstract public function getRequest();

    /**
     * 发送HTTP请求
     *
     * @param  array  $post POST数据,null表示无post即GET请求
     * @param  string $url  请求的URL地址,可以通过包装类指定一个URL
     */
    abstract public function sendRequest($url = null, $post = null);

    /**
     * 解析HTTP请求返回的response数据
     */
    abstract public function parseResponse();
}


text:
require 'active_merchant/billing/compatibility'
require 'active_merchant/empty'

module ActiveMerchant
  module Billing
    class Model
      include Compatibility::Model
      include Empty

      def initialize(attributes = {})
        attributes.each do |key, value|
          send("#{key}=", value)
        end
      end

      def validate
        {}
      end

      private

      def errors_hash(array)
        array.inject({}) do |hash, (attribute, error)|
          (hash[attribute] ||= []) << error
          hash
        end
      end
    end
  end
end


text:
package plasticine

import "strings"

type CatApi struct {
	server *Server
	v      string
}

func (s *Server) Cat() *CatApi {
	return &CatApi{s, ""}
}
func (c *CatApi) V(v bool) {
	if v {
		c.v = c.v
	}
}
func (c *CatApi) Aliases() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "aliases"), c.v), c.server.hr).String()
}
func (c *CatApi) Allocation() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "allocation"), c.v), c.server.hr).String()
}

func (c *CatApi) Count(s ...string) (string, error) {
	if len(s) == 0 {
		return Get(c.server.getUrl(getPath("_cat", "count"), c.v), c.server.hr).String()
	} else {
		return Get(c.server.getUrl(getPath("_cat", "count", s[0]), c.v), c.server.hr).String()
	}
}

func (c *CatApi) Fielddata(q ...string) (string, error) {
	if len(q) == 0 {
		return Get(c.server.getUrl(getPath("_cat", "fielddata"), c.v), c.server.hr).String()
	} else {
		return Get(c.server.getUrl(getPath("_cat", "fielddata", strings.Join(q, ",")), c.v), c.server.hr).String()
	}
}

func (c *CatApi) Health() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "health"), c.v), c.server.hr).String()
}

func (c *CatApi) Indices(q ...string) (string, error) {
	if len(q) == 0 {
		return Get(c.server.getUrl(getPath("_cat", "indices"), c.v), c.server.hr).String()
	} else {
		return Get(c.server.getUrl(getPath("_cat", "indices", strings.Join(q, ",")), c.v), c.server.hr).String()
	}
}

func (c *CatApi) Master() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "master"), c.v), c.server.hr).String()
}

func (c *CatApi) Nodes() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "nodes"), c.v), c.server.hr).String()
}

func (c *CatApi) PendingTasks() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "pending_tasks"), c.v), c.server.hr).String()
}

func (c *CatApi) Plugins() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "plugins"), c.v), c.server.hr).String()
}

func (c *CatApi) Recovery() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "recovery"), c.v), c.server.hr).String()
}

func (c *CatApi) ThreadPool() (string, error) {
	return Get(c.server.getUrl(getPath("_cat", "thread_pool"), c.v), c.server.hr).String()
}

func (c *CatApi) Shards(q ...string) (string, error) {
	if len(q) == 0 {
		return Get(c.server.getUrl(getPath("_cat", "shards"), c.v), c.server.hr).String()
	} else {
		return Get(c.server.getUrl(getPath("_cat", "shards", strings.Join(q, ",")), c.v), c.server.hr).String()
	}
}


text:
import logging
import os
import sys

import tutum

from haproxy import Haproxy
from parser import parse_uuid_from_resource_uri

__version__ = '0.2'
tutum.user_agent = "tutum-haproxy/%s" % __version__

DEBUG = os.getenv("DEBUG", False)

logger = logging.getLogger("haproxy")

def run_haproxy():
    haproxy = Haproxy()
    haproxy.update()

def tutum_event_handler(event):
    logger.debug(event)
    # When service scale up/down or container start/stop/terminate/redeploy, reload the service
    if event.get("state", "") not in ["In progress", "Pending", "Terminating", "Starting", "Scaling", "Stopping"] and \
                    event.get("type", "").lower() in ["container", "service"] and \
                    len(set(Haproxy.cls_linked_services).intersection(set(event.get("parents", [])))) > 0:
        logger.info("Tutum event detected: %s %s is %s" %
                    (event["type"], parse_uuid_from_resource_uri(event.get("resource_uri", "")), event["state"]))
        run_haproxy()

    # Add/remove services linked to haproxy
    if event.get("state", "") == "Success" and Haproxy.cls_service_uri in event.get("parents", []):
        service = Haproxy.fetch_tutum_obj(Haproxy.cls_service_uri)
        service_endpoints = [srv.get("to_service") for srv in service.linked_to_service]
        if Haproxy.cls_linked_services != service_endpoints:
            removed = ", ".join(set(Haproxy.cls_linked_services) - set(service_endpoints))
            added = ", ".join(set(service_endpoints) - set(Haproxy.cls_linked_services))
            changes = "Tutum event detected:"
            if removed:
                changes += " linked removed: %s" % removed
            if added:
                changes += " linked added: %s" % added
            logger.info(changes)
            Haproxy.cls_linked_services = service_endpoints
            run_haproxy()

def main():
    logging.basicConfig(stream=sys.stdout)
    logging.getLogger("haproxy").setLevel(logging.DEBUG if DEBUG else logging.INFO)

    if Haproxy.cls_container_uri and Haproxy.cls_service_uri:
        if Haproxy.cls_tutum_auth:
            logger.info("HAProxy has access to Tutum API - will reload list of backends in real-time")
        else:
            logger.warning(
                "HAProxy doesn't have access to Tutum API and it's running in Tutum - you might want to give "
                "an API role to this service for automatic backend reconfiguration")
    else:
        logger.info("HAProxy is not running in Tutum")

    if Haproxy.cls_container_uri and Haproxy.cls_service_uri and Haproxy.cls_tutum_auth:
        events = tutum.TutumEvents()
        events.on_open(run_haproxy)
        events.on_message(tutum_event_handler)
        events.run_forever()
    else:
        run_haproxy()

if __name__ == "__main__":
    main()


text:
package rx.singles;

import rx.Single;
import rx.SingleSubscriber;
import rx.Subscription;
import rx.annotations.Experimental;
import rx.internal.operators.BlockingOperatorToFuture;
import rx.internal.util.BlockingUtils;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;

/**
 * {@code BlockingSingle} is a blocking "version" of {@link Single} that provides blocking
 * operators.
 *

 * You construct a {@code BlockingSingle} from a {@code Single} with {@link #from(Single)}
 * or {@link Single#toBlocking()}.
 */
@Experimental
public class BlockingSingle<T> {
    private final Single<? extends T> single;

    private BlockingSingle(Single<? extends T> single) {
        this.single = single;
    }

    /**
     * Converts a {@link Single} into a {@code BlockingSingle}.
     *
     * @param single the {@link Single} you want to convert
     * @return a {@code BlockingSingle} version of {@code single}
     */
    @Experimental
    public static <T> BlockingSingle<T> from(Single<? extends T> single) {
        return new BlockingSingle<T>(single);
    }

    /**
     * Returns the item emitted by this {@code BlockingSingle}.
     *

     * If the underlying {@link Single} returns successfully, the value emitted
     * by the {@link Single} is returned. If the {@link Single} emits an error,
     * the throwable emitted ({@link SingleSubscriber#onError(Throwable)}) is
     * thrown.
     *
     * @return the value emitted by this {@code BlockingSingle}
     */
    @Experimental
    public T value() {
        final AtomicReference<T> returnItem = new AtomicReference<T>();
        final AtomicReference<Throwable> returnException = new AtomicReference<Throwable>();
        final CountDownLatch latch = new CountDownLatch(1);
        Subscription subscription = single.subscribe(new SingleSubscriber<T>() {
            @Override
            public void onSuccess(T value) {
                returnItem.set(value);
                latch.countDown();
            }

            @Override
            public void onError(Throwable error) {
                returnException.set(error);
                latch.countDown();
            }
        });

        BlockingUtils.awaitForComplete(latch, subscription);
        Throwable throwable = returnException.get();
        if (throwable != null) {
            if (throwable instanceof RuntimeException) {
                throw (RuntimeException) throwable;
            }
            throw new RuntimeException(throwable);
        }
        return returnItem.get();
    }

    /**
     * Returns a {@link Future} representing the value emitted by this {@code BlockingSingle}.
     *
     * @return a {@link Future} that returns the value
     */
    @Experimental
    public Future<T> toFuture() {
        return BlockingOperatorToFuture.toFuture(single.toObservable());
    }
}


text:
var TableTenantUsersController = function(tenant, tenantUsers, $scope, $state, locationUtils) {

	$scope.tenant = tenant;

	$scope.tenantUsers = tenantUsers;

	$scope.editUser = function(id) {
		locationUtils.navigateToPath('/users/' + id);
	};

	$scope.refresh = function() {
		$state.reload(); // reloads all the resolves for the view
	};

	$scope.navigateToPath = locationUtils.navigateToPath;

	angular.element(document).ready(function () {
		$('#tenantUsersTable').dataTable({
			"aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
			"iDisplayLength": 25,
			"aaSorting": []
		});
	});

};

TableTenantUsersController.$inject = ['tenant', 'tenantUsers', '$scope', '$state', 'locationUtils'];
module.exports = TableTenantUsersController;


text:
const remote = require('electron').remote;
const dialog = remote.require('dialog');
import * as fs from 'fs';

import {default as writeConvertedFile} from './convert';

let filtersListOpen = [{
  name: 'GeoJSON',
  extensions: ['geojson']
}, {
  name: 'ESRI Shapefile',
  extensions: ['shp']
}, {
  name: 'OSM',
  extensions: ['osm']
}];

let filtersListClose = filtersListOpen.slice(0, 2);

let ioDialog  = {

  inputFileOpen: '',

  inputFileClosed: '',

  openFile: function () {
    dialog.showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: filtersListOpen,
    }, function (fileNames) {
      if (fileNames === undefined) {
        return;
      } else {
        var fileName = fileNames[0];
        // gdal.open(fileName, function () {
        //   document.getElementById("editor").value = 'Loaded data';
        // });
        // fs.readFile(fileName, 'utf-8', function (err, data) {
        //   document.getElementById("editor").value = data;
        // });
        // stores input file name
        this.inputFileOpen = fileName;
      }
    });
  },

  saveFile: function () {
    dialog.showSaveDialog({
      title: 'Save as',
      filters: filtersListClose,
    }, function (fileName, err) {
      if (fileName === undefined) return;
      // stores file name to be saved
      this.inputFileClosed = fileName;
      // stores crs to be saved
      function saveCRS() {
        // var crs = document.getElementById("crs")
        // var crs = this.refs.myInput.state.entryValue;
        var crs = this.refs
        console.log(crs);

        var number = +parseInt(crs);
        // console.log(Number.isInteger(crs));
        if (crs.value === "" || number != number) {
          dialog.showErrorBox('Error','Missing CRS');
        } else {
          console.log('it is a number');
          return number;
        }

      }
      var crs = saveCRS()
      console.log(writeConvertedFile);
        // funzione gdal per convertire e trasformare.
        // Uso gdal write al posto di fs writeFile per scrivere nuovo file
      writeConvertedFile(this.inputFileOpen, this.inputFileClosed, crs, err);
    });
  }

};

export default ioDialog;
// export { openFile, saveFile  };


text:
#region Copyright (c) 2013 James Snape
// <copyright file="ProductCategoryFileMap.cs" company="James Snape">
//  Copyright 2013 James Snape
//
//  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.
// </copyright>
#endregion

namespace Deeply.AdventureWorks.Loader.Domain
{
    using System;
    using CsvHelper.Configuration;

    /// <summary>
    /// CSV file map for product category.
    /// </summary>
    [CLSCompliant(false)]
    public class ProductCategoryFileMap : CsvClassMap<ProductCategory>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductCategoryFileMap"/> class.
        /// </summary>
        public ProductCategoryFileMap()
        {
            Map(m => m.AlternateKey).Index(0);
            Map(m => m.Name).Index(1);
        }
    }
}


text:
<?php

/* OfertaBundle:Default:portada.html.twig */
class __TwigTemplate_ff29c68cfdc78e2a6d319601dba62512 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::frontend.html.twig");

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'id' => array($this, 'block_id'),
            'article' => array($this, 'block_article'),
            'aside' => array($this, 'block_aside'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::frontend.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_title($context, array $blocks = array())
    {
        echo "Cupon, cada día ofertas increíbles en tu ciudad con
descuentos de hasta el 90%";
    }

    // line 4
    public function block_id($context, array $blocks = array())
    {
        echo "portada";
    }

    // line 5
    public function block_article($context, array $blocks = array())
    {
        echo "
";
        // line 6
        $this->env->loadTemplate("OfertaBundle:Default:includes/oferta.html.twig")->display($context);
    }

    // line 8
    public function block_aside($context, array $blocks = array())
    {
        echo " ... ";
    }

    public function getTemplateName()
    {
        return "OfertaBundle:Default:portada.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  53 => 8,  49 => 6,  44 => 5,  38 => 4,  31 => 2,);
    }
}


text:
typedef NS_ENUM( NSInteger, CZProximity ){
	CZProximityImmediate = 0,
	CZProximityNear = 1,
	CZProximityFar = 2,
	CZProximityUnknown = 99,
	CZProximityOut = 100		// Corrects the Apple SDK's poor enumeration type
};

extern NSInteger const CurtziBeaconOutOfRangeRSSI;		// Large negative value for RSSI when out of range

@interface CZTag : NSObject

@property (nonatomic,assign,readonly) NSInteger rssi;
@property (nonatomic,assign,readonly) CZProximity proximity;		// quantized, time-averaged proximity based on radio strength
@property (nonatomic,assign,readonly) NSUInteger distance;			// erratic estimate, using bluetooth radio strength, in meters
@property (nonatomic,assign,readonly) UInt16 major;
@property (nonatomic,assign,readonly) UInt16 minor;
@property (nonatomic,strong,readonly) NSString *uuid;

-(NSComparisonResult) compareProximity:(CZTag*) otherTag;

-(NSString*) proximityString;

@end