text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class AutofacCompositionContainerBuilder
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class AutofacCompositionContainerBuilder
   ">
    <meta name="generator" content="docfx 2.43.2.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class AutofacCompositionContainerBuilder

An Autofac composition container builder.

Inheritance

System.Object

CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>

AutofacCompositionContainerBuilder

Implements

ICompositionContainerBuilder

Inherited Members

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.LogManager

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.TypeLoader

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.AppRuntime

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.Logger

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.ConventionsBuilder

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.CompositionParts

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.Registry

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithConventionAssemblies(IEnumerable<Assembly>)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithConventionAssembly(Assembly)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithConventions(IConventionsBuilder)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithAssemblies(IEnumerable<Assembly>)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithAssembly(Assembly)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithParts(IEnumerable<Type>)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithPart(Type)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithFactory<TContract>(Func<TContract>, Boolean, Boolean)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithRegistration(IAppServiceInfo[])

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.WithConventionsRegistrar(IConventionsRegistrar)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.CreateContainer()

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.GetCompositionAssemblies()

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.GetConventionAssemblies(IEnumerable<Assembly>)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.GetConventions(IEnumerable<Assembly>, IList<Type>)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.AssertRequiredService<TService>(TService)

      CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>.GetSettings()

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.ToString()

Namespace: Kephas.Composition.Autofac.Hosting

Assembly: Kephas.Composition.Autofac.dll

Syntax

public class AutofacCompositionContainerBuilder : CompositionContainerBuilderBase<AutofacCompositionContainerBuilder>, ICompositionContainerBuilder

Constructors

    |
    <a href="https://github.com/kephas-software/kephas/new/master/apiSpec/new?filename=Kephas_Composition_Autofac_Hosting_AutofacCompositionContainerBuilder__ctor_Kephas_Composition_Hosting_ICompositionRegistrationContext_.md&value=---%0Auid%3A%20Kephas.Composition.Autofac.Hosting.AutofacCompositionContainerBuilder.%23ctor(Kephas.Composition.Hosting.ICompositionRegistrationContext)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

AutofacCompositionContainerBuilder(ICompositionRegistrationContext)

Initializes a new instance of the AutofacCompositionContainerBuilder class.

Declaration

public AutofacCompositionContainerBuilder(ICompositionRegistrationContext context)

Parameters

        Type
        Name
        Description

        ICompositionRegistrationContext
        context

The context.

Methods

    |
    <a href="https://github.com/kephas-software/kephas/new/master/apiSpec/new?filename=Kephas_Composition_Autofac_Hosting_AutofacCompositionContainerBuilder_CreateContainerCore_Kephas_Composition_Conventions_IConventionsBuilder_System_Collections_Generic_IEnumerable_System_Type__.md&value=---%0Auid%3A%20Kephas.Composition.Autofac.Hosting.AutofacCompositionContainerBuilder.CreateContainerCore(Kephas.Composition.Conventions.IConventionsBuilder%2CSystem.Collections.Generic.IEnumerable%7BSystem.Type%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

CreateContainerCore(IConventionsBuilder, IEnumerable<Type>)

Creates a new composition container based on the provided conventions and assembly parts.

Declaration

protected override ICompositionContext CreateContainerCore(IConventionsBuilder conventions, IEnumerable<Type> parts)

Parameters

        Type
        Name
        Description

        IConventionsBuilder
        conventions

The conventions.

        System.Collections.Generic.IEnumerable<System.Type>
        parts

The parts candidating for composition.

Returns

        Type
        Description

        ICompositionContext

A new composition container.

Overrides

Kephas.Composition.Hosting.CompositionContainerBuilderBase<Kephas.Composition.Autofac.Hosting.AutofacCompositionContainerBuilder>.CreateContainerCore(Kephas.Composition.Conventions.IConventionsBuilder, System.Collections.Generic.IEnumerable<System.Type>)

    |
    Improve this Doc

    View Source

CreateConventionsBuilder()

Factory method for creating the conventions builder.

Declaration

protected override IConventionsBuilder CreateConventionsBuilder()

Returns

        Type
        Description

        IConventionsBuilder

A newly created conventions builder.

Overrides

Kephas.Composition.Hosting.CompositionContainerBuilderBase<Kephas.Composition.Autofac.Hosting.AutofacCompositionContainerBuilder>.CreateConventionsBuilder()

    |
    <a href="https://github.com/kephas-software/kephas/new/master/apiSpec/new?filename=Kephas_Composition_Autofac_Hosting_AutofacCompositionContainerBuilder_WithConfig_System_Action_Autofac_ContainerBuilder__.md&value=---%0Auid%3A%20Kephas.Composition.Autofac.Hosting.AutofacCompositionContainerBuilder.WithConfig(System.Action%7BAutofac.ContainerBuilder%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

WithConfig(Action<ContainerBuilder>)

Adds a builder configuration action.

Declaration

public AutofacCompositionContainerBuilder WithConfig(Action<ContainerBuilder> config)

Parameters

        Type
        Name
        Description

        System.Action<Autofac.ContainerBuilder>
        config

The configuration.

Returns

        Type
        Description

        AutofacCompositionContainerBuilder

This builder.

    |
    <a href="https://github.com/kephas-software/kephas/new/master/apiSpec/new?filename=Kephas_Composition_Autofac_Hosting_AutofacCompositionContainerBuilder_WithContainerBuilder_Autofac_ContainerBuilder_.md&value=---%0Auid%3A%20Kephas.Composition.Autofac.Hosting.AutofacCompositionContainerBuilder.WithContainerBuilder(Autofac.ContainerBuilder)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

WithContainerBuilder(ContainerBuilder)

Sets the container builder to be used for the composition.

Declaration

public AutofacCompositionContainerBuilder WithContainerBuilder(ContainerBuilder builder)

Parameters

        Type
        Name
        Description

        Autofac.ContainerBuilder
        builder

The builder.

Returns

        Type
        Description

        AutofacCompositionContainerBuilder

This builder.

Implements

      ICompositionContainerBuilder

Extension Methods

      DynamicObjectExtensions.SetPropertyValue(Object, String, Object)

      DynamicObjectExtensions.TrySetPropertyValue(Object, String, Object)

      DynamicObjectExtensions.GetPropertyValue(Object, String)

      DynamicObjectExtensions.TryGetPropertyValue(Object, String, out Object)

      DynamicObjectExtensions.GetRuntimeTypeInfo(Object)

      DynamicObjectExtensions.ToDynamic(Object)

      DynamicObjectExtensions.ToExpando(Object)

      BehaviorValue.ToBehaviorValue<TValue>(TValue)

      CollectionExtensions.AddRange<T, TItem>(T, IEnumerable<TItem>)

      LoggingExtensions.GetLogger(Object, IContext)

      TypeExtensions.GetAbstractType(Object)

      TypeExtensions.GetAbstractTypeInfo(Object)

      ReflectionHelper.GetTypeInfo(Object)

      EntityEntryExtensions.TryGetAttachedEntityEntry(Object)

                    Improve this Doc

                    View Source

              Back to top

            Generated by DocFX


text:
package com.intellij.java.codeInsight.daemon.quickFix;

import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.quickFix.ActionHint;
import com.intellij.codeInsight.daemon.quickFix.LightQuickFixTestCase;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.roots.OrderEntry;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;

import java.util.Collection;
import java.util.List;

/**
 * @author cdr
 */
public class OrderEntryTest extends DaemonAnalyzerTestCase {
  @NonNls public static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/quickFix/orderEntry/";

  @Override
  protected void setUpProject() throws Exception {
    final String root = PathManagerEx.getTestDataPath() + BASE_PATH;

    VirtualFile tempProjectRootDir =
      PsiTestUtil.createTestProjectStructure(getTestName(true), null, FileUtil.toSystemIndependentName(root), myFilesToDelete, false);

    VirtualFile projectFile = tempProjectRootDir.findChild("orderEntry.ipr");

    myProject = ProjectManagerEx.getInstanceEx().loadProject(projectFile.getPath());
    ProjectManagerEx.getInstanceEx().openTestProject(myProject);
    UIUtil.dispatchAllInvocationEvents(); // startup activities

    setUpJdk();
    myModule = ModuleManager.getInstance(getProject()).getModules()[0];
  }

  @Override
  protected void tearDown() throws Exception {
    try {
      removeLibs();
    }
    finally {
      super.tearDown();
    }
  }

  private void doTest(String fileName, boolean performAction) {
    VirtualFile root = ModuleRootManager.getInstance(myModule).getContentRoots()[0].getParent();
    configureByExistingFile(root.findFileByRelativePath(fileName));
    VirtualFile virtualFile = getFile().getVirtualFile();
    ActionHint actionHint = ActionHint.parse(getFile(), getFile().getText());
    Collection<HighlightInfo> infosBefore = highlightErrors();
    final IntentionAction action = findActionAndCheck(actionHint, infosBefore);

    if(action != null && performAction) {
      String text = action.getText();
      WriteCommandAction.runWriteCommandAction(null, () -> action.invoke(getProject(), getEditor(), getFile()));

      myFile = getPsiManager().findFile(virtualFile);

      Collection<HighlightInfo> infosAfter = highlightErrors();
      final IntentionAction afterAction = findActionWithText(text);
      if (afterAction != null) {
        fail("Action '" + text + "' is still available after its invocation in test " + BASE_PATH + fileName);
      }
      assertTrue(infosBefore.size() > infosAfter.size());
    }
  }

