text:
package org.wso2.mdm.mdmmgt.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.mdm.mdmmgt.common.MDMException;

import java.util.List;

/**
 * MDMServiceAPIUtils class provides utility function.
 */
public class MDMServiceAPIUtils {

    private static Log log = LogFactory.getLog(MDMServiceAPIUtils.class);

    public static DeviceManagementProviderService getDeviceManagementService(int tenantId) {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(tenantId, true);
        DeviceManagementProviderService deviceManagementProviderService =
                (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
        if (deviceManagementProviderService == null) {
            String msg = "Device Management provider service has not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return deviceManagementProviderService;
    }

    public static int getTenantId(String tenantDomain) throws MDMException {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
        try {
            return realmService.getTenantManager().getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            throw new MDMException(
                    "Error obtaining tenant id from tenant domain " + tenantDomain);
        }
    }

    public static UserStoreManager getUserStoreManager(int tenantId) throws MDMException {
        RealmService realmService;
        UserStoreManager userStoreManager;
        try {
            PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            ctx.setTenantId(tenantId, true);
            realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
            if (realmService == null) {
                String msg = "Realm service has not initialized.";
                log.error(msg);
                throw new IllegalStateException(msg);
            }
            userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        } catch (UserStoreException e) {
            String msg = "Error occurred while retrieving current user store manager";
            log.error(msg, e);
            throw new MDMException(msg, e);
        }
        return userStoreManager;
    }

    /**
     * Getting the current tenant's user realm
     *
     * @return
     * @throws org.wso2.mdm.mdmmgt.common.MDMException
     */
    public static UserRealm getUserRealm(int tenantId) throws MDMException {
        RealmService realmService;
        UserRealm realm;
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            ctx.setTenantId(tenantId, true);
            ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
            ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
            realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);

            if (realmService == null) {
                String msg = "Realm service not initialized";
                log.error(msg);
                throw new MDMException(msg);
            }
            realm = realmService.getTenantUserRealm(tenantId);
        } catch (UserStoreException e) {
            String msg = "Error occurred while retrieving current user realm";
            log.error(msg, e);
            throw new MDMException(msg, e);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
        return realm;
    }

    public static AuthorizationManager getAuthorizationManager(int tenantId) throws MDMException {
        RealmService realmService;
        AuthorizationManager authorizationManager;
        try {
            PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            ctx.setTenantId(tenantId, true);
            realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
            if (realmService == null) {
                String msg = "Realm service has not initialized.";
                log.error(msg);
                throw new IllegalStateException(msg);
            }
            authorizationManager = realmService.getTenantUserRealm(tenantId).getAuthorizationManager();
        } catch (UserStoreException e) {
            String msg = "Error occurred while retrieving current Authorization manager.";
            log.error(msg, e);
            throw new MDMException(msg, e);
        }
        return authorizationManager;
    }

    /**
     * This method is used to get the current tenant id.
     *
     * @return returns the tenant id.
     */
    public static int getTenantId() {
        return CarbonContext.getThreadLocalCarbonContext().getTenantId();
    }

    public static DeviceIdentifier instantiateDeviceIdentifier(String deviceType, String deviceId) {
        DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
        deviceIdentifier.setType(deviceType);
        deviceIdentifier.setId(deviceId);
        return deviceIdentifier;
    }

    public static ApplicationManagementProviderService getAppManagementService(int tenantId) {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(tenantId, true);
        ApplicationManagementProviderService applicationManagementProviderService =
                (ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null);
        if (applicationManagementProviderService == null) {
            String msg = "Application management service has not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return applicationManagementProviderService;
    }

    public static PolicyManagerService getPolicyManagementService(int tenantId) {
        PolicyManagerService policyManagementService;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(tenantId, true);
        policyManagementService =
                (PolicyManagerService) ctx.getOSGiService(PolicyManagerService.class, null);
        if (policyManagementService == null) {
            String msg = "Policy Management service not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return policyManagementService;
    }

    public static TenantConfigurationManagementService getTenantConfigurationManagementService() {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        TenantConfigurationManagementService tenantConfigurationManagementService =
                (TenantConfigurationManagementService) ctx.getOSGiService(TenantConfigurationManagementService.class, null);
        if (tenantConfigurationManagementService == null) {
            String msg = "Tenant configuration Management service not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return tenantConfigurationManagementService;
    }

    public static NotificationManagementService getNotificationManagementService() {
        NotificationManagementService notificationManagementService;
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        notificationManagementService = (NotificationManagementService) ctx.getOSGiService(
                NotificationManagementService.class, null);
        if (notificationManagementService == null) {
            String msg = "Notification Management service not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }
        return notificationManagementService;
    }

    public static PaginationResult getPagingResponse(int recordsTotal, int recordsFiltered, int draw, List<?> data) {
        PaginationResult pagingResponse = new PaginationResult();
        pagingResponse.setRecordsTotal(recordsTotal);
        pagingResponse.setRecordsFiltered(recordsFiltered);
        pagingResponse.setDraw(draw);
        pagingResponse.setData(data);
        return pagingResponse;
    }
}


text:
package com.intellij.codeInspection.localCanBeFinal;

import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInspection.*;
import consulo.logging.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * @author max
 */
public class LocalCanBeFinal extends BaseJavaBatchLocalInspectionTool {
  private static final Logger LOG = Logger.getInstance(LocalCanBeFinal.class);

  public boolean REPORT_VARIABLES = true;
  public boolean REPORT_PARAMETERS = true;

  private final LocalQuickFix myQuickFix;
  @NonNls public static final String SHORT_NAME = "LocalCanBeFinal";

  public LocalCanBeFinal() {
    myQuickFix = new AcceptSuggested();
  }

  @Override
  public ProblemDescriptor[] checkMethod(@Nonnull PsiMethod method, @Nonnull InspectionManager manager, boolean isOnTheFly) {
    List<ProblemDescriptor> list = checkCodeBlock(method.getBody(), manager, isOnTheFly);
    return list == null ? null : list.toArray(new ProblemDescriptor[list.size()]);
  }

  @Override
  public ProblemDescriptor[] checkClass(@Nonnull PsiClass aClass, @Nonnull InspectionManager manager, boolean isOnTheFly) {
    List<ProblemDescriptor> allProblems = null;
    final PsiClassInitializer[] initializers = aClass.getInitializers();
    for (PsiClassInitializer initializer : initializers) {
      final List<ProblemDescriptor> problems = checkCodeBlock(initializer.getBody(), manager, isOnTheFly);
      if (problems != null) {
        if (allProblems == null) {
          allProblems = new ArrayList<ProblemDescriptor>(1);
        }
        allProblems.addAll(problems);
      }
    }
    return allProblems == null ? null : allProblems.toArray(new ProblemDescriptor[allProblems.size()]);
  }

  @Nullable
  private List<ProblemDescriptor> checkCodeBlock(final PsiCodeBlock body, InspectionManager manager, boolean onTheFly) {
    if (body == null) return null;
    final ControlFlow flow;
    try {
      ControlFlowPolicy policy = new ControlFlowPolicy() {
        @Override
        public PsiVariable getUsedVariable(PsiReferenceExpression refExpr) {
          if (refExpr.isQualified()) return null;

          PsiElement refElement = refExpr.resolve();
          if (refElement instanceof PsiLocalVariable || refElement instanceof PsiParameter) {
            if (!isVariableDeclaredInMethod((PsiVariable)refElement)) return null;
            return (PsiVariable)refElement;
          }

          return null;
        }

        @Override
        public boolean isParameterAccepted(PsiParameter psiParameter) {
          return isVariableDeclaredInMethod(psiParameter);
        }

        @Override
        public boolean isLocalVariableAccepted(PsiLocalVariable psiVariable) {
          return isVariableDeclaredInMethod(psiVariable);
        }

        private boolean isVariableDeclaredInMethod(PsiVariable psiVariable) {
          return PsiTreeUtil.getParentOfType(psiVariable, PsiClass.class) == PsiTreeUtil.getParentOfType(body, PsiClass.class);
        }
      };
      flow = ControlFlowFactory.getInstance(body.getProject()).getControlFlow(body, policy, false);
    }
    catch (AnalysisCanceledException e) {
      return null;
    }

    int start = flow.getStartOffset(body);
    int end = flow.getEndOffset(body);

    final List<PsiVariable> writtenVariables = new ArrayList<PsiVariable>(ControlFlowUtil.getWrittenVariables(flow, start, end, false));

    final HashSet<PsiVariable> ssaVarsSet = new HashSet<PsiVariable>();
    body.accept(new JavaRecursiveElementWalkingVisitor() {
      @Override public void visitCodeBlock(PsiCodeBlock block) {
        super.visitCodeBlock(block);
        PsiElement anchor = block;
        if (block.getParent() instanceof PsiSwitchStatement) {
          anchor = block.getParent();
        }
        int from = flow.getStartOffset(anchor);
        int end = flow.getEndOffset(anchor);
        List<PsiVariable> ssa = ControlFlowUtil.getSSAVariables(flow, from, end, true);
        HashSet<PsiElement> declared = getDeclaredVariables(block);
        for (PsiVariable psiVariable : ssa) {
          if (declared.contains(psiVariable)) {
            ssaVarsSet.add(psiVariable);
          }
        }
      }

      @Override public void visitForeachStatement(PsiForeachStatement statement) {
        super.visitForeachStatement(statement);
        final PsiParameter param = statement.getIterationParameter();
        final PsiStatement body = statement.getBody();
        if (body == null) return;
        int from = flow.getStartOffset(body);
        int end = flow.getEndOffset(body);
        if (!ControlFlowUtil.getWrittenVariables(flow, from, end, false).contains(param)) {
          writtenVariables.remove(param);
          ssaVarsSet.add(param);
        }
      }

      private HashSet<PsiElement> getDeclaredVariables(PsiCodeBlock block) {
        final HashSet<PsiElement> result = new HashSet<PsiElement>();
        PsiElement[] children = block.getChildren();
        for (PsiElement child : children) {
          child.accept(new JavaElementVisitor() {
            @Override public void visitReferenceExpression(PsiReferenceExpression expression) {
              visitReferenceElement(expression);
            }

            @Override public void visitDeclarationStatement(PsiDeclarationStatement statement) {
              PsiElement[] declaredElements = statement.getDeclaredElements();
              for (PsiElement declaredElement : declaredElements) {
                if (declaredElement instanceof PsiVariable) result.add(declaredElement);
              }
            }
          });
        }

        return result;
      }

      @Override public void visitReferenceExpression(PsiReferenceExpression expression) {
      }
    });

    ArrayList<PsiVariable> result = new ArrayList<PsiVariable>(ssaVarsSet);

    if (body.getParent() instanceof PsiMethod) {
      PsiMethod method = (PsiMethod)body.getParent();
      PsiParameter[] parameters = method.getParameterList().getParameters();
      for (PsiParameter parameter : parameters) {
        if (!result.contains(parameter)) result.add(parameter);
      }
    }

    PsiVariable[] psiVariables = result.toArray(new PsiVariable[result.size()]);
    for (PsiVariable psiVariable : psiVariables) {
      if (!isReportParameters() && psiVariable instanceof PsiParameter || !isReportVariables() && psiVariable instanceof PsiLocalVariable ||
          psiVariable.hasModifierProperty(PsiModifier.FINAL)) {
        result.remove(psiVariable);
      }

      if (psiVariable instanceof PsiLocalVariable) {
        PsiDeclarationStatement decl = (PsiDeclarationStatement)psiVariable.getParent();
        if (decl != null && decl.getParent() instanceof PsiForStatement) {
          result.remove(psiVariable);
        }
      }
    }

    for (PsiVariable writtenVariable : writtenVariables) {
      if (writtenVariable instanceof PsiParameter) {
        result.remove(writtenVariable);
      }
    }

    if (result.isEmpty()) return null;
    for (Iterator<PsiVariable> iterator = result.iterator(); iterator.hasNext();) {
      final PsiVariable variable = iterator.next();
      if (!variable.isPhysical()){
        iterator.remove();
      }
    }
    List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>(result.size());
    for (PsiVariable variable : result) {
      final PsiIdentifier nameIdenitier = variable.getNameIdentifier();
      PsiElement problemElement = nameIdenitier != null ? nameIdenitier : variable;
      if (variable instanceof PsiParameter && !(((PsiParameter)variable).getDeclarationScope() instanceof PsiForeachStatement)) {
        problems.add(manager.createProblemDescriptor(problemElement,
                                                     InspectionsBundle.message("inspection.can.be.local.parameter.problem.descriptor"),
                                                     myQuickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, onTheFly));
      }
      else {
        problems.add(manager.createProblemDescriptor(problemElement,
                                                     InspectionsBundle.message("inspection.can.be.local.variable.problem.descriptor"),
                                                     myQuickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, onTheFly));
      }
    }

    return problems;
  }

  @Override
  @Nonnull
  public String getDisplayName() {
    return InspectionsBundle.message("inspection.local.can.be.final.display.name");
  }

  @Override
  @Nonnull
  public String getGroupDisplayName() {
    return GroupNames.STYLE_GROUP_NAME;
  }

  @Override
  @Nonnull
  public String getShortName() {
    return SHORT_NAME;
  }

  private static class AcceptSuggested implements LocalQuickFix {
    @Override
    @Nonnull
    public String getName() {
      return InspectionsBundle.message("inspection.can.be.final.accept.quickfix");
    }

    @Override
    public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor problem) {
      if (!FileModificationService.getInstance().preparePsiElementForWrite(problem.getPsiElement())) return;
      PsiElement nameIdentifier = problem.getPsiElement();
      if (nameIdentifier == null) return;
      PsiVariable psiVariable = PsiTreeUtil.getParentOfType(nameIdentifier, PsiVariable.class, false);
      if (psiVariable == null) return;
      try {
        psiVariable.normalizeDeclaration();
        PsiUtil.setModifierProperty(psiVariable, PsiModifier.FINAL, true);
      }
      catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }

    @Override
    @Nonnull
    public String getFamilyName() {
      return getName();
    }
  }

  @Override
  public JComponent createOptionsPanel() {
    return new OptionsPanel();
  }

  private boolean isReportVariables() {
    return REPORT_VARIABLES;
  }

  private boolean isReportParameters() {
    return REPORT_PARAMETERS;
  }

  private class OptionsPanel extends JPanel {
    private final JCheckBox myReportVariablesCheckbox;
    private final JCheckBox myReportParametersCheckbox;

    private OptionsPanel() {
      super(new GridBagLayout());

      GridBagConstraints gc = new GridBagConstraints();
      gc.weighty = 0;
      gc.weightx = 1;
      gc.fill = GridBagConstraints.HORIZONTAL;
      gc.anchor = GridBagConstraints.NORTHWEST;

      myReportVariablesCheckbox = new JCheckBox(InspectionsBundle.message("inspection.local.can.be.final.option"));
      myReportVariablesCheckbox.setSelected(REPORT_VARIABLES);
      myReportVariablesCheckbox.getModel().addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
          REPORT_VARIABLES = myReportVariablesCheckbox.isSelected();
        }
      });
      gc.gridy = 0;
      add(myReportVariablesCheckbox, gc);

      myReportParametersCheckbox = new JCheckBox(InspectionsBundle.message("inspection.local.can.be.final.option1"));
      myReportParametersCheckbox.setSelected(REPORT_PARAMETERS);
      myReportParametersCheckbox.getModel().addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
          REPORT_PARAMETERS = myReportParametersCheckbox.isSelected();
        }
      });