  private IntentionAction findActionWithText(final String actionText) {
    List<IntentionAction> actions = LightQuickFixTestCase.getAvailableActions(getEditor(), getFile());
    return LightQuickFixTestCase.findActionWithText(actions, actionText);
  }

  private IntentionAction findActionAndCheck(final ActionHint actionHint, Collection<HighlightInfo> infosBefore) {
    List<IntentionAction> actions = LightQuickFixTestCase.getAvailableActions(getEditor(), getFile());
    return actionHint.findAndCheck(actions, () -> "Infos: " + infosBefore);
  }

  public void testAddDependency() {
    removeModule();
    doTest("B/src/y/AddDependency.java", true);
  }

  public void testAddAmbiguousDependency() {
    doTest("B/src/y/AddAmbiguous.java", true);
  }

  private void removeModule() {
    ModuleManager manager = ModuleManager.getInstance(getProject());
    ModifiableModuleModel model = manager.getModifiableModel();
    model.disposeModule(manager.findModuleByName("C"));
    WriteAction.run(() -> model.commit());
  }

  public void testAddLibrary() {
    doTest("B/src/y/AddLibrary.java", true);
  }

  public void testAddCircularDependency() {
    final Module a = ModuleManager.getInstance(getProject()).findModuleByName("A");
    final Module b = ModuleManager.getInstance(getProject()).findModuleByName("B");
    ModuleRootModificationUtil.addDependency(a, b);
    removeModule();

    try {
      doTest("B/src/y/AddDependency.java", true);
      fail("user should have been warned");
    }
    catch (RuntimeException e) {
      final String expected = "Adding dependency on module '" + a.getName() + "'" +
                              " will introduce circular dependency between modules '" + a.getName() + "' and '" +
                              b.getName() + "'.\n" + "Add dependency anyway?";
      String message = e.getMessage();
      assertEquals(expected, message);
    }
  }

  public void testAddJunit() {
    doTest("A/src/x/DoTest.java", false);
  }

  public void testAddJunit4() {
    doTest("A/src/x/DoTest4.java", false);
  }

  public void testAddJunit4inJunit() {
    doTest("A/src/x/DoTest4junit.java", false);
  }

  public void testExistingJunit() {
    doTest("B/src/y/AddExistingJunit.java", true);
  }

  private void removeLibs() {
    ApplicationManager.getApplication().runWriteAction(() -> {
      try {
        for (Module module : ModuleManager.getInstance(getProject()).getModules()) {
          ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
          ModifiableRootModel model = rootManager.getModifiableModel();
          for (OrderEntry orderEntry : model.getOrderEntries()) {
            model.removeOrderEntry(orderEntry);
          }
          model.commit();
        }
      }
      catch (Throwable e) {
        e.printStackTrace();  // when running test from within IDEA it would fail because junit.jar cache is locked by host IDEA instance
      }
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
package ir.mtajik.android.advancedsmsmanager.model;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;

import static android.telephony.SmsManager.getSmsManagerForSubscriptionId;

public class MySmsManager {

    Context context;
    SMSManagerCallBack mySmsManagerCallBack = null;
    private String SENT = "SMS_SENT";
    private String DELIVERED = "SMS_DELIVERED";
    private String sms_number;
    private String mBody;
    private int carrierSlotNumber;
    private int carrierSlotCount;
    private int smsId = 0;
    private String carrierName;
    private String carrierNameFilter;

    public MySmsManager(String sms_number, Context context) {

        this.context = context;
        this.sms_number = sms_number;

    }

    public void generateSMS(int smsId, String body, SMSManagerCallBack callBack) {

        this.mySmsManagerCallBack = callBack;
        this.smsId = smsId;
        this.mBody = body;
        sendSMS(mBody);

    }

    public void generateSMS(int smsId, String body, int carrierSlotCount, int carrierSlutNumber,
                            String carrierName,
                            SMSManagerCallBack callBack) {

        this.mySmsManagerCallBack = callBack;
        this.smsId = smsId;

        initializeSmsManager(body, carrierSlotCount, carrierSlutNumber, carrierName);
        sendSMS(mBody);

    }

    public void initializeSmsManager(String body, int carrierSlotCount, int carrierSlotNumber,
                                     String
                                             cariername) {
        this.carrierSlotNumber = carrierSlotNumber;
        this.carrierName = cariername;
        this.mBody = body;
        this.carrierSlotCount = carrierSlotCount;
    }

    public void sendSMS(String message) {

        PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
                new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
                new Intent(DELIVERED), 0);

        BroadcastReceiver mySender = new BroadcastReceiver() {

            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {

                    case Activity.RESULT_OK:
                        context.unregisterReceiver(this);
                        if (mySmsManagerCallBack != null)
                            mySmsManagerCallBack.afterSuccessfulSMS(smsId);
                        break;

                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        context.unregisterReceiver(this);
                        if (mySmsManagerCallBack != null)
                            mySmsManagerCallBack.afterUnSuccessfulSMS(smsId, "Generic failure");
                        break;

                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        context.unregisterReceiver(this);
                        if (mySmsManagerCallBack != null)
                            mySmsManagerCallBack.afterUnSuccessfulSMS(smsId, "No service");
                        break;

                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        context.unregisterReceiver(this);
                        if (mySmsManagerCallBack != null)
                            mySmsManagerCallBack.afterUnSuccessfulSMS(smsId, "Null PDU");
                        break;

                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        context.unregisterReceiver(this);
                        if (mySmsManagerCallBack != null)
                            mySmsManagerCallBack.afterUnSuccessfulSMS(smsId, "Radio off");
                        break;

                }
            }
        };

        context.registerReceiver(mySender, new IntentFilter(SENT));

        BroadcastReceiver myReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        context.unregisterReceiver(this);
                        mySmsManagerCallBack.afterDelivered(smsId);

                        break;
                    case Activity.RESULT_CANCELED:
                        context.unregisterReceiver(this);
                        if (mySmsManagerCallBack != null)
                            mySmsManagerCallBack.afterUnSuccessfulSMS(smsId, "SMS not delivered");

                        break;

                }
            }
        };
        context.registerReceiver(myReceiver, new IntentFilter(DELIVERED));
        SmsManager sms = SmsManager.getDefault();
        int subscriptionId = carrierSlotNumber;

        //even selected carrier Slot is 0 if there is more than one carier ( means 2 sim) it shoud
        // use first method to send sms.
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {

            if (checkCarrierNameFilter()) {

                if( carrierSlotCount > 1){
                    sendSms(message, sentPI, deliveredPI, getSmsManagerForSubscriptionId(subscriptionId));
                }else{
                    sendSms(message, sentPI, deliveredPI, sms);
                }

            } else {
                mySmsManagerCallBack.onCarrierNameNotMatch(smsId, "You had to send sms from: " +
                        carrierNameFilter);
            }
        } else {
            sendSms(message, sentPI, deliveredPI, sms);

        }

    }

    private void sendSms(String message, PendingIntent sentPI, PendingIntent deliveredPI, SmsManager sms) {
        sms.sendTextMessage(sms_number, null, message, sentPI, deliveredPI);
    }

    private boolean checkCarrierNameFilter() {
        if (carrierNameFilter != null) {
            if (carrierName.contains(carrierNameFilter)) {
                return true;
            } else {
                return false;
            }

        } else {
            return true;
        }
    }

    public void setSms_number(String sms_number) {
        this.sms_number = sms_number;
    }

    public void setCarrierNameFilter(String carrierNameFilter) {
        this.carrierNameFilter = carrierNameFilter;
    }

    public interface SMSManagerCallBack {
        void afterSuccessfulSMS(int smsId);

        void afterDelivered(int smsId);

        /*
         SmsManager error types (from 1 ~5) and Activity.RESULT_CANCELED = 0
         */
        void afterUnSuccessfulSMS(int smsId, String message);

        void onCarrierNameNotMatch(int smsId, String message);

    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.adsdk.nativeadsdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.adsdk.nativeadsdemo.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>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>


text:
<?php

namespace Frontend\Modules\Mailmotor;

use Frontend\Core\Engine\Base\Config as FrontendBaseConfig;

/**
 * This is the configuration-object
 *
 * @author Dave Lens <dave.lens@netlash.com>
 */
class Config extends FrontendBaseConfig
{
    /**
     * The default action
     *
     * @var	string
     */
    protected $defaultAction = 'Index';

    /**
     * The disabled actions
     *
     * @var	array
     */
    protected $disabledActions = array();
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Skills.active'
        db.add_column(u'users_skills', 'active',
                      self.gf('django.db.models.fields.BooleanField')(default=True),
                      keep_default=False)

        # Adding field 'Skills.teach'
        db.add_column(u'users_skills', 'teach',
                      self.gf('django.db.models.fields.BooleanField')(default=False),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Skills.active'
        db.delete_column(u'users_skills', 'active')

        # Deleting field 'Skills.teach'
        db.delete_column(u'users_skills', 'teach')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'users.search': {
            'Meta': {'object_name': 'Search'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'users.skills': {
            'Meta': {'object_name': 'Skills'},
            'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'teach': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
        },
        u'users.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'location': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'short_bio': ('django.db.models.fields.TextField', [], {}),
            'skills': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['users.Skills']", 'null': 'True', 'symmetrical': 'False'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        }
    }

    complete_apps = ['users']


text:
package org.bremersee.profile.domain.mongodb.mapper;

import org.bremersee.profile.domain.mongodb.entity.OAuth2ClientMongo;
import org.bremersee.profile.model.OAuth2ClientDto;

/**
 * @author Christian Bremer
 */
public interface OAuth2ClientMongoMapper {

    void mapToDto(OAuth2ClientMongo source, OAuth2ClientDto destination);

    OAuth2ClientDto mapToDto(OAuth2ClientMongo source);

    void updateEntity(OAuth2ClientDto source, OAuth2ClientMongo destination);

}


text:
{% extends "base.html" %}

{% block content %}
{% from "_formhelpers.html" import render_field %}

            <form id="signupform" method="post" action="{{url_for('account.register')}}">
                {{ render_field(form.w) }}
                {{ render_field(form.n) }}
                {{ render_field(form.s, placeholder="********") }}
                {{ render_field(form.c, placeholder="********") }}

                    <input id="signup" type="submit" value="Signup" class="btn btn-primary" />

<input id="m" type="text" name="m" />

            </form>

{% endblock %}


text:
@interface AddBookmarkViewController : UITableViewController<UITextFieldDelegate, UIActionSheetDelegate> {
    id _delegate;
    NSMutableArray *_bookmarksArray;
    BookmarkObject *_bookmark;
    UITextField *_nameTextField;
}

@property (retain,nonatomic) id delegate;
@property (retain,nonatomic) BookmarkObject *bookmark;

- (void)setBookmark:(NSString *)aName url:(NSURL *)aURL;
@end

@protocol AddBookmarkDelegate <NSObject>
- (void)dismissAddBookmMarkViewController:(AddBookmarkViewController *)viewController;
@end


text:
//>>built
define("dijit/Calendar", [
	"dojo/_base/array", // array.map
	"dojo/date",
	"dojo/date/locale",
	"dojo/_base/declare", // declare
	"dojo/dom-attr", // domAttr.get
	"dojo/dom-class", // domClass.add domClass.contains domClass.remove domClass.toggle
	"dojo/_base/event", // event.stop
	"dojo/_base/kernel", // kernel.deprecated
	"dojo/keys", // keys
	"dojo/_base/lang", // lang.hitch
	"dojo/sniff", // has("ie")
	"./CalendarLite",
	"./_Widget",
	"./_CssStateMixin",
	"./_TemplatedMixin",
	"./form/DropDownButton"
], function(array, date, local, declare, domAttr, domClass, event, kernel, keys, lang, has,
			CalendarLite, _Widget, _CssStateMixin, _TemplatedMixin, DropDownButton){

/*=====
	var CalendarLite = dijit.CalendarLite;
	var _CssStateMixin = dijit._CssStateMixin;
	var _Widget = dijit._Widget;
	var _TemplatedMixin = dijit._TemplatedMixin;
	var DropDownButton = dijit.form.DropDownButton;
=====*/

	// module:
	//		dijit/Calendar
	// summary:
	//		A simple GUI for choosing a date in the context of a monthly calendar.

	var Calendar = declare("dijit.Calendar",
		[CalendarLite, _Widget, _CssStateMixin], // _Widget for deprecated methods like setAttribute()
		{
		// summary:
		//		A simple GUI for choosing a date in the context of a monthly calendar.
		//
		// description:
		//		See CalendarLite for general description.   Calendar extends CalendarLite, adding:
		//			- month drop down list
		//			- keyboard navigation
		//			- CSS classes for hover/mousepress on date, month, and year nodes
		//			- support of deprecated methods (will be removed in 2.0)

		// Set node classes for various mouse events, see dijit._CssStateMixin for more details
		cssStateNodes: {
			"decrementMonth": "dijitCalendarArrow",
			"incrementMonth": "dijitCalendarArrow",
			"previousYearLabelNode": "dijitCalendarPreviousYear",
			"nextYearLabelNode": "dijitCalendarNextYear"
		},

		setValue: function(/*Date*/ value){
			// summary:
			//      Deprecated.   Use set('value', ...) instead.
			// tags:
			//      deprecated
			kernel.deprecated("dijit.Calendar:setValue() is deprecated.  Use set('value', ...) instead.", "", "2.0");
			this.set('value', value);
		},

		_createMonthWidget: function(){
			// summary:
			//		Creates the drop down button that displays the current month and lets user pick a new one

			return new Calendar._MonthDropDownButton({
				id: this.id + "_mddb",
				tabIndex: -1,
				onMonthSelect: lang.hitch(this, "_onMonthSelect"),
				lang: this.lang,
				dateLocaleModule: this.dateLocaleModule
			}, this.monthNode);
		},

		postCreate: function(){
			this.inherited(arguments);

			// Events specific to Calendar, not used in CalendarLite
			this.connect(this.domNode, "onkeypress", "_onKeyPress");
			this.connect(this.dateRowsNode, "onmouseover", "_onDayMouseOver");
			this.connect(this.dateRowsNode, "onmouseout", "_onDayMouseOut");
			this.connect(this.dateRowsNode, "onmousedown", "_onDayMouseDown");
			this.connect(this.dateRowsNode, "onmouseup", "_onDayMouseUp");
		},

		_onMonthSelect: function(/*Number*/ newMonth){
			// summary:
			//      Handler for when user selects a month from the drop down list
			// tags:
			//      protected

			// move to selected month, bounding by the number of days in the month
			// (ex: dec 31 --> jan 28, not jan 31)
			this._setCurrentFocusAttr(this.dateFuncObj.add(this.currentFocus, "month",
				newMonth - this.currentFocus.getMonth()));
		},

		_onDayMouseOver: function(/*Event*/ evt){
			// summary:
			//      Handler for mouse over events on days, sets hovered style
			// tags:
			//      protected

			// event can occur on  or the  inside the td,
			// set node to the .
			var node =
				domClass.contains(evt.target, "dijitCalendarDateLabel") ?
				evt.target.parentNode :
				evt.target;

			if(node && (
				(node.dijitDateValue && !domClass.contains(node, "dijitCalendarDisabledDate"))
					|| node == this.previousYearLabelNode || node == this.nextYearLabelNode
				)){
				domClass.add(node, "dijitCalendarHoveredDate");
				this._currentNode = node;
			}
		},

		_onDayMouseOut: function(/*Event*/ evt){
			// summary:
			//      Handler for mouse out events on days, clears hovered style
			// tags:
			//      protected

			if(!this._currentNode){ return; }

			// if mouse out occurs moving from  to  inside , ignore it
			if(evt.relatedTarget && evt.relatedTarget.parentNode == this._currentNode){ return; }
			var cls = "dijitCalendarHoveredDate";
			if(domClass.contains(this._currentNode, "dijitCalendarActiveDate")){
				cls += " dijitCalendarActiveDate";
			}
			domClass.remove(this._currentNode, cls);
			this._currentNode = null;
		},

		_onDayMouseDown: function(/*Event*/ evt){
			var node = evt.target.parentNode;
			if(node && node.dijitDateValue && !domClass.contains(node, "dijitCalendarDisabledDate")){
				domClass.add(node, "dijitCalendarActiveDate");
				this._currentNode = node;
			}
		},

		_onDayMouseUp: function(/*Event*/ evt){
			var node = evt.target.parentNode;
			if(node && node.dijitDateValue){
				domClass.remove(node, "dijitCalendarActiveDate");
			}
		},

		handleKey: function(/*Event*/ evt){
			// summary:
			//		Provides keyboard navigation of calendar.
			// description:
			//		Called from _onKeyPress() to handle keypress on a stand alone Calendar,
			//		and also from `dijit.form._DateTimeTextBox` to pass a keypress event
			//		from the `dijit.form.DateTextBox` to be handled in this widget
			// returns:
			//		False if the key was recognized as a navigation key,
			//		to indicate that the event was handled by Calendar and shouldn't be propogated
			// tags:
			//		protected
			var increment = -1,
				interval,
				newValue = this.currentFocus;
			switch(evt.charOrCode){
				case keys.RIGHT_ARROW:
					increment = 1;
					//fallthrough...
				case keys.LEFT_ARROW:
					interval = "day";
					if(!this.isLeftToRight()){ increment *= -1; }
					break;
				case keys.DOWN_ARROW:
					increment = 1;
					//fallthrough...
				case keys.UP_ARROW:
					interval = "week";
					break;
				case keys.PAGE_DOWN:
					increment = 1;
					//fallthrough...
				case keys.PAGE_UP:
					interval = evt.ctrlKey || evt.altKey ? "year" : "month";
					break;
				case keys.END:
					// go to the next month
					newValue = this.dateFuncObj.add(newValue, "month", 1);
					// subtract a day from the result when we're done
					interval = "day";
					//fallthrough...
				case keys.HOME:
					newValue = new this.dateClassObj(newValue);
					newValue.setDate(1);
					break;
				case keys.ENTER:
				case " ":
					this.set("value", this.currentFocus);
					break;
				default:
					return true;
			}

			if(interval){
				newValue = this.dateFuncObj.add(newValue, interval, increment);
			}

			this._setCurrentFocusAttr(newValue);

			return false;
		},

		_onKeyPress: function(/*Event*/ evt){
			// summary:
			//		For handling keypress events on a stand alone calendar
			if(!this.handleKey(evt)){
				event.stop(evt);
			}
		},

		onValueSelected: function(/*Date*/ /*===== date =====*/){
			// summary:
			//		Deprecated.   Notification that a date cell was selected.  It may be the same as the previous value.
			// description:
			//      Formerly used by `dijit.form._DateTimeTextBox` (and thus `dijit.form.DateTextBox`)
			//      to get notification when the user has clicked a date.  Now onExecute() (above) is used.
			// tags:
			//      protected
		},

		onChange: function(value){
			this.onValueSelected(value);	// remove in 2.0
		},

		getClassForDate: function(/*===== dateObject, locale =====*/){
			// summary:
			//		May be overridden to return CSS classes to associate with the date entry for the given dateObject,
			//		for example to indicate a holiday in specified locale.
			// dateObject: Date
			// locale: String?
			// tags:
			//      extension

/*=====
			return ""; // String
=====*/
		}
	});

	Calendar._MonthDropDownButton = declare("dijit.Calendar._MonthDropDownButton", DropDownButton, {
		// summary:
		//		DropDownButton for the current month.    Displays name of current month
		//		and a list of month names in the drop down

		onMonthSelect: function(){ },

		postCreate: function(){
			this.inherited(arguments);
			this.dropDown = new Calendar._MonthDropDown({
				id: this.id + "_mdd", //do not change this id because it is referenced in the template
				onChange: this.onMonthSelect
			});
		},
		_setMonthAttr: function(month){
			// summary:
			//		Set the current month to display as a label
			var monthNames = this.dateLocaleModule.getNames('months', 'wide', 'standAlone', this.lang, month);
			this.dropDown.set("months", monthNames);

			// Set name of current month and also fill in spacer element with all the month names
			// (invisible) so that the maximum width will affect layout.   But not on IE6 because then
			// the center  overlaps the right  (due to a browser bug).
			this.containerNode.innerHTML =
				(has("ie") == 6 ? "" : "
" + this.dropDown.domNode.innerHTML + "
") +
				"
" +  monthNames[month.getMonth()] + "
";
		}
	});

	Calendar._MonthDropDown = declare("dijit.Calendar._MonthDropDown", [_Widget, _TemplatedMixin], {
		// summary:
		//		The list-of-months drop down from the MonthDropDownButton

		// months: String[]
		//		List of names of months, possibly w/some undefined entries for Hebrew leap months
		//		(ex: ["January", "February", undefined, "April", ...])
		months: [],

		templateString: "

",

		_setMonthsAttr: function(/*String[]*/ months){
			this.domNode.innerHTML = array.map(months, function(month, idx){
					return month ? "
" + month + "
" : "";
				}).join("");
		},

		_onClick: function(/*Event*/ evt){
			this.onChange(domAttr.get(evt.target, "month"));
		},

		onChange: function(/*Number*/ /*===== month =====*/){
			// summary:
			//		Callback when month is selected from drop down
		},

		_onMenuHover: function(evt){
			domClass.toggle(evt.target, "dijitCalendarMonthLabelHover", evt.type == "mouseover");
		}
	});

	return Calendar;
});


text:
<?php

namespace DataEntity\Type;

use DataEntity\Type;
use Filterus\Filter;

class ArrayType extends Type
{

    public function filter($value, $context = null)
    {
        return Filter::factory('array')->filter($value);
    }

    public function validate($value)
    {
        return Filter::factory('array')->validate($value);
    }
}


text:
package org.apache.isis.objectstore.nosql.db.mongo;

import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.spec.ObjectSpecId;
import org.apache.isis.core.metamodel.spec.feature.Contributed;
import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation;
import org.apache.isis.core.runtime.persistence.objectstore.transaction.PersistenceCommand;
import org.apache.isis.objectstore.nosql.NoSqlCommandContext;
import org.apache.isis.objectstore.nosql.NoSqlStoreException;
import org.apache.isis.objectstore.nosql.db.NoSqlDataDatabase;
import org.apache.isis.objectstore.nosql.db.StateReader;
import org.apache.isis.objectstore.nosql.db.StateWriter;
import org.apache.isis.objectstore.nosql.keys.KeyCreatorDefault;

public class MongoDb implements NoSqlDataDatabase {

	private static final String SERIALNUMBERS_COLLECTION_NAME = "serialnumbers";

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

	private static final int DEFAULT_PORT = 27017;

    private final String host;
    private final int port;
    private final String dbName;
    private final KeyCreatorDefault keyCreator;

	private Mongo mongo;
	private DB db;

    public MongoDb(final String host, final int port, final String name, final KeyCreatorDefault keyCreator) {
        this.host = host;
        this.port = port == 0 ? DEFAULT_PORT : port;
        this.dbName = name;
        this.keyCreator = keyCreator;
    }

    public KeyCreatorDefault getKeyCreator() {
        return keyCreator;
    }

    @Override
    public void open() {
        try {
            if (mongo == null) {
                mongo = new Mongo(host, port);
                db = mongo.getDB(dbName);
                db.setWriteConcern(com.mongodb.WriteConcern.SAFE);
                LOG.info("opened database (" + dbName + "): " + mongo);
            } else {
                LOG.info(" using opened database " + db);
            }
        } catch (final UnknownHostException e) {
            throw new NoSqlStoreException(e);
        } catch (final MongoException e) {
            throw new NoSqlStoreException(e);
        }
    }

    @Override
    public void close() {
    }

    public NoSqlCommandContext createTransactionContext() {
        return null;
    }

    //////////////////////////////////////////////////
    // contains data
    //////////////////////////////////////////////////

    @Override
    public boolean containsData() {
        return db.getCollectionNames().size() > 0;
    }

    //////////////////////////////////////////////////
    // serial numbers
    //////////////////////////////////////////////////

    @Override
    public long nextSerialNumberBatch(final ObjectSpecId name, final int batchSize) {
        long next = readSerialNumber();
        writeSerialNumber(next + batchSize);
        return next + 1;
    }

    private void writeSerialNumber(final long serialNumber) {
        final DBCollection system = db.getCollection(SERIALNUMBERS_COLLECTION_NAME);
        DBObject object = system.findOne();
        if (object == null) {
            object = new BasicDBObject();
        }
        object.put("next-id", Long.toString(serialNumber));
        system.save(object);
        LOG.info("serial number written: " + serialNumber);
    }

    private long readSerialNumber() {
        final DBCollection system = db.getCollection(SERIALNUMBERS_COLLECTION_NAME);
        final DBObject data = system.findOne();
        if (data == null) {
            return 0;
        } else {
            final String number = (String) data.get("next-id");
            LOG.info("serial number read: " + number);
            return Long.valueOf(number);
        }
    }

    //////////////////////////////////////////////////
    // hasInstances, instancesOf
    //////////////////////////////////////////////////

    @Override
    public boolean hasInstances(final ObjectSpecId objectSpecId) {
        final DBCollection instances = db.getCollection(objectSpecId.asString());
        return instances.getCount() > 0;
    }

    @Override
    public Iterator<StateReader> instancesOf(final ObjectSpecId objectSpecId) {
        final DBCollection instances = db.getCollection(objectSpecId.asString());
        final DBCursor cursor = instances.find();
        LOG.info("searching for instances of: " + objectSpecId);
        return new Iterator<StateReader>() {
            @Override
            public boolean hasNext() {
                return cursor.hasNext();
            }

            @Override
            public StateReader next() {
                return new MongoStateReader(cursor.next());
            }

            @Override
            public void remove() {
                throw new NoSqlStoreException("Can't remove elements");
            }

        };
    }

    @Override
    public Iterator<StateReader> instancesOf(ObjectSpecId objectSpecId, ObjectAdapter pattern) {
        final DBCollection instances = db.getCollection(objectSpecId.asString());

        // REVIEW check the right types are used in matches
        final BasicDBObject query = new BasicDBObject();
        for ( ObjectAssociation association  : pattern.getSpecification().getAssociations(Contributed.EXCLUDED)) {
            ObjectAdapter field = association.get(pattern);
            if (!association.isEmpty(pattern)) {
                if (field.isValue()) {
                    query.put(association.getIdentifier().getMemberName(), field.titleString());
                } else if (association.isOneToOneAssociation()) {
                    query.put(association.getIdentifier().getMemberName(), field.getOid());
                }
            }
        }
        final DBCursor cursor = instances.find(query);
        LOG.info("searching for instances of: " + objectSpecId);
        return new Iterator<StateReader>() {
            @Override
            public boolean hasNext() {
                return cursor.hasNext();
            }

            @Override
            public StateReader next() {
                return new MongoStateReader(cursor.next());
            }

            @Override
            public void remove() {
                throw new NoSqlStoreException("Can't remove elements");
            }

        };
    }

    @Override
    public StateReader getInstance(final String key, final ObjectSpecId objectSpecId) {
        return new MongoStateReader(db, objectSpecId, key);
    }

    //////////////////////////////////////////////////
    // write, delete
    //////////////////////////////////////////////////

    public StateWriter createStateWriter(final ObjectSpecId objectSpecId) {
        return new MongoStateWriter(db, objectSpecId);
    }

    @Override
    public void write(final List<PersistenceCommand> commands) {
        final NoSqlCommandContext context = new MongoClientCommandContext(db);
        for (final PersistenceCommand command : commands) {
            command.execute(context);
        }
    }

    //////////////////////////////////////////////////
    // services
    //////////////////////////////////////////////////

    @Override
    public void addService(final ObjectSpecId objectSpecId, final String key) {
        final DBCollection services = db.getCollection("services");
        services.insert(new BasicDBObject().append("name", objectSpecId.asString()).append("key", key));
        LOG.info("service added " + objectSpecId + ":" + key);
    }

    @Override
    public String getService(final ObjectSpecId objectSpecId) {
        final DBCollection services = db.getCollection("services");
        final DBObject object = services.findOne(new BasicDBObject().append("name", objectSpecId.asString()));
        if (object == null) {
            return null;
        } else {
            final String id = (String) object.get("key");
            LOG.info("service found " + objectSpecId + ":" + id);
            return id;
        }
    }
}


text:
package example.sos.rest.inventory;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.springframework.data.domain.AbstractAggregateRoot;

/**
 * @author Oliver Gierke
 */
@Data
@Entity
@EqualsAndHashCode(of = "id", callSuper = false)
@Setter(value = AccessLevel.NONE)
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public class InventoryItem extends AbstractAggregateRoot<InventoryItem> {

	private final @Id UUID id = UUID.randomUUID();

	private ProductId productId;
	private long amount;

	public static InventoryItem of(ProductId productId, long amount) {

		InventoryItem item = new InventoryItem(productId, amount);
		item.registerEvent(ProductOutOfStock.of(productId));

		return item;
	}

	InventoryItem decrease(Long amount) {

		this.amount = this.amount - amount;

		log.info("Decreasing amount of inventory for product {} by {} to {}.", productId, amount, this.amount);

		if (this.amount < 1) {
			registerEvent(ProductOutOfStock.of(productId));
		}

		return this;
	}

	@Embeddable
	@Value
	@RequiredArgsConstructor(staticName = "of")
	@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
	public static class ProductId {
		String productId;
	}

	@Value(staticConstructor = "of")
	public static class ProductOutOfStock {
		ProductId productId;
	}
}


text:
require "rack/auth/abstract/handler"
require "rack/auth/abstract/request"

module Rack
 module Auth
   	class Custom < AbstractHandler

		def unauthorized()
			return [ 302, { 'Location' => "/login?redirect=#{@requestURI}" },[ "" ] ]
		end

		def requestFailure( msg )
			return [ 302, { 'Location' => "/error" },[ "" ] ]
		end

		def call( env )
			@requestURI	= env["REQUEST_URI"]

			## Ignore the user check for login/logout actions
			if(env["REQUEST_URI"].match( /log.*/ ))
				return @app.call( env )
			end

			## No session means the user has not logged in yet, or has just logged out
			#env.each do |k,v| puts "#{k}: #{v}" end

			#Log.debug( "env" ){ env.inspect }
			#Log.debug( "rack.session" ){ env["rack.session"].inspect }
			if(env["rack.session"] == nil || env["rack.session"][:userId] == nil)
				Log.info( "Authentication" ){ "Invalid session" }
				return unauthorized()
			end

			user	= User.all( :conditions => { :_id => env["rack.session"][:userId] })
			## Call the mount point *only* if the user exists and is authorized to login
			if(user.count == 1 && user[0].authorized?() )
				return unauthorized() if(user[0]._disabled == true)
				env[:user] = user[0]
				return @app.call( env )
			end
			return unauthorized()
		end

	end ## Custom
 end ## Auth
end ## Rack


text:
All connector functions (e.g. AddInventoryItem() on
inventory-service-connector.php) take a final optional debug boolean (false by
default).  If set to true, this will print the outgoing and incoming responses
to/from the ROBUST service.


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Profile.Common;
using Microsoft.Azure.Commands.Profile.Models;
using Microsoft.Azure.Commands.Profile.Utilities;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using System;
using System.Globalization;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Profile
{
    /// <summary>
    /// Cmdlet to add Azure Environment to Profile.
    /// </summary>
    [Cmdlet("Add", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "Environment", SupportsShouldProcess = true, DefaultParameterSetName = EnvironmentPropertiesParameterSet)]
    [OutputType(typeof(PSAzureEnvironment))]
    public class AddAzureRMEnvironmentCommand : AzureContextModificationCmdlet
    {
        // Currently, this is the only resource endpoint used for both AzureCloud and all dogfood for Data Lake
        // This ensures that existing scripts will automatically pick up the right environment with no changes.
        private string _defaultDataLakeResourceEndpoint = "https://datalake.azure.net";
        private EnvironmentHelper envHelper;

        private const string MetadataParameterSet = "ARMEndpoint";
        private const string EnvironmentPropertiesParameterSet = "Name";

        public EnvironmentHelper EnvHelper
        {
            get { return this.envHelper; }
            set { this.envHelper = value != null ? value : new EnvironmentHelper(); }
        }

        [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)]
        public string Name { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true)]
        public string PublishSettingsFileUrl { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true)]
        [Alias("ServiceManagement", "ServiceManagementUrl")]
        public string ServiceEndpoint { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true)]
        public string ManagementPortalUrl { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 4, Mandatory = false, HelpMessage = "The storage endpoint")]
        [Parameter(ParameterSetName = MetadataParameterSet, Position = 2, Mandatory = false, HelpMessage = "The storage endpoint")]
        [Alias("StorageEndpointSuffix")]
        public string StorageEndpoint { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 5, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The URI for the Active Directory service for this environment")]
        [Alias("AdEndpointUrl", "ActiveDirectory", "ActiveDirectoryAuthority")]
        public string ActiveDirectoryEndpoint { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 6, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The cloud service endpoint")]
        [Alias("ResourceManager", "ResourceManagerUrl")]
        public string ResourceManagerEndpoint { get; set; }

        [Parameter(ParameterSetName = MetadataParameterSet, Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The Azure Resource Manager endpoint")]
        [Alias("ArmUrl")]
        public string ARMEndpoint { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 7, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The public gallery endpoint")]
        [Alias("Gallery", "GalleryUrl")]
        public string GalleryEndpoint { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 8, Mandatory = false, ValueFromPipelineByPropertyName = true,
            HelpMessage = "Identifier of the target resource that is the recipient of the requested token.")]
        public string ActiveDirectoryServiceEndpointResourceId { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 9, Mandatory = false, ValueFromPipelineByPropertyName = true,
            HelpMessage = "The AD Graph Endpoint.")]
        [Alias("Graph", "GraphUrl")]
        public string GraphEndpoint { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 10, Mandatory = false, ValueFromPipelineByPropertyName = true,
           HelpMessage = "Dns suffix of Azure Key Vault service. Example is vault-int.azure-int.net")]
        [Parameter(ParameterSetName = MetadataParameterSet, Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Dns suffix of Azure Key Vault service")]
        public string AzureKeyVaultDnsSuffix { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 11, Mandatory = false, ValueFromPipelineByPropertyName = true,
           HelpMessage = "Resource identifier of Azure Key Vault data service that is the recipient of the requested token.")]
        [Parameter(ParameterSetName = MetadataParameterSet, Position = 4, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Resource identifier of Azure Key Vault data service that is the recipient of the requested token.")]
        public string AzureKeyVaultServiceEndpointResourceId { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 12, Mandatory = false, ValueFromPipelineByPropertyName = true,
           HelpMessage = "Dns suffix of Traffic Manager service.")]
        public string TrafficManagerDnsSuffix { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 13, Mandatory = false, ValueFromPipelineByPropertyName = true,
          HelpMessage = "Dns suffix of Sql databases created in this environment.")]
        public string SqlDatabaseDnsSuffix { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 14, Mandatory = false, ValueFromPipelineByPropertyName = true,
            HelpMessage = "Dns Suffix of Azure Data Lake Store FileSystem. Example: azuredatalake.net")]
        public string AzureDataLakeStoreFileSystemEndpointSuffix { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 15, Mandatory = false, ValueFromPipelineByPropertyName = true,
            HelpMessage = "Dns Suffix of Azure Data Lake Analytics job and catalog services")]
        public string AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 16, Mandatory = false, ValueFromPipelineByPropertyName = true,
          HelpMessage = "Enable ADFS authentication by disabling the authority validation")]
        [Alias("OnPremise")]
        public SwitchParameter EnableAdfsAuthentication { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 17, Mandatory = false, ValueFromPipelineByPropertyName = true,
           HelpMessage = "The default tenant for this environment.")]
        public string AdTenant { get; set; }

        [Parameter(ParameterSetName = EnvironmentPropertiesParameterSet, Position = 18, Mandatory = false, ValueFromPipelineByPropertyName = true,
           HelpMessage = "The audience for tokens authenticating with the AD Graph Endpoint.")]
        [Alias("GraphEndpointResourceId", "GraphResourceId")]
        public string GraphAudience { get; set; }

        [Parameter(Position = 19, Mandatory = false, ValueFromPipelineByPropertyName = true,
           HelpMessage = "The audience for tokens authenticating with the AD Data Lake services Endpoint.")]
        [Alias("DataLakeEndpointResourceId", "DataLakeResourceId")]
        public string DataLakeAudience
        {
            get
            {
                return _defaultDataLakeResourceEndpoint;
            }
            set
            {
                _defaultDataLakeResourceEndpoint = value;
            }
        }

        [Parameter(Position = 20, Mandatory = false, ValueFromPipelineByPropertyName = true,
            HelpMessage = "The resource identifier of the Azure Batch service that is the recipient of the requested token.")]
        [Alias("BatchResourceId", "BatchAudience")]
        public string BatchEndpointResourceId { get; set; }

        [Parameter(Position = 21, Mandatory = false, ValueFromPipelineByPropertyName = true,
           HelpMessage = "The audience for tokens authenticating with the Azure Log Analytics API.")]
        public string AzureOperationalInsightsEndpointResourceId { get; set; }

        [Parameter(Position = 22, Mandatory = false, ValueFromPipelineByPropertyName = true,
            HelpMessage = "The endpoint to use when communicating with the Azure Log Analytics API.")]
        public string AzureOperationalInsightsEndpoint { get; set; }

        [Parameter(Mandatory = false,
           HelpMessage = "The endpoint to use when communicating with the Azure Log Analytics API.")]
        public string AzureAnalysisServicesEndpointSuffix { get; set; }

        protected override void BeginProcessing()
        {
            // do not call begin processing there is no context needed for this cmdlet
        }

        public override void ExecuteCmdlet()
        {
            ConfirmAction("adding environment", Name,
                () =>
                {
                    if (AzureEnvironment.PublicEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                            "Cannot add built-in environment {0}.", Name));
                    }

                    if (this.ParameterSetName.Equals(MetadataParameterSet, StringComparison.Ordinal))
                    {
                        // Simply use built-in environments if the ARM endpoint matches the ARM endpoint for a built-in environment
                        var publicEnvironment = AzureEnvironment.PublicEnvironments.FirstOrDefault(
                            env => !string.IsNullOrWhiteSpace(ARMEndpoint) &&
                            string.Equals(
                                env.Value?.GetEndpoint(AzureEnvironment.Endpoint.ResourceManager)?.ToLowerInvariant(),
                                GeneralUtilities.EnsureTrailingSlash(ARMEndpoint)?.ToLowerInvariant(), StringComparison.CurrentCultureIgnoreCase));

                        var defProfile = GetDefaultProfile();
                        IAzureEnvironment newEnvironment;
                        if (!defProfile.TryGetEnvironment(this.Name, out newEnvironment))
                        {
                            newEnvironment = new AzureEnvironment { Name = this.Name };
                        }

                        if (publicEnvironment.Key == null)
                        {
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ResourceManager, ARMEndpoint);
                            try
                            {
                                EnvHelper = (EnvHelper == null ? new EnvironmentHelper() : EnvHelper);
                                MetadataResponse metadataEndpoints = EnvHelper.RetrieveMetaDataEndpoints(newEnvironment.ResourceManagerUrl).Result;
                                string domain = EnvHelper.RetrieveDomain(ARMEndpoint);

                                SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory,
                                    metadataEndpoints.authentication.LoginEndpoint.TrimEnd('/') + '/');
                                SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId,
                                    metadataEndpoints.authentication.Audiences[0]);
                                SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Gallery, metadataEndpoints.GalleryEndpoint);
                                SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Graph, metadataEndpoints.GraphEndpoint);
                                SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.GraphEndpointResourceId,
                                    metadataEndpoints.GraphEndpoint);
                                SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix,
                                        AzureKeyVaultDnsSuffix ?? string.Format("vault.{0}", domain).ToLowerInvariant());
                                SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId,
                                        AzureKeyVaultServiceEndpointResourceId ?? string.Format("https://vault.{0}", domain).ToLowerInvariant());
                                SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix, StorageEndpoint ?? domain);
                                newEnvironment.OnPremise = metadataEndpoints.authentication.LoginEndpoint.TrimEnd('/').EndsWith("/adfs", System.StringComparison.OrdinalIgnoreCase);
                            }
                            catch (AggregateException ae)
                            {
                                if (ae.Flatten().InnerExceptions.Count > 1)
                                {
                                    throw;
                                }

                                if (ae.InnerException != null)
                                {
                                    throw ae.InnerException;
                                }
                            }
                        }
                        else
                        {
                            newEnvironment = new AzureEnvironment(publicEnvironment.Value);
                            newEnvironment.Name = Name;
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix,
                                    AzureKeyVaultDnsSuffix);
                            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId,
                                    AzureKeyVaultServiceEndpointResourceId);
                        }

                        ModifyContext((profile, client) =>
                        {
                            WriteObject(new PSAzureEnvironment(client.AddOrSetEnvironment(newEnvironment)));
                        });
                    }
                    else
                    {
                        ModifyContext((profile, profileClient) =>
                        {

                            IAzureEnvironment newEnvironment = new AzureEnvironment { Name = Name };
                            if (profile.EnvironmentTable.ContainsKey(Name))
                            {
                                newEnvironment = profile.EnvironmentTable[Name];
                            }

                            if (MyInvocation != null && MyInvocation.BoundParameters != null)
                            {
                                if (MyInvocation.BoundParameters.ContainsKey(nameof(EnableAdfsAuthentication)))
                                {
                                    newEnvironment.OnPremise = EnableAdfsAuthentication;
                                }

                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.PublishSettingsFileUrl,
                                        nameof(PublishSettingsFileUrl));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ServiceManagement, nameof(ServiceEndpoint));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ResourceManager,
                                    nameof(ResourceManagerEndpoint));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ManagementPortalUrl,
                                    nameof(ManagementPortalUrl));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix,
                                    nameof(StorageEndpoint));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory,
                                    nameof(ActiveDirectoryEndpoint), true);

                                SetEndpointIfBound(newEnvironment,
                                    AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId,
                                    nameof(ActiveDirectoryServiceEndpointResourceId));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.Gallery, nameof(GalleryEndpoint));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.Graph, nameof(GraphEndpoint));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix,
                                   nameof(AzureKeyVaultDnsSuffix));
                                SetEndpointIfBound(newEnvironment,
                                    AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId,
                                    nameof(AzureKeyVaultServiceEndpointResourceId));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.TrafficManagerDnsSuffix,
                                    nameof(TrafficManagerDnsSuffix));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix,
                                    nameof(SqlDatabaseDnsSuffix));
                                SetEndpointIfBound(newEnvironment,
                                    AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix,
                                    nameof(AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix));
                                SetEndpointIfBound(newEnvironment,
                                    AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix,
                                    nameof(AzureDataLakeStoreFileSystemEndpointSuffix));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.AdTenant, nameof(AdTenant));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.GraphEndpointResourceId,
                                   nameof(GraphAudience));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.DataLakeEndpointResourceId,
                                    nameof(DataLakeAudience));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.Endpoint.BatchEndpointResourceId,
                                    nameof(BatchEndpointResourceId));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId,
                                    nameof(AzureOperationalInsightsEndpointResourceId));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpoint,
                                    nameof(AzureOperationalInsightsEndpoint));
                                SetEndpointIfBound(newEnvironment, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointSuffix,
                                   nameof(AzureAnalysisServicesEndpointSuffix));
                                WriteObject(new PSAzureEnvironment(profileClient.AddOrSetEnvironment(newEnvironment)));
                            }
                        });
                    }
                });

        }

        private void SetEndpointIfProvided(IAzureEnvironment newEnvironment, string endpoint, string property, bool trailingSlash = false)
        {
            if (!string.IsNullOrEmpty(property))
            {
                string value = property;
                if (!string.IsNullOrWhiteSpace(value) && trailingSlash)
                {
                    value = value.EndsWith("/", StringComparison.OrdinalIgnoreCase) ? value : value + "/";
                }
                newEnvironment.SetEndpoint(endpoint, value);
            }
        }

        private void SetEndpointIfBound(IAzureEnvironment newEnvironment, string endpoint, string key, bool trailingSlash=false)
        {
            if (MyInvocation.BoundParameters.ContainsKey(key))
            {
                string value = MyInvocation.BoundParameters[key] as string;
                if (!string.IsNullOrWhiteSpace(value) && trailingSlash)
                {
                    value = value.EndsWith("/", StringComparison.OrdinalIgnoreCase) ? value : value + "/";
                }

                newEnvironment.SetEndpoint(endpoint, value);
            }
        }

    }
}


text:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
  helper_method :current_user
end


text:
package com.android.sdk.social.wechat;

import android.support.annotation.NonNull;

/**
 * @author Ztiany
 * Email: ztiany3@gmail.com
 * Date : 2018-11-07 15:17
 */
@SuppressWarnings("unused")
public class AuthResult {

    private int errcode;
    private String errmsg;

    int getErrcode() {
        return errcode;
    }

    String getErrmsg() {
        return errmsg;
    }

    @NonNull
    @Override
    public String toString() {
        return "AuthResult{" +
                "errcode=" + errcode +
                ", errmsg='" + errmsg + '\'' +
                '}';
    }
}


text:
macro(pkg_config_find_module varname pkgname header library pathsuffix)

    find_package(PkgConfig)
    pkg_check_modules(${varname}_pkgconfig ${pkgname})

    find_path(${varname}_INCLUDE_DIR ${header}
        HINTS ${${varname}_pkgconfig_INCLUDEDIR}
        PATH_SUFFIXES ${pathsuffix}
        DOC "Path to ${pkgname} include directory")

    find_library(${varname}_LIBRARY ${library} HINTS ${${varname}_pkgconfig_LIBDIR} DOC "Path to ${pkgname} library")

    set(${varname}_INCLUDE_DIRS ${${varname}_INCLUDE_DIR})
    set(${varname}_LIBRARIES ${${varname}_LIBRARY})

    include(FindPackageHandleStandardArgs)
    find_package_handle_standard_args(${varname} DEFAULT_MSG ${varname}_INCLUDE_DIR ${varname}_LIBRARY)

    mark_as_advanced(${varname}_INCLUDE_DIR)
    mark_as_advanced(${varmame}_LIBRARY)