      gc.weighty = 1;
      gc.gridy++;
      add(myReportParametersCheckbox, gc);
    }
  }

  @Override
  public boolean isEnabledByDefault() {
    return false;
  }
}

redpajama_set_name: RedPajamaGithub


text:
import pytest
import numpy as np

from matmodlab2 import MaterialPointSimulator, PolynomialHyperelasticMaterial
from testing_utils import *

@pytest.mark.material
@pytest.mark.polynomial_hyperelastic
def test_polynomial_hyperelastic():
    parameters = {'D1': 1.e-15, 'C10': 1e6, 'C01': .1e6}

    # stretch to 300%
    lam = np.linspace(.5, 3, 50)

    # Set up the simulator
    mps = MaterialPointSimulator('test1')
    mps.material = PolynomialHyperelasticMaterial(**parameters)

    # Drive the *incompressible* material through a path of uniaxial stress by
    # prescribing the deformation gradient.
    Fij = lambda x: (x, 0, 0, 0, 1/np.sqrt(x), 0, 0, 0, 1/np.sqrt(x))
    mps.run_step('F', Fij(lam[0]), frames=10)
    mps.run_step('F', Fij(1), frames=1)
    mps.run_step('F', Fij(lam[-1]), frames=20)

    # analytic solution for true and engineering stress
    C10, C01 = parameters['C10'], parameters['C01']
    s = 2*C01*lam - 2*C01/lam**2 + 2*C10*lam**2 - 2*C10/lam

    lam_ = np.exp(mps.get('E.XX'))
    ss = mps.get('S.XX') - mps.get('S.ZZ')
    print(ss)

    # check the actual solutions
    assert abs(np.amax(ss) - np.amax(s)) / np.amax(s) < 1e-6
    assert abs(np.amin(ss) - np.amin(s)) / np.amin(s) < 1e-6