endmacro()

pkg_config_find_module(LCM lcm lcm/lcm.h lcm lcm)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Song, Ouyang & Hu, Journal of Tropical and Subtropical Botany 5(2): 38 (1997)

#### Original name
Meliola schoepfiae B. Song & Y.X. Hu

### Remarks
null


text:
Lokal læreplan innhold

        Kompetansemål/Arbeidsoppgaver
        Utplasseringssted
        Fjern

        {{#each maal}}

                {{kompetanseMaal}}
{{arbeidsOppgaver}}

                {{utplasseringsSted}}
                delete

        {{/each}}


text:
'use strict';

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { closeDrawer } from '../../actions/drawer';
import { replaceOrPushRoute } from '../../actions/route';

import {Content, Text, List, ListItem } from 'native-base';

import styles from './style';

class SideBar extends Component {

    navigateTo(route) {
        this.props.closeDrawer();
        this.props.replaceOrPushRoute(route);
    }

    render(){
        return (
            <Content style={styles.sidebar} >
                <List foregroundColor={'white'}>
                    <ListItem onPress={() => this.navigateTo('home')} >
                        <Text>Bar Hoper</Text>
                    </ListItem>
                    <ListItem onPress={() => this.navigateTo('blankPage')} >
                        <Text>Blank Page</Text>
                    </ListItem>
                </List>
            </Content>
        );
    }
}

function bindAction(dispatch) {
    return {
        closeDrawer: ()=>dispatch(closeDrawer()),
        replaceOrPushRoute:(route)=>dispatch(replaceOrPushRoute(route))
    }
}

export default connect(null, bindAction)(SideBar);


text:
<!--
  ~ Copyright (c) 2013 Wisen Tanasa
  ~
  ~ Permission is hereby granted, free of charge, to any person obtaining
  ~ a copy of this software and associated documentation files (the
  ~ "Software"), to deal in the Software without restriction, including
  ~ without limitation the rights to use, copy, modify, merge, publish,
  ~ distribute, sublicense, and/or sell copies of the Software, and to
  ~ permit persons to whom the Software is furnished to do so, subject to
  ~ the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be
  ~ included in all copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  ~ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  ~ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  ~ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  ~ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  ~ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  ~ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ceilfors.maven.plugin.it</groupId>
    <artifactId>fail3_</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>Fail #3</name>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.0</version>
                <dependencies>
                    <dependency>
                        <!--suppress MavenModelInspection --><groupId>@project.groupId@</groupId>
                        <!--suppress MavenModelInspection --><artifactId>@project.artifactId@</artifactId>
                        <!--suppress MavenModelInspection --><version>@project.version@</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <rules>
                        <matchArtifactIdAndBaseDir />
                    </rules>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
package org.terracotta.offheapstore.storage.listener;

import org.terracotta.offheapstore.storage.listener.ListenableStorageEngine;
import org.terracotta.offheapstore.storage.listener.RecoveryStorageEngineListener;
import org.terracotta.offheapstore.storage.listener.RuntimeStorageEngineListener;
import java.nio.ByteBuffer;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;

import org.hamcrest.core.Is;
import org.hamcrest.core.IsEqual;
import org.hamcrest.core.IsNull;
import org.junit.Assert;
import org.junit.Test;

import org.terracotta.offheapstore.Metadata;
import org.terracotta.offheapstore.OffHeapHashMap;
import org.terracotta.offheapstore.buffersource.HeapBufferSource;
import org.terracotta.offheapstore.paging.UnlimitedPageSource;
import org.terracotta.offheapstore.storage.StorageEngine;

@SuppressWarnings("unchecked")
public abstract class AbstractListenerIT {

  @Test
  public void testListeningForPuts() {
    ListenableStorageEngine<String, String> storageEngine = createStorageEngine();

    TrackingListener<String, String> listener = new TrackingListener<String, String>();
    storageEngine.registerListener(listener);
    Map<String, String> map = new OffHeapHashMap<String, String>(new UnlimitedPageSource(new HeapBufferSource()), (StorageEngine<? super String, ? super String>) storageEngine);

    for (int i = 0; i < 100; i++) {
      map.put(Integer.toString(i), Integer.toHexString(i));
      Assert.assertThat(listener.getTrackingMap(), IsEqual.equalTo(map));
    }
  }

  @Test
  public void testListeningForRemoves() {
    ListenableStorageEngine<String, String> storageEngine = createStorageEngine();

    TrackingListener<String, String> listener = new TrackingListener<String, String>();
    storageEngine.registerListener(listener);
    Map<String, String> map = new OffHeapHashMap<String, String>(new UnlimitedPageSource(new HeapBufferSource()), (StorageEngine<? super String, ? super String>) storageEngine);

    HashMap<String, String> values = new HashMap<String, String>();
    for (int i = 0; i < 100; i++) {
      values.put(Integer.toString(i), Integer.toHexString(i));
    }

    map.putAll(values);
    Assert.assertThat(listener.getTrackingMap(), IsEqual.equalTo(map));

    for (int i = 0; i < 100; i++) {
      map.remove(Integer.toString(i));
      Assert.assertThat(listener.getTrackingMap(), IsEqual.equalTo(map));
    }
  }

  @Test
  public void testListeningForClears() {
    ListenableStorageEngine<String, String> storageEngine = createStorageEngine();

    TrackingListener<String, String> listener = new TrackingListener<String, String>();
    storageEngine.registerListener(listener);
    Map<String, String> map = new OffHeapHashMap<String, String>(new UnlimitedPageSource(new HeapBufferSource()), (StorageEngine<? super String, ? super String>) storageEngine);

    HashMap<String, String> values = new HashMap<String, String>();
    for (int i = 0; i < 100; i++) {
      values.put(Integer.toString(i), Integer.toHexString(i));
    }

    map.putAll(values);
    Assert.assertThat(listener.getTrackingMap(), IsEqual.equalTo(map));

    map.clear();
    Assert.assertThat(listener.getTrackingMap(), IsEqual.equalTo(map));
  }

  protected abstract ListenableStorageEngine<String, String> createStorageEngine();

  static class TrackingListener<K, V> implements RuntimeStorageEngineListener<K, V>, RecoveryStorageEngineListener<K, V> {

    private final Map<Long, Entry<K, V>> trackingMap = new HashMap<Long, Map.Entry<K,V>>();
    private final Set<Long> pinnedEncodings = new HashSet<Long>();

    @Override
    public void written(K key, V value, ByteBuffer binaryKey, ByteBuffer binaryValue, int hash, int metadata,
                        long encoding) {
      Assert.assertThat(key.hashCode(), Is.is(hash));
      Entry<K, V> previous = trackingMap.put(encoding, new SimpleEntry<K, V>(key, value));
      Assert.assertThat(previous, IsNull.nullValue());
    }

    @Override
    public void freed(long encoding, int hash, ByteBuffer key, boolean removed) {
      Entry<K, V> previous = trackingMap.remove(encoding);
      Assert.assertThat(previous, IsNull.notNullValue());
      Assert.assertThat(previous.getKey().hashCode(), Is.is(hash));
    }

    @Override
    public void cleared() {
      trackingMap.clear();
    }

    @Override
    public void copied(int hash, long oldEncoding, long newEncoding, int metadata) {
      Entry<K, V> mapping = trackingMap.get(oldEncoding);
      Assert.assertThat(mapping, IsNull.notNullValue());
      Assert.assertThat(mapping.getKey().hashCode(), Is.is(hash));
      Entry<K, V> previous = trackingMap.put(newEncoding, mapping);
      Assert.assertThat(previous, IsNull.nullValue());
      if ((Metadata.PINNED & metadata) == 0) {
        Assert.assertTrue(pinnedEncodings.remove(oldEncoding));
      } else {
        Assert.assertFalse(pinnedEncodings.remove(oldEncoding));
        Assert.assertTrue(pinnedEncodings.add(newEncoding));
      }
    }

    public Map<K, V> getTrackingMap() {
      Map<K, V> result = new HashMap<K, V>();
      for (Entry<K, V> entry : trackingMap.values()) {
        V previous = result.put(entry.getKey(), entry.getValue());
        Assert.assertThat(previous, IsNull.nullValue());
      }
      return result;
    }

    @Override
    public void recovered(Callable<? extends K> key, Callable<? extends V> value, ByteBuffer binaryKey, ByteBuffer binaryValue, int hash, int metadata, long encoding) {
      try {
        written(key.call(), value.call(), binaryKey, binaryValue, hash, metadata, encoding);
      } catch (Exception ex) {
        throw new AssertionError(ex);
      }
    }
  }
}


text:
package org.apache.usergrid.batch.job;

import org.junit.Ignore;
import org.junit.Test;

import org.apache.usergrid.persistence.entities.JobData;
import org.apache.usergrid.persistence.entities.JobStat;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Class to test job runtimes
 */

@Ignore("Pending https://issues.apache.org/jira/browse/USERGRID-1105. Spring problems." )
// These tests no longer work with shared Spring context, need to be fixed
public class SchedulerRuntime4IT extends AbstractSchedulerRuntimeIT {
    /**
     * Test the scheduler ramps up correctly when there are more jobs to be read after a pause when the job specifies
     * the retry time
     */
    @Test
    public void delayExecution() throws Exception {
        long sleepTime = Long.parseLong( props.getProperty( TIMEOUT_PROP ) );

        int delayCount = 2;

        long customRetry = sleepTime * 2;

        DelayExecution job = springResource.getBean( "delayExecution", DelayExecution.class );

        job.setTimeout( customRetry );

        int runCount = delayCount +1;

        job.setLatch( runCount );

        getJobListener().setExpected( runCount );

        JobData returned = scheduler.createJob( "delayExecution", System.currentTimeMillis(), new JobData() );

        scheduler.refreshIndex();

        // sleep until the job should have failed. We sleep 1 extra cycle just to
        // make sure we're not racing the test
        boolean waited = getJobListener().blockTilDone( 50000L + sleepTime * 2 );

        assertTrue( "Job ran to complete", waited );

        scheduler.refreshIndex();

        JobStat stat = scheduler.getStatsForJob( returned.getJobName(), returned.getUuid() );

        // we should have only marked this as run once since we delayed furthur execution
        // we should have only marked this as run once
        assertEquals( 1, stat.getTotalAttempts() );
        assertEquals( runCount, stat.getRunCount() );
        assertEquals( delayCount, stat.getDelayCount() );
    }
}


text:
import { run } from '@ember/runloop';
import EmberObject, { get } from '@ember/object';
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { storageDeepEqual } from '../helpers/storage';

import StorageObject from 'ember-local-storage/local/object';
import SessionStorageObject from 'ember-local-storage/session/object';
import {
  storageFor,
  _resetStorages,
} from 'ember-local-storage/helpers/storage';

let subject;

module('object - settings', function (hooks) {
  setupTest(hooks);

  hooks.beforeEach(function () {
    let mockStorage = StorageObject.extend();
    let mockStorageB = StorageObject.extend();
    let mockStorageC = SessionStorageObject.extend();
    let mockStorageD = StorageObject.extend();

    mockStorage.reopenClass({
      initialState() {
        return {
          welcomeMessageSeen: false,
        };
      },
    });

    mockStorageB.reopenClass({
      initialState() {
        return {
          address: {
            first: null,
            second: null,
            anotherProp: null,
          },
        };
      },
    });

    this.owner.register('storage:settings', mockStorage);
    this.owner.register('storage:nested-objects', mockStorageB);
    this.owner.register('storage:cache', mockStorageC);
    this.owner.register('storage:local-cache', mockStorageD);

    this.owner.register(
      'object:test',
      EmberObject.extend({
        settings: storageFor('settings'),
        nestedObjects: storageFor('nested-objects'),
        cache: storageFor('cache'),
        localCache: storageFor('local-cache'),
      })
    );
    subject = this.owner.lookup('object:test');
  });

  hooks.afterEach(function () {
    window.localStorage.clear();
    window.sessionStorage.clear();
    _resetStorages();
  });

  test('it has correct defaults', function (assert) {
    assert.expect(6);

    assert.equal(get(subject, 'settings._storageType'), 'local');
    assert.equal(get(subject, 'settings._storageKey'), 'storage:settings');
    assert.deepEqual(get(subject, 'settings._initialContent'), {
      welcomeMessageSeen: false,
    });

    assert.equal(get(subject, 'cache._storageType'), 'session');
    assert.equal(get(subject, 'cache._storageKey'), 'storage:cache');
    assert.deepEqual(get(subject, 'cache._initialContent'), {});
  });

  test('it saves changes to sessionStorage', function (assert) {
    assert.expect(3);

    assert.ok(window.sessionStorage);
    storageDeepEqual(assert, window.sessionStorage['storage:cache'], undefined);

    run(function () {
      subject.set('cache.image1', 'image1png');
    });

    storageDeepEqual(assert, window.sessionStorage['storage:cache'], {
      image1: 'image1png',
    });
  });

  test('it saves changes to localStorage', function (assert) {
    assert.expect(3);

    assert.ok(window.localStorage);
    storageDeepEqual(
      assert,
      window.localStorage['storage:settings'],
      undefined
    );

    run(function () {
      subject.set('settings.welcomeMessageSeen', true);
    });

    storageDeepEqual(assert, window.localStorage['storage:settings'], {
      welcomeMessageSeen: true,
    });
  });

  test('it does not share data', function (assert) {
    assert.expect(10);

    assert.equal(get(subject, 'cache._storageType'), 'session');
    assert.equal(get(subject, 'cache._storageKey'), 'storage:cache');
    assert.deepEqual(get(subject, 'cache._initialContent'), {});

    run(function () {
      subject.set('cache.key1', '123456');
    });

    assert.deepEqual(get(subject, 'cache.key1'), '123456');

    assert.equal(get(subject, 'localCache._storageType'), 'local');
    assert.equal(get(subject, 'localCache._storageKey'), 'storage:local-cache');
    assert.deepEqual(get(subject, 'localCache._initialContent'), {});

    assert.deepEqual(get(subject, 'cache.key1'), '123456');

    run(function () {
      subject.set('localCache.key1', 'abcde');
    });

    assert.deepEqual(get(subject, 'localCache.key1'), 'abcde');

    assert.deepEqual(get(subject, 'cache.key1'), '123456');
  });

  test('it updates when change events fire', function (assert) {
    assert.expect(3);

    // setup testing
    get(subject, 'settings')._testing = true;

    assert.equal(get(subject, 'settings.changeFired'), undefined);
    window.dispatchEvent(
      new window.StorageEvent('storage', {
        key: 'storage:settings',
        newValue: '{"welcomeMessageSeen":false,"changeFired":true}',
        oldValue: '{"welcomeMessageSeen":false}',
        storageArea: get(subject, 'settings')._storage(),
      })
    );
    assert.false(get(subject, 'settings.welcomeMessageSeen'));
    assert.true(get(subject, 'settings.changeFired'));
  });

  test('nested values get persisted', function (assert) {
    assert.expect(4);

    storageDeepEqual(
      assert,
      window.localStorage['storage:nested-objects'],
      undefined
    );

    assert.equal(get(subject, 'nestedObjects.address.first'), null);

    run(function () {
      get(subject, 'nestedObjects').set('address.first', {
        street: 'Somestreet 1',
        city: 'A City',
      });
    });

    assert.deepEqual(get(subject, 'nestedObjects.address.first'), {
      street: 'Somestreet 1',
      city: 'A City',
    });

    storageDeepEqual(assert, window.localStorage['storage:nested-objects'], {
      address: {
        first: {
          street: 'Somestreet 1',
          city: 'A City',
        },
        second: null,
        anotherProp: null,
      },
    });
  });

  test('reset method restores initialContent', function (assert) {
    assert.expect(5);

    //initialContent is set properly
    assert.deepEqual(get(subject, 'settings.content'), {
      welcomeMessageSeen: false,
    });

    //set new properties and overwrite others
    run(function () {
      subject.set('settings.newProp', 'some-value');
      subject.set('settings.welcomeMessageSeen', true);
    });

    //we expect them to be present
    assert.equal(get(subject, 'settings.newProp'), 'some-value');
    assert.true(get(subject, 'settings.welcomeMessageSeen'));

    //reset
    get(subject, 'settings').reset();

    //data is back to initial values
    assert.deepEqual(get(subject, 'settings.content'), {
      welcomeMessageSeen: false,
    });
    assert.strictEqual(get(subject, 'settings.newProp'), undefined);
  });

  test('it updates _isInitialContent', function (assert) {
    assert.expect(2);

    assert.true(get(subject, 'settings').isInitialContent());

    run(function () {
      subject.set('settings.welcomeMessageSeen', true);
    });

    assert.false(get(subject, 'settings').isInitialContent());
  });

  test('it updates _isInitialContent on reset', function (assert) {
    assert.expect(2);

    run(function () {
      subject.set('settings.welcomeMessageSeen', true);
    });

    assert.false(get(subject, 'settings').isInitialContent());

    run(function () {
      get(subject, 'settings').reset();
    });

    assert.true(get(subject, 'settings').isInitialContent());
  });

  test('clear method removes the content from localStorage', function (assert) {
    assert.expect(2);

    run(function () {
      subject.set('settings.welcomeMessageSeen', true);
    });

    storageDeepEqual(assert, window.localStorage['storage:settings'], {
      welcomeMessageSeen: true,
    });

    run(function () {
      get(subject, 'settings').clear();
    });

    assert.equal(window.localStorage['storage:settings'], undefined);
  });

  test('after .clear() the object works as expected', function (assert) {
    assert.expect(4);

    run(function () {
      subject.set('settings.welcomeMessageSeen', true);
    });

    storageDeepEqual(assert, window.localStorage['storage:settings'], {
      welcomeMessageSeen: true,
    });

    run(function () {
      get(subject, 'settings').clear();
    });

    assert.equal(window.localStorage['storage:settings'], undefined);

    run(function () {
      subject.set('settings.welcomeMessageSeen', true);
    });

    storageDeepEqual(assert, window.localStorage['storage:settings'], {
      welcomeMessageSeen: true,
    });
    assert.true(get(subject, 'settings.welcomeMessageSeen'));
  });
});