text:
using AdventureGrainInterfaces;
using Orleans;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdventureClient
{
    class Program
    {
        static void Main(string[] args)
        {
            GrainClient.Initialize();

            Console.WriteLine(@"
  ___      _                 _
 / _ \    | |               | |
/ /_\ \ __| |_   _____ _ __ | |_ _   _ _ __ ___
|  _  |/ _` \ \ / / _ \ '_ \| __| | | | '__/ _ \
| | | | (_| |\ V /  __/ | | | |_| |_| | | |  __/
\_| |_/\__,_| \_/ \___|_| |_|\__|\__,_|_|  \___|");

            Console.WriteLine();
            Console.WriteLine("What's you name?");
            string name = Console.ReadLine();

            var player = GrainClient.GrainFactory.GetGrain<IPlayerGrain>(Guid.NewGuid());
            player.SetName(name).Wait();
            var room1 = GrainClient.GrainFactory.GetGrain<IRoomGrain>(0);
            player.SetRoomGrain(room1).Wait();

            Console.WriteLine(player.Play("look").Result);

            string result="Start";

            try
            {
                while (result!="")
                {
                    string command = Console.ReadLine();

                    result = player.Play(command).Result;
                    Console.WriteLine(result);
                }
            }
            finally
            {
                player.Die().Wait();
                Console.WriteLine("Game over!");
            }
        }
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<link rel="apple-touch-icon" sizes="180x180" href="assets/ico/apple-touch-icon.png">
	<link rel="icon" type="image/png" sizes="32x32" href="assets/ico/favicon-32x32.png">
	<link rel="icon" type="image/png" sizes="16x16" href="assets/ico/favicon-16x16.png">
	<link rel="manifest" href="assets/ico/manifest.json">
	<link rel="mask-icon" href="assets/ico/safari-pinned-tab.svg" color="#5bbad5">
	<link rel="shortcut icon" href="assets/ico/favicon.ico">
	<meta name="msapplication-config" content="assets/ico/browserconfig.xml">
	<meta name="theme-color" content="#ffffff">

	<title>Sweet Cups - Roll Ice Cream & Coffee</title>

	<link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.min.css">
	<link rel="stylesheet" href="assets/plugins/lightbox/css/lightbox.min.css">
	<link rel="stylesheet" href="assets/plugins/flickity/flickity.min.css">

	<link rel="stylesheet" href="assets/css/theme.css">

			Touché

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

			</button>

						About Us

							Menu

							Menu: Standard
							Menu: No Images

						Reservation

					Touché

						News & Events

						Gallery

						Contact

						News & Events

						Our latest news

						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia obcaecati sit odio velit culpa aspernatur consectetur natus quidem minima veritatis.

							<time datetime="2017-08-30">August 30, 2017</time>

							Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum voluptas, aut ea quae!

							Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit accusamus corporis nam eveniet, saepe, ipsum nostrum fugit, iste commodi expedita totam optio velit excepturi nemo, repellat doloribus laudantium repudiandae labore!

							Read more...

							<time datetime="2017-08-29">August 29, 2017</time>

							Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum voluptas, aut ea quae!

							Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit accusamus corporis nam eveniet, saepe, ipsum nostrum fugit, iste commodi expedita totam optio velit excepturi nemo, repellat doloribus laudantium repudiandae labore!

							Read more...

						Upcoming events

						Commodi rem veritatis quis eaque mollitia.

									<time datetime="2017-09-30">September 30, 2017</time>

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum voluptas, aut ea quae!

									Alias earum, labore doloremque iusto a modi et, dolorem veritatis iste quis ab. Facere est optio, voluptate molestias aspernatur impedit perferendis odit?

									Reserve a table

								<time datetime="2017-09-30">
									30 Sep
								</time>

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum voluptas, aut ea quae!

									Reserve a table

									<time datetime="2017-09-29">September 29, 2017</time>

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum voluptas, aut ea quae!

									Alias earum, labore doloremque iusto a modi et, dolorem veritatis iste quis ab. Facere est optio, voluptate molestias aspernatur impedit perferendis odit?

									Reserve a table

								<time datetime="2017-09-29">
									29 Sep
								</time>

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum voluptas, aut ea quae!

									Reserve a table

									<time datetime="2017-09-28">September 28, 2017</time>

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum voluptas, aut ea quae!

									Alias earum, labore doloremque iusto a modi et, dolorem veritatis iste quis ab. Facere est optio, voluptate molestias aspernatur impedit perferendis odit?

									Reserve a table

								<time datetime="2017-09-28">
									28 Sep
								</time>

									Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum voluptas, aut ea quae!

									Reserve a table

						Newsletter

						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam illo praesentium sequi in cum, beatae maiores quae qui.

						<form class="section_newsletter__form validate" action="//simpleqode.us15.list-manage.com/subscribe/post-json?u=507744bbfd1cc2879036c7780&id=4523d25e1b&c=?" method="get" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" target="_blank" novalidate="">

									E-mail address
									<input type="email" value="" name="EMAIL" class="required email form-control" id="mce-EMAIL" placeholder="Email address">

									<input type="text" name="b_507744bbfd1cc2879036c7780_4523d25e1b" tabindex="-1" value="">

									<button type="submit" class="btn btn-primary" id="mc-embedded-subscribe">
										Subscribe
									</button>

						</form>

						About Us

						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corrupti dolorum, sint corporis nostrum, possimus unde eos vitae eius quasi saepe.

						Contact info

							 1234 Altschul, New York, NY 10027-0000

							 +1 987 654 3210

							 admin@domain.com

						Opening hours

Monday - Thursday

10:00 AM - 11:00 PM

Friday - Sunday

12:00 AM - 03:00 AM

						  Touché. All rights reserved.


text:
import angular from "angular";

import highlandModule from "../highland/highland-module";

import { streamWhenVisible, documentHidden, documentVisible } from "./stream-when-visible";

import type { HighlandStreamT } from "highland";

export type streamWhenChartVisibleT = (streamFn: () => HighlandStreamT<mixed>) => HighlandStreamT<mixed>;

export default angular
  .module("streamWhenVisible", [highlandModule])
  .factory("streamWhenVisible", streamWhenVisible)
  .value("documentHidden", documentHidden)
  .value("documentVisible", documentVisible).name;


text:
<?php
$_pluginInfo=array(
	'name'=>'Walla',
	'version'=>'1.0.4',
	'description'=>"Get the contacts from a Walla mail account",
	'base_version'=>'1.6.5',
	'type'=>'email',
	'check_url'=>'http://friends.walla.co.il/?tsscript=login&theme=&ReturnURL=http://mail.walla.co.il/index.cgi',
	'requirement'=>'user',
	'allowed_domains'=>false,
	'imported_details'=>array('first_name','email_1'),
	);
/**
 * Walla Plugin
 *
 * Imports user's contacts from Walla's AddressBook
 *
 * @author OpenInviter
 * @version 1.0.0
 */
class walla extends openinviter_base
	{
	private $login_ok=false;
	public $showContacts=true;
	public $internalError=false;
	protected $timeout=30;

	public $debug_array=array(
				'initial_get'=>'@login',
				'post_login'=>'newaddress',
				'url_contacts'=>'@compose',
				);

	/**
	 * Login function
	 *
	 * Makes all the necessary requests to authenticate
	 * the current user to the server.
	 *
	 * @param string $user The current user.
	 * @param string $pass The password for the current user.
	 * @return bool TRUE if the current user was authenticated successfully, FALSE otherwise.
	 */
	public function login($user,$pass)
		{
		$this->resetDebugger();
		$this->service='walla';
		$this->service_user=$user;
		$this->service_password=$pass;
		if (!$this->init()) return false;

		$res=$this->get("http://friends.walla.co.il/?tsscript=login&theme=&ReturnURL=http://mail.walla.co.il/index.cgi",true);
		if ($this->checkResponse('initial_get',$res))
			$this->updateDebugBuffer('initial_get',"http://www.gawab.com/default.php",'GET');
		else
			{
			$this->updateDebugBuffer('initial_get',"http://www.gawab.com/default.php",'GET',false);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		$form_action="http://friends.walla.co.il/";
		$post_elements=array('w'=>'/@login.commit',
							'ReturnURL'=>'http://mail.walla.co.il/index.cgi',
							 'username'=>$user,
							 'password'=>$pass
							 );
		$res=$this->post($form_action,$post_elements,true);
		if ($this->checkResponse('post_login',$res))
			$this->updateDebugBuffer('post_login',"{$form_action}",'POST',true,$post_elements);
		else
			{
			$this->updateDebugBuffer('post_login',"{$form_action}",'POST',false,$post_elements);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}
		$url_contacts="http://newaddress.walla.co.il";
		$this->login_ok=$url_contacts;
		return true;
		}

	/**
	 * Get the current user's contacts
	 *
	 * Makes all the necesarry requests to import
	 * the current user's contacts
	 *
	 * @return mixed The array if contacts if importing was successful, FALSE otherwise.
	 */
	public function getMyContacts()
		{
		if (!$this->login_ok)
			{
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}
		else $url=$this->login_ok;
		$res=$this->get($url);
		if ($this->checkResponse('url_contacts',$res))
			$this->updateDebugBuffer('url_contacts',$url,'GET');
		else
			{
			$this->updateDebugBuffer('url_contacts',$url,'GET',false);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		$contacts=array();
		$doc=new DOMDocument();libxml_use_internal_errors(true);if (!empty($res)) $doc->loadHTML($res);libxml_use_internal_errors(false);
		$xpath=new DOMXPath($doc);$query="//a";$data=$xpath->query($query);
		foreach($data as $node)
			{
			if (strpos($node->getAttribute('href'),'@view')!==false) $name=$node->nodeValue;
			if (strpos($node->getAttribute('href'),'w=/@compose')!==false) $email=$node->nodeValue;
			if (!empty($email))
				$contacts[$email]=array('first_name'=>(!empty($name)?$name:false),'email_1'=>$email);
			}

		foreach ($contacts as $email=>$name) if (!$this->isEmail($email)) unset($contacts[$email]);
		return $this->returnContacts($contacts);

		}

	/**
	 * Terminate session
	 *
	 * Terminates the current user's session,
	 * debugs the request and reset's the internal
	 * debudder.
	 *
	 * @return bool TRUE if the session was terminated successfully, FALSE otherwise.
	 */
	public function logout()
		{
		if (!$this->checkSession()) return false;
		$res=$this->get("http://friends.walla.co.il/?w=/@logout",true);
		$this->debugRequest();
		$this->resetDebugger();
		$this->stopPlugin();
		return true;
		}

	}
?>


text:
WHOAMI=$(shell whoami)

SED_I = sed -i
ifeq ($(shell uname -s), Darwin)
    SED_I = sed -i ''
endif

nothing:

generate_proto:
	docker run --rm -v $(PWD):$(PWD) -w $(PWD) znly/protoc -I. --go_out=Mgoogle/protobuf/field_mask.proto=github.com/google/go-genproto/protobuf/field_mask,plugins=grpc:./ ./google_libphonenumber/resources/*.proto
	mv ./google_libphonenumber/resources/*.pb.go ./
	sudo chown -R $(WHOAMI) *
	$(SED_I) -E 's/package i18n_phonenumbers/package libphonenumber/g' $(shell ls *.pb.go)
	awk '/static const unsigned char/ { show=1 } show; /}/ { show=0 }' ./google_libphonenumber/cpp/src/phonenumbers/metadata.cc | tail -n +2 | sed '$$d' | sed -E 's/([^,])$$/\1,/g' | awk 'BEGIN{print "package libphonenumber\nvar metaData = []byte{"}; {print}; END{print "}"}' > metagen.go
	go fmt ./metagen.go

distupdate:
	rm -rf ./google_libphonenumber
	git clone --depth 1 https://github.com/googlei18n/libphonenumber.git ./google_libphonenumber/

update: distupdate generate_proto


text:
var path = require('path');

module.exports = function basename (filepath) { 'use strict';
    return path.basename(filepath, path.extname(filepath));
    };


text:
<tmpl,code=go:cat arg.go>
``` go
package main

import (
	"fmt"

	"github.com/jpillora/opts"
)

type Config struct {
	Foo string `type:"arg" help:"foo is a very important argument"`
	Bar string
}

func main() {

	c := Config{}

	opts.New(&c).Parse()

	fmt.Println(c.Foo)
	fmt.Println(c.Bar)
}
```
</tmpl>
```
$ arg --foo hello --bar world
```
<tmpl,code:go run arg.go --foo hello --bar world>
``` plain

  Usage: arg [options] <foo>

  foo is a very important argument

  Options:
  --bar, -b
  --help, -h

  Error:
    flag provided but not defined: -foo

```
</tmpl>
```
$ arg --help
```
<tmpl,code:go run arg.go --help>
``` plain

  Usage: arg [options] <foo>

  foo is a very important argument

  Options:
  --bar, -b
  --help, -h

```
</tmpl>


text:
<!DOCTYPE html>

    <title></title>

            Windows Store apps support standards-based Web Workers for multithreaded JavaScript. Web Workers can improve
            the responsiveness of your app by removing tasks from the UI thread. Web Workers can use the postMessage function to
            communicate with the UI thread.

            This example uses two Web Workers to calculate prime numbers. Even though this task is CPU intensive, the UI remains
            responsive because the calculations run inside the Web Workers.

        <button id="startPrimes" class="action">
            Calculate Primes</button>

Prime Numbers Found: 0


text:
<?php

namespace ch\tebe\worker;

abstract class AbstractWorker implements WorkerInterface
{
    /** @var array */
    protected $data = [];

    /** @var array */
    protected $services = [];

    /**
     * @return array
     */
    public function getKeys()
    {
        return [];
    }

    /**
     * @return string
     */
    public function getId()
    {
        return static::class;
    }

    /**
     * @param string $key
     * @return array
     */
    public function getData($key)
    {
        return $this->data[$key];
    }

    /**
     * @param string $key
     * @param array $data
     */
    public function setData($key, array $data)
    {
        $this->data[$key] = $data;
    }

    /**
     * @return array
     */
    public function work()
    {
        return [];
    }

    /**
     * @param string $name
     * @return object
     */
    public function getService($name)
    {
        return $this->services[$name];
    }

    /**
     * @return void
     */
    public function setServices(array $services)
    {
        $this->services = $services;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" colors="true" stopOnError="true">
    <testsuites>
        <testsuite>
            <directory suffix="Test.php">test</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>


text:
class SecurityService

  def rewrite_url(url, context)
    case Settings.streaming.server.to_sym
    when :aws
      configure_signer
      context[:protocol] ||= :stream_hls
      uri = Addressable::URI.parse(url)
      case context[:protocol]
      when :stream_hls
        Addressable::URI.join(Settings.streaming.http_base,uri.path).to_s
        #Aws::CF::Signer.sign_url(URI.join(Settings.streaming.http_base,uri.path).to_s, expires: expiration)
      else
        url
      end
    else
      session = context[:session] || { media_token: nil }
      token = StreamToken.find_or_create_session_token(session, context[:target])
      "#{url}?token=#{token}"
    end
  end

  def create_cookies(context)
    result = {}
    case Settings.streaming.server.to_sym
    when :aws
      configure_signer
      domain = Addressable::URI.parse(Settings.streaming.http_base).host
      cookie_domain = (context[:request_host].split(/\./) & domain.split(/\./)).join('.')
      resource = "http*://#{domain}/#{context[:target]}/*"
      Rails.logger.info "Creating signed policy for resource #{resource}"
      expiration = Settings.streaming.stream_token_ttl.minutes.from_now
      params = Aws::CF::Signer.signed_params(resource, expires: expiration, resource: resource)
      params.each_pair do |param,value|
        result["CloudFront-#{param}"] = {
          value: value,
          path: "/#{context[:target]}",
          domain: cookie_domain,
          expires: expiration
        }
      end
    end
    result
  end

  private

    def configure_signer
      require 'cloudfront-signer'
      unless Aws::CF::Signer.is_configured?
        Aws::CF::Signer.configure do |config|
          key = case Settings.streaming.signing_key
          when %r(^-----BEGIN)
            Settings.streaming.signing_key
          when %r(^s3://)
            FileLocator::S3File.new(Settings.streaming.signing_key).object.get.body.read
          when nil
            Rails.logger.warn('No CloudFront signing key configured')
          else
            File.read(Settings.streaming.signing_key)
          end
          config.key = key
          config.key_pair_id = Settings.streaming.signing_key_id
        end
      end
    end

end


text:
import * as eta from "eta-lib";

import * as express from "express";

export class Model implements eta.Model {
    public render(req: express.Request, res: express.Response, callback: (env: { [key: string]: any }) => void): void {
        if (!eta.params.test(req.body, ["userid", "positions"])) {
            callback({ errcode: eta.http.InvalidParameters });
            return;
        }
        eta.person.getByUsernameOrID(req.body.userid, req.body.userid, (person: eta.Person) => {
            if (person === null) {
                callback({ errcode: eta.http.NotFound });
                return;
            }
            // some columns are not explicitly listed because they are implicitly null
            let sql: string = `
                INSERT INTO Employee
                (id, current, international, maxHours, minHours, shirt, hoodie, mentor, workStudy)
                VALUES(?, 1, 0, 12, 27, '', '', -1, 0)
                ON DUPLICATE KEY UPDATE current = 1`;
            eta.db.query(sql, [person.id], (err: eta.DBError, rows: any[]) => {
                if (err) {
                    eta.logger.dbError(err);
                    callback({ errcode: eta.http.InternalError });
                    return;
                }
                let positions: string[] = JSON.parse(req.body.positions);
                let moreSql: string = "(?, ?, CURDATE(), NULL),".repeat(positions.length);
                let params: string[] = [];
                for (let i: number = 0; i < positions.length; i++) {
                    params.push(person.id);
                    params.push(positions[i]);
                }
                sql = `
                    INSERT INTO EmployeePosition (id, position, start, end)
                    VALUES ${moreSql.substring(0, moreSql.length - 1)}
                    ON DUPLICATE KEY UPDATE start = VALUES(start), end = VALUES(end)`;
                eta.db.query(sql, params, (err: eta.DBError, rows: any[]) => {
                    if (err) {
                        eta.logger.dbError(err);
                        callback({ errcode: eta.http.InternalError });
                        return;
                    }
                    callback({ "raw": "true" });
                });
            });
        });
    }
}


text:
namespace Alsolos.Commons.Wpf.Mvvm
{
    using System;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Threading;

    public class DelegateCommand : ICommand
    {
        private readonly Action _executeAction;
        private readonly Func<bool> _canExecute;

        public DelegateCommand(Action execute)
            : this(execute, null)
        {
        }

        public DelegateCommand(Action execute, Func<bool> canExecute)
        {
            _executeAction = execute;
            _canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }

            return _canExecute.Invoke();
        }

        public void Execute(object parameter)
        {
            _executeAction.Invoke();
        }

        public void RaiseCanExecuteChanged()
        {
            Application.Current.Dispatcher.Invoke(
                DispatcherPriority.DataBind,
                new Action(CommandManager.InvalidateRequerySuggested));
        }
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Storedetails_model extends MY_Model
{
	protected $_table="seller_store_details";

	protected $primary_key="seller_store_id";

	protected $soft_delete = FALSE;

    public $before_create = array( 'created_at', 'updated_at' );

    public $before_update = array( 'updated_at' );

	public function __construct()

	{
	parent::__construct();

	}

  public function insertseller_store($data)
{

	$this->db->insert('seller_store_details',$data);
  return $insert_id = $this->db->insert_id();

}

public function insertFiles($images){
	$sid= $this->session->userdata('seller_id');
	for($i=0; $i<count($images); $i++)
	{
	$data=array('seller_id'=>$sid,'file_name'=>$images[$i]);
	$this->db->insert('kyc_reports',$data);
	}
	return true;
	}

}


text:
package de.mrapp.android.adapter.datastructure.item;

import android.os.Parcel;
import android.os.Parcelable;

import java.io.Serializable;

import androidx.annotation.NonNull;
import de.mrapp.android.adapter.datastructure.AbstractAdapterItem;
import de.mrapp.util.Condition;

/**
 * A data structure, which holds the data of an item of an adapter. It has a state, a selection
 * state and may be enabled or disabled.
 *
 * @param <DataType>
 *         The type of the item's data
 * @author Michael Rapp
 * @since 0.1.0
 */
public class Item<DataType> extends AbstractAdapterItem<DataType> {

    /**
     * A creator, which allows to create instances of the class {@link Item} from parcels.
     */
    @SuppressWarnings("rawtypes")
    public static final Creator<Item> CREATOR = new Creator<Item>() {

        @Override
        public Item createFromParcel(final Parcel source) {
            return new Item(source);
        }

        @Override
        public Item[] newArray(final int size) {
            return new Item[size];
        }

    };

    /**
     * The constant serial version UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * True, if the item is selected, false otherwise.
     */
    private boolean selected;

    /**
     * True, if the item is enabled, false otherwise.
     */
    private boolean enabled;

    /**
     * The item's state.
     */
    private int state;

    /**
     * Creates a new data structure, which holds the data on an item of an adapter.
     *
     * @param source
     *         The source, the item should be created from, as an instance of the class {@link
     *         Parcel}. The source may not be null
     */
    protected Item(@NonNull final Parcel source) {
        super(source);
        setSelected(source.readInt() == 1);
        setEnabled(source.readInt() == 1);
        setState(source.readInt());
    }

    /**
     * Creates a new data structure, which holds the data of an item of an adapter.
     *
     * @param data
     *         The item's data, as an instance of the generic type DataType. The data may not be
     *         null
     */
    public Item(@NonNull final DataType data) {
        super(data);
        setEnabled(true);
        setSelected(false);
        setState(0);
    }

    /**
     * Returns, whether the item is selected, or not.
     *
     * @return True, if the item is selected, false otherwise
     */
    public final boolean isSelected() {
        return selected;
    }

    /**
     * Sets, whether the item is selected, or not.
     *
     * @param selected
     *         True, if the item should be selected, false otherwise
     */
    public final void setSelected(final boolean selected) {
        this.selected = selected;
    }

    /**
     * Returns, whether the item is enabled, or not.
     *
     * @return True, if the item is enabled false otherwise
     */
    public final boolean isEnabled() {
        return enabled;
    }

    /**
     * Sets, whether the item is enabled, or not.
     *
     * @param enabled
     *         True, if the item should be enabled, false otherwise
     */
    public final void setEnabled(final boolean enabled) {
        this.enabled = enabled;
    }

    /**
     * Returns the item's state.
     *
     * @return The item's state as an {@link Integer} value
     */
    public final int getState() {
        return state;
    }

    /**
     * Sets the item's state.
     *
     * @param state
     *         The state, which should be set as an {@link Integer} value. The value must be at
     *         least 0
     */
    public final void setState(final int state) {
        Condition.INSTANCE.ensureAtLeast(state, 0, "The state must be at least 0");
        this.state = state;
    }

    @Override
    public final boolean isParcelable() {
        if (getData() instanceof AbstractAdapterItem) {
            return ((AbstractAdapterItem) getData()).isParcelable();
        } else {
            return Parcelable.class.isAssignableFrom(getData().getClass());
        }
    }

    @Override
    public final boolean isSerializable() {
        if (getData() instanceof AbstractAdapterItem) {
            return ((AbstractAdapterItem) getData()).isSerializable();
        } else {
            return Serializable.class.isAssignableFrom(getData().getClass());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public final Item<DataType> clone() throws CloneNotSupportedException {
        try {
            DataType clonedData =
                    (DataType) getData().getClass().getMethod("clone").invoke(getData());
            Item<DataType> clonedItem = new Item<>(clonedData);
            clonedItem.setSelected(isSelected());
            clonedItem.setEnabled(isEnabled());
            clonedItem.setState(getState());
            return clonedItem;
        } catch (Exception e) {
            throw new CloneNotSupportedException();
        }
    }

    @Override
    public final String toString() {
        return "Item [data=" + getData() + ", selected=" + isSelected() + ", enabled=" +
                isEnabled() + ", state=" + getState() + "]";
    }

    @Override
    public final int hashCode() {
        final int prime = 31;
        int result = super.hashCode();
        result = prime * result + (enabled ? 1231 : 1237);
        result = prime * result + (selected ? 1231 : 1237);
        result = prime * result + state;
        return result;
    }

    @Override
    public final boolean equals(final Object obj) {
        if (this == obj)
            return true;
        if (!super.equals(obj))
            return false;
        if (getClass() != obj.getClass())
            return false;
        Item<?> other = (Item<?>) obj;
        if (enabled != other.enabled)
            return false;
        if (selected != other.selected)
            return false;
        if (state != other.state)
            return false;
        return true;
    }

    @Override
    public final void writeToParcel(final Parcel dest, final int flags) {
        super.writeToParcel(dest, flags);
        dest.writeInt(isSelected() ? 1 : 0);
        dest.writeInt(isEnabled() ? 1 : 0);
        dest.writeInt(getState());
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>
	Mobile Phone Setup Wizard
</title>

        <meta name="DCS.dcsuri" content="/en-us/140/dd936215(d=loband,l=en-us,v=exchsrvcs.140).aspx" />

        <meta name="NormalizedUrl" content="http://help.outlook.com/en-us/140/dd936215(d=loband,l=en-us,v=exchsrvcs.140).aspx" />

        <meta name="ms.normalizedurl" content="http://help.outlook.com/en-us/140/dd936215(d=loband,l=en-us,v=exchsrvcs.140).aspx" />

        <meta name="DCSext.Title" content="Mobile Phone Setup Wizard" />

        <meta name="DCSext.ContentType" content="article (conceptual overviews)" />

        <meta name="DCSext.CreativeWork" content="TechArticle" />

        <meta name="DCSext.Product" content="EXCHANGE" />

        <meta name="DCSext.ProductFamily" content="TECHNET_OFFICE" />

        <meta name="ms.prodfamily" content="OFFICE" />

        <meta name="ms.prod" content="EXCHANGE" />

        <meta name="VotingContextUrl" content="http://help.outlook.com/en-us/140/dd936215(d=loband,l=en-us,v=exchsrvcs.140).aspx" />

        <meta name="MN" content="FF7BF564-9:42:51 AM" />

        <meta name="Search.ShortId" content="dd936215" />

        <meta name="ms.shortidmsdn" content="dd936215" />

        <meta name="ms.locale" content="en-us" />

    <meta name="Search.MSHKeywordA" content="1b9ececc-cfcc-42cb-adc6-01c23d72496c" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.DCSext.Title" content="Mobile Phone Setup Wizard" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.DCSext.ContentType" content="article (conceptual overviews)" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.DCSext.CreativeWork" content="TechArticle" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.DCSext.Product" content="EXCHANGE" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.DCSext.ProductFamily" content="TECHNET_OFFICE" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.DoNotIndex" content="True" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ExchTagSA" content="Setup" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ExchTagSF" content="Mobile Phone" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ExchTagSSF" content="Setup" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ExchTagSSP" content="Live@edu" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ExchTagSSP" content="Microsoft Exchange" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ExchTagSSP" content="Office 365 for enterprises" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ExchTagSSP" content="Office 365 for professionals and small businesses" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ExchTagSUR" content="All" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ms.prodfamily" content="OFFICE" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.PageType" content="SelfHelp" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.PreferredLib" content="/help.outlook.com" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.PreferredSiteName" content="outlook" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.robots" content="noodp" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.robots" content="noydir" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.ms.prod" content="EXCHANGE" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.Locale" content="en-us" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.AssetID" content="1b9ececc-cfcc-42cb-adc6-01c23d72496c" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.TopicType" content="kbArticle" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.Abstract" content="You can use this wizard to get personalized instructions for setting up your mobile phone or tablet to access your account." xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.LastModifiedDate" content="2012-05-10" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSHAttr.LCID" content="1033" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.Microsoft.Help.Id" content="1b9ececc-cfcc-42cb-adc6-01c23d72496c" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.Description" content="You can use this wizard to get personalized instructions for setting up your mobile phone or tablet to access your account." xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSCategory" content="cc745982" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSCategoryV" content="cc745982EXCHSRVCS140" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSCategory" content="cc990226" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSCategoryV" content="cc990226EXCHSRVCS140" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSCategory" content="dd936215" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.MSCategoryV" content="dd936215EXCHSRVCS140" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.TocNodeId" content="dd936215" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHKeywordA" content="1b9ececc-cfcc-42cb-adc6-01c23d72496c" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="DCSext.Title:Mobile Phone Setup Wizard" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="DCSext.ContentType:article (conceptual overviews)" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="DCSext.CreativeWork:TechArticle" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="DCSext.Product:EXCHANGE" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="DCSext.ProductFamily:TECHNET_OFFICE" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="DoNotIndex:True" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ExchTagSA:Setup" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ExchTagSF:Mobile Phone" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ExchTagSSF:Setup" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ExchTagSSP:Live@edu" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ExchTagSSP:Microsoft Exchange" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ExchTagSSP:Office 365 for enterprises" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ExchTagSSP:Office 365 for professionals and small businesses" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ExchTagSUR:All" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ms.prodfamily:OFFICE" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="PageType:SelfHelp" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="PreferredLib:/help.outlook.com" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="PreferredSiteName:outlook" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="robots:noodp" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="robots:noydir" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="ms.prod:EXCHANGE" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="Locale:en-us" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="AssetID:1b9ececc-cfcc-42cb-adc6-01c23d72496c" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="TopicType:kbArticle" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="Abstract:You can use this wizard to get personalized instructions for setting up your mobile phone or tablet to access your account." xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="LastModifiedDate:2012-05-10" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="LCID:1033" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Microsoft.Help.Id" content="1b9ececc-cfcc-42cb-adc6-01c23d72496c" xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Description" content="You can use this wizard to get personalized instructions for setting up your mobile phone or tablet to access your account." xmlns:c="urn:msdn-com:mtps/2004/1/common" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSHAttr" content="Rating:55.714" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.Rating" content="55.714285" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="Search.Rating.FiveStarScale" content="2.78571425" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="MSMETANRatingMSMETAV" content="55.714285" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="TotalHelpfulVotes" content="46" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="TotalVotes" content="140" xmlns="http://www.w3.org/1999/xhtml" />
<meta name="HasCodeSamples" content="false" xmlns="http://www.w3.org/1999/xhtml" />

<link rel="stylesheet" type="text/css" href="http://i3.help.outlook.com/Combined.css?resources=0:Main,0:ImageSprite,0:OutlookHelp,0:OutlookHelp_Font_Small,0:SelfHelp;/areas/outlook/content/styles:0&amp;hashKey=A3FCA680B0EE41A588446C3418AB3210&amp;v=93537450BF3A7A05A8CED95101061BCD" />

Home

                        Bahasa Indonesia (Indonesia)

                        Bahasa Melayu (Malaysia)

                        Català (Català)

                        Deutsch (Deutschland)

                        English (Australia)

                        English (Canada)

                        English (India)

                        English (United Kingdom)

                        English (United States)

                        Español (España, alfabetización internacional)

                        Español (México)

                        Filipino (Pilipinas)

                        Nederlands (Nederland)

                        Português (Brasil)

                        Tiếng Việt (Việt Nam)

                        Türkçe (Türkiye)

                        dansk (Danmark)

                        eesti (Eesti)

                        euskara (euskara)

                        français (Canada)

                        français (France)

                        galego (galego)

                        hrvatski (Hrvatska)

                        italiano (Italia)

                        latviešu (Latvija)

                        lietuvių (Lietuva)

                        magyar (Magyarország)

                        norsk, bokmål (Norge)

                        polski (Polska)

                        português (Portugal)

                        română (România)

                        slovenski (Slovenija)

                        slovenčina (Slovenská republika)

                        srpski (Srbija i Crna Gora (Bivša))

                        suomi (Suomi)

                        svenska (Sverige)

                        íslenska (Ísland)

                        čeština (Česká republika)

                        Ελληνικά (Ελλάδα)

                        български (България)

                        русский (Россия)

                        српски (Србија и Црна Гора (Бивша))

                        українська (Україна)

                        Қазақ (Қазақстан)

                        עברית (ישראל)

                        العربية (المملكة العربية السعودية)

                        اُردو (پاکستان)

                        فارسى (ایران)

                        हिंदी (भारत)

                        ไทย (ไทย)

                        中文(中华人民共和国)

                        中文(台灣)

                        中文(香港特別行政區)

                        日本語 (日本)

                        한국어(대한민국)

            English (United States)

    Search - Please type a search term or phrase
    <input id="ohid_searchText" type="text" onkeydown="ehcAutoCompleteChangeColor(event)" onkeyup="ehcAutoCompleteGetList(event,'http://help.outlook.com/en-us/140/autocomplete(d=loband).aspx?prefix=--prefix--','http://help.outlook.com/en-us/140/search(d=loband).aspx?q=--query--')" onclick="ehcAutoCompleteChangeColor(event)" value="" />
    <input type="image" id="ohid_searchButton" alt="Search" class="cl_search" src="http://i.help.outlook.com/Areas/Global/Content/clear.gif" onclick="ehcAutoCompleteClickSearch('http://help.outlook.com/en-us/140/search(d=loband).aspx?q=--query--')" />

    Outlook Web App >

    Mobile Phones >

print

|

e-mail

|

            share

|

        feedback

    <form method="post" action="http://help.outlook.com/en-us/140/feedback(d=loband).aspx?id=dd936215">

            Tell us what you think X

        Was this topic helpful?

                <input id="feedbackQuestion" name="feedbackQuestion" type="radio" value="100.00" />

                Yes

                <input id="feedbackQuestion" name="feedbackQuestion" type="radio" value="20.00" />

                No

        Tell us more.

    <textarea id="ohid_feedbackComments" name="feedbackComments" rows="5" cols="42"></textarea>
    <input type="hidden" id="FeedbackText" name="FeedbackText" value="" />
    <input type="hidden" id="FeedbackInfo" name="FeedbackInfo" value="Please enter feedback here." />
    <input type="hidden" id="Feedback" name="Feedback" value="" />
    <textarea id="Comments" name="Comments" style="display:none;visibility:collapse" rows="5" cols="42"></textarea>

    <input type="submit" value="Send" id="ohid_feedbackSend" />
    </form>

Switch to text-only view

                Mobile Phone Setup Wizard

                You can use this wizard to get personalized instructions for setting up your mobile phone or tablet to access your account.  If your mobile phone or device supports Exchange ActiveSync (also referred to as Exchange e-mail), POP3, and IMAP4, you can choose which type of account to set up. Exchange ActiveSync is designed to synchronize e-mail, calendar, contact, task, and other information. POP3 and IMAP4 accounts are designed to send and receive e-mail messages.    If you do not see the wizard interface when viewing this page, you aren't viewing this page from the Help.Outlook.com Web site. To use the wizard, go to  at the Help.Outlook.com Web site.

    ©2017 Microsoft Corporation. All rights reserved.
    Terms of Use
    |
    Trademarks
    |
    Privacy Statement


text:
/*
 * This module contains user and roles related functionality
 */
var userModule = function () {
    var log = new Log("/app/modules/user.js");

    var constants = require("/app/modules/constants.js");
    var utility = require("/app/modules/utility.js")["utility"];
    var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
    var serviceInvokers = require("/app/modules/backend-service-invoker.js").backendServiceInvoker;

    /* Initializing user manager */
    var carbon = require('carbon');
    var tenantId = carbon.server.tenantId();
    var url = carbon.server.address('https') + "/admin/services";
    var server = new carbon.server.Server(url);
    var userManager = new carbon.user.UserManager(server, tenantId);

    var deviceManagementService = utility.getDeviceManagementService();
    var EmailMessageProperties = Packages.org.wso2.carbon.device.mgt.common.EmailMessageProperties;

    var publicMethods = {};
    var privateMethods = {};

    /**
     *  Get the carbon user object from the session. If not found - it will throw a user not found error.
     * @returns {carbon user object}
     */
    privateMethods.getCarbonUser = function () {
        var carbon = require('carbon');
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        return carbonUser;
    }

    /**
     * Only GET method is implemented for now since there are no other type of methods used this method.
     * @param url - URL to call the backend without the host
     * @param method - HTTP Method (GET, POST)
     * @returns {
     *  'status': 'success'|'error',
     *  'content': {}
     * }
     */
    privateMethods.callBackend = function (url, method) {
        switch (method) {
            case constants.HTTP_GET:
                var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) {
                        var response = {};
                        response.content = responsePayload["responseContent"];
                        if(responsePayload["responseContent"] == null && responsePayload != null){
                            response.content = responsePayload;
                        }
                        response.status = "success";
                        return response;
                    },
                    function (responsePayload) {
                        var response = {};
                        response.content = responsePayload;
                        response.status = "error";
                        return response;
                    });
                return response;
                break;
            case constants.HTTP_POST:
                //todo
                log.error("programing error");
                break;
            case constants.HTTP_PUT:
                //todo
                log.error("programing error");
                break;
            case constants.HTTP_DELETE:
                //todo
                log.error("programing error");
                break;
        }
    };

    /*
     @Deprecated
     */
    /**
     * Add user to devicemgt-user-store.
     *
     * @param username Username of the user
     * @param firstname First name of the user
     * @param lastname Last name of the user
     * @param emailAddress Email address of the user
     * @param userRoles Roles assigned to the user
     *
     * @returns {number} HTTP Status code 201 if succeeded, 409 if user already exists
     */
    publicMethods.addUser = function (username, firstname, lastname, emailAddress, userRoles) {
        var statusCode, carbon = require('carbon');
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try {
            utility.startTenantFlow(carbonUser);
            var tenantId = carbon.server.tenantId();
            var userManager = new carbon.user.UserManager(server, tenantId);
            if (userManager.userExists(username)) {
                if (log.isDebugEnabled()) {
                    log.debug("A user with name '" + username + "' already exists.");
                }
                // http status code 409 refers to - conflict.
                statusCode = 409;
            } else {
                var initialUserPassword = privateMethods.generateInitialUserPassword();
                var defaultUserClaims = privateMethods.buildDefaultUserClaims(firstname, lastname, emailAddress);

                userManager.addUser(username, initialUserPassword, userRoles, defaultUserClaims, "default");
                privateMethods.inviteUserToEnroll(username, initialUserPassword);
                if (log.isDebugEnabled()) {
                    log.debug("A new user with name '" + username + "' was created.");
                }
                // http status code 201 refers to - created.
                statusCode = 201;
            }
            return statusCode;
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /**
     * Register user to dc-user-store.
     *
     * @param username Username of the user
     * @param firstname First name of the user
     * @param lastname Last name of the user
     * @param emailAddress Email address of the user
     * @param password Password of the user
     * @param userRoles Roles assigned to the user
     *
     * @returns {number} HTTP Status code 201 if succeeded, 409 if user already exists
     */
    publicMethods.registerUser = function (username, firstname, lastname, emailAddress, password, userRoles) {
        var carbon = require('carbon');
        var tenantId = carbon.server.tenantId();
        var url = carbon.server.address('https') + "/admin/services";
        var server = new carbon.server.Server(url);
        var userManager = new carbon.user.UserManager(server, tenantId);

        try {
            if (userManager.userExists(username)) {
                if (log.isDebugEnabled()) {
                    log.debug("A user with name '" + username + "' already exists.");
                }
                // http status code 409 refers to - conflict.
                return 409;
            } else {
                var defaultUserClaims = privateMethods.buildDefaultUserClaims(firstname, lastname, emailAddress);

                for (var role in userRoles){
                    if (userRoles[role] == "iot-admin" && !userManager.roleExists("iot-admin")){
                        var permissions = {
                            '/permission/admin/device-mgt/devices': ['ui.execute'],
                            '/permission/admin/device-mgt/policies': ['ui.execute'],
                            '/permission/admin/device-mgt/user': ['ui.execute'],
                            '/permission/admin/device-mgt/users': ['ui.execute'],
                            '/permission/admin/device-mgt/admin/devices': ['ui.execute'],
                            '/permission/admin/device-mgt/admin/groups': ['ui.execute'],
                            '/permission/admin/device-mgt/admin/policies': ['ui.execute']
                        };
                        userManager.addRole("iot-admin", ["admin"], permissions);
                    }
                }

                userManager.addUser(username, password, userRoles, defaultUserClaims, "default");
                if (log.isDebugEnabled()) {
                    log.debug("A new user with name '" + username + "' was created.");
                }
                // http status code 201 refers to - created.
                return 201;
            }
        } catch (e) {
            throw e;
        }
    };

    /*
     @Deprecated
     */
    /**
     * Remove an existing user from devicemgt-user-store.
     *
     * @param username Username of the user
     * @returns {number} HTTP Status code 200 if succeeded, 409 if the user does not exist
     */
    publicMethods.removeUser = function (username) {
        var statusCode, carbon = require('carbon');
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try {
            utility.startTenantFlow(carbonUser);
            var tenantId = carbon.server.tenantId();
            var userManager = new carbon.user.UserManager(server, tenantId);
            if (userManager.userExists(username)) {
                userManager.removeUser(username);
                if (log.isDebugEnabled()) {
                    log.debug("An existing user with name '" + username + "' was removed.");
                }
                // http status code 200 refers to - success.
                statusCode = 200;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("A user with name '" + username + "' does not exist to remove.");
                }
                // http status code 409 refers to - conflict.
                statusCode = 409;
            }
            return statusCode;
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    /**
     * Private method to be used by addUser() to
     * generate an initial user password for a user.
     * This will be the password used by a user for his initial login to the system.
     *
     * @returns {string} Initial User Password
     */
    privateMethods.generateInitialUserPassword = function () {
        var passwordLength = 6;
        //defining the pool of characters to be used for initial password generation
        var lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
        var upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var numericCharset = "0123456789";

        var totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
        var totalCharsetLength = totalCharset.length;

        var initialUserPassword = "";
        for (var i = 0; i < passwordLength; ++i) {
            initialUserPassword += totalCharset.charAt(Math.floor(Math.random() * totalCharsetLength));
        }
        if (log.isDebugEnabled()) {
            log.debug("Initial password created for new user : " + initialUserPassword);
        }
        return String(initialUserPassword);
    };

    /*
     @Deprecated
     */
    /**
     * Build default user claims.
     *
     * @param firstname First name of the user
     * @param lastname Last name of the user
     * @param emailAddress Email address of the user
     *
     * @returns {Object} Default user claims to be provided
     */
    privateMethods.buildDefaultUserClaims = function (firstname, lastname, emailAddress) {
        var defaultUserClaims = {
            "http://wso2.org/claims/givenname": firstname,
            "http://wso2.org/claims/lastname": lastname,
            "http://wso2.org/claims/emailaddress": emailAddress
        };
        if (log.isDebugEnabled()) {
            log.debug("ClaimMap created for new user : " + stringify(defaultUserClaims));
        }
        return defaultUserClaims;
    };

    /*
     @Deprecated
     */
    /**
     * Send an initial invitation email to a user with username/password attached
     * for the very-first enrollment with WSO2 CDM.
     *
     * @param username Username of the user
     * @param password Password of the user
     */
    privateMethods.inviteUserToEnroll = function (username, password) {
        var carbon = require('carbon');
        var enrollmentURL = devicemgtProps.httpsURL + devicemgtProps.appContext + "download-agent";
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        //var user = userManagementService.getUser(username, carbonUser.tenantId);
        try {
            utility.startTenantFlow(carbonUser);
            var tenantId = carbon.server.tenantId();
            var userManager = new carbon.user.UserManager(server, tenantId);
            var emailTo = [];
            var user = userManager.getUser(username);
            emailTo[0] = privateMethods.getEmail(username, userManager);
            var emailMessageProperties = new EmailMessageProperties();
            emailMessageProperties.setMailTo(emailTo);
            emailMessageProperties.setFirstName(privateMethods.getFirstName(username, userManager));
            emailMessageProperties.setUserName(username);
            emailMessageProperties.setPassword(password);
            emailMessageProperties.setEnrolmentUrl(enrollmentURL);
            deviceManagementService.sendRegistrationEmail(emailMessageProperties);
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    privateMethods.getEmail = function (username, userManager) {
        return userManager.getClaim(username, "http://wso2.org/claims/emailaddress", null)
    };

    /*
     @Deprecated
     */
    privateMethods.getFirstName = function (username, userManager) {
        return userManager.getClaim(username, "http://wso2.org/claims/givenname", null)
    };

    /*
     @Deprecated
     */
    privateMethods.getLastName = function (username, userManager) {
        return userManager.getClaim(username, "http://wso2.org/claims/lastname", null)
    };

    /*
     @Deprecated
     */
    publicMethods.inviteUser = function (username) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        var enrollmentURL = devicemgtProps.httpsURL + devicemgtProps.appContext + "download-agent";

        try {
            utility.startTenantFlow(carbonUser);
            var tenantId = carbon.server.tenantId();
            var userManager = new carbon.user.UserManager(server, tenantId);
            var user = userManager.getUser(username);
            var emailProperties = new EmailMessageProperties();
            var emailTo = [];
            emailTo[0] = privateMethods.getEmail(username, userManager);
            emailProperties.setMailTo(emailTo);
            //emailProperties.setFirstName(user.getFirstName());
            emailProperties.setFirstName(privateMethods.getFirstName(username, userManager));
            emailProperties.setEnrolmentUrl(enrollmentURL);
            deviceManagementService.sendEnrolmentInvitation(emailProperties);
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Updated
     */
    publicMethods.getUsers = function () {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        var utility = require("/app/modules/utility.js")["utility"];
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        try {
            utility.startTenantFlow(carbonUser);
            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users";
            return privateMethods.callBackend(url, constants.HTTP_GET);

        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /**
     * Return a User object from the backend by calling the JAX-RS
     * @param username
     * @returns {
     *  'status': 'success'|'error',
     *  'content': {
            "username": "abc",
            "firstname": "abc",
            "lastname": "efj",
            "emailAddress": "abc@abc.com"
        }
     * }
     */
    publicMethods.getUser = function (username) {
        var carbonUser = privateMethods.getCarbonUser();
        try {
            utility.startTenantFlow(carbonUser);
            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/view?username=" + username;
            var response = privateMethods.callBackend(url, constants.HTTP_GET);
            response["userDomain"] = carbonUser.domain;
            return response;
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };
    /**
     * TODO: comment
     * @param username
     * @returns {*}
     */
    publicMethods.getRolesByUsername = function (username) {
        var carbonUser = privateMethods.getCarbonUser();
        try {
            utility.startTenantFlow(carbonUser);
            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/roles?username=" + username;
            var response = privateMethods.callBackend(url, constants.HTTP_GET);
            return response;
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    }

    /*
     @NewlyAdded
     */
    publicMethods.getUsersByUsername = function () {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        var utility = require("/app/modules/utility.js")["utility"];
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        try {
            utility.startTenantFlow(carbonUser);
            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/users-by-username";
            return privateMethods.callBackend(url, constants.HTTP_GET)
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Updated
     */
    /**
     * Get User Roles from user store (Internal roles not included).
     */
    publicMethods.getRoles = function () {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        var utility = require('/app/modules/utility.js')["utility"];
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        try {
            utility.startTenantFlow(carbonUser);
            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles";
            return privateMethods.callBackend(url, constants.HTTP_GET);
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /**
     * Get Platforms.
     */
    publicMethods.getPlatforms = function () {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        var utility = require('/app/modules/utility.js')["utility"];
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        try {
            utility.startTenantFlow(carbonUser);
            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types";
            return privateMethods.callBackend(url, constants.HTTP_GET);
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };
    /*
     @Updated
     */
    /**
     * Get role
     */
    publicMethods.getRole = function (roleName) {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        var utility = require('/app/modules/utility.js')["utility"];
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        try {
            utility.startTenantFlow(carbonUser);
            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/" + roleName;
            var response = privateMethods.callBackend(url, constants.HTTP_GET);
            return response;
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /**
     * Authenticate a user when he or she attempts to login to Devicemgt.
     *
     * @param username Username of the user
     * @param password Password of the user
     * @param successCallback Function to be called at the event of successful authentication
     * @param failureCallback Function to be called at the event of failed authentication
     */
    publicMethods.login = function (username, password, successCallback, failureCallback) {
        var carbonModule = require("carbon");
        var carbonServer = application.get("carbonServer");
        try {
            // check if the user is an authenticated user.
            var isAuthenticated = carbonServer.authenticate(username, password);
            if (isAuthenticated) {
                var tenantUser = carbonModule.server.tenantUser(username);
                session.put(constants.USER_SESSION_KEY, tenantUser);
                successCallback(tenantUser);
            } else {
                failureCallback();
            }
        } catch (e) {
            throw e;
        }
    };

    publicMethods.logout = function (successCallback) {
        session.invalidate();
        successCallback();
    };

    publicMethods.isAuthorized = function (permission) {
        var carbon = require("carbon");
        var carbonServer = application.get("carbonServer");
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            response.sendError(401, constants.ERRORS.USER_NOT_FOUND);
            exit();
        }

        try {
            utility.startTenantFlow(carbonUser);
            var tenantId = carbon.server.tenantId();
            var userManager = new carbon.user.UserManager(server, tenantId);
            var user = new carbon.user.User(userManager, carbonUser.username);
            return user.isAuthorized(permission, "ui.execute");
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.getUIPermissions = function () {
        var permissions = {};
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/devices/list") ||
            publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/list")) {
            permissions["LIST_DEVICES"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/groups/list")) {
            permissions["LIST_GROUPS"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/list")) {
            permissions["LIST_USERS"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/roles/list")) {
            permissions["LIST_ROLES"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/list")) {
            permissions["LIST_POLICIES"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/groups/add")) {
            permissions["ADD_GROUP"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/add")) {
            permissions["ADD_USER"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/roles/add")) {
            permissions["ADD_ROLE"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/add")) {
            permissions["ADD_POLICY"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/priority")) {
            permissions["CHANGE_POLICY_PRIORITY"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/dashboard/view")) {
            permissions["VIEW_DASHBOARD"] = true;
        }
        if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/platform-configs/view")) {
            permissions["TENANT_CONFIGURATION"] = true;
        }
        return permissions;
    };

    publicMethods.addPermissions = function (permissionList, path, init) {
        var registry, carbon = require("carbon");
        var carbonServer = application.get("carbonServer");
        var utility = require('/app/modules/utility.js').utility;
        var options = {system: true};
        if (init == "login") {
            try {
                var carbonUser = session.get(constants.USER_SESSION_KEY);
                if (!carbonUser) {
                    log.error("User object was not found in the session");
                    throw constants.ERRORS.USER_NOT_FOUND;
                }
                utility.startTenantFlow(carbonUser);
                var tenantId = carbon.server.tenantId();
                if (carbonUser) {
                    options.tenantId = tenantId;
                }
                registry = new carbon.registry.Registry(carbonServer, options);
                var i, permission, resource;
                for (i = 0; i < permissionList.length; i++) {
                    permission = permissionList[i];
                    resource = {
                        collection: true,
                        name: permission.name,
                        properties: {
                            name: permission.name
                        }
                    };
                    if (path != "") {
                        registry.put("/_system/governance/permission/admin/" + path + "/" + permission.key, resource);
                    } else {
                        registry.put("/_system/governance/permission/admin/" + permission.key, resource);
                    }
                }
            } catch (e) {
                throw e;
            } finally {
                utility.endTenantFlow();
            }
        } else {
            registry = new carbon.registry.Registry(carbonServer, options);
            var i, permission, resource;
            for (i = 0; i < permissionList.length; i++) {
                permission = permissionList[i];
                resource = {
                    collection: true,
                    name: permission.name,
                    properties: {
                        name: permission.name
                    }
                };
                if (path != "") {
                    registry.put("/_system/governance/permission/admin/" + path + "/" + permission.key, resource);
                } else {
                    registry.put("/_system/governance/permission/admin/" + permission.key, resource);
                }
            }
        }
    };

    /**
     * Private method to be used by addUser() to
     * retrieve secondary user stores.
     * This needs Authentication since the method access admin services.
     *
     * @returns {string array} Array of secondary user stores.
     */
    publicMethods.getSecondaryUserStores = function () {
        var returnVal = [];
        var endpoint = devicemgtProps.adminService + constants.USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT;
        var wsPayload = "<xsd:getSecondaryRealmConfigurations  xmlns:xsd='http://org.apache.axis2/xsd'/>";
        serviceInvokers.WS.soapRequest(
            "urn:getSecondaryRealmConfigurations", endpoint, wsPayload, function (wsResponse) {
                var domainIDs = stringify(wsResponse.*::['return']. *::domainId.text());
                if (domainIDs != "\"\"") {
                    var regExpForSearch = new RegExp(constants.USER_STORES_NOISY_CHAR, "g");
                    domainIDs = domainIDs.replace(regExpForSearch, "");
                    returnVal = domainIDs.split(constants.USER_STORES_SPLITTING_CHAR);
                }
            }, function (e) {
                log.error("Error retrieving secondary user stores", e);
            }, constants.SOAP_VERSION);
        return returnVal;
    };
    return publicMethods;
}();