Store sales funnel UTM parameters
and additional tracking parameters to session
542835
protected function buildTrackingParamsSession()
    {
        $this->utmSession = $this->getSession('utm_session');
        $this->utmSession->setExpiration('30 minutes');

        if ($this->getParameter('utm_source')) {
            $this->utmSession->utmSource = $this->getParameter('utm_source');
        }
        if ($this->getParameter('utm_medium')) {
            $this->utmSession->utmMedium = $this->getParameter('utm_medium');
        }
        if ($this->getParameter('utm_campaign')) {
            $this->utmSession->utmCampaign = $this->getParameter('utm_campaign');
        }
        if ($this->getParameter('utm_content')) {
            $this->utmSession->utmContent = $this->getParameter('utm_content');
        }

        // store additional parameters
        $this->additionalTrackingSession = $this->getSession('additional_tracking_params');
        $this->additionalTrackingSession->setExpiration('30 minutes');

        if ($this->getParameter('banner_variant')) {
            $this->additionalTrackingSession->bannerVariant = $this->getParameter('banner_variant');
        }
    }
659238
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    OrderServiceInterface orderService =
        adManagerServices.get(session, OrderServiceInterface.class);

    // Create a statement to select orders.
    StatementBuilder statementBuilder = new StatementBuilder()
        .where("status = :status and startDateTime >= :now and startDateTime <= :soon")
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
        .withBindVariableValue("status", OrderStatus.APPROVED.toString())
        .withBindVariableValue("now", DateTimes.toDateTime(Instant.now(), "America/New_York"))
        .withBindVariableValue("soon", DateTimes.toDateTime(Instant.now().plus(
            Duration.standardDays(5L)), "America/New_York"));

    // Retrieve a small amount of orders at a time, paging through
    // until all orders have been retrieved.
    int totalResultSetSize = 0;
    do {
      OrderPage page =
          orderService.getOrdersByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each order.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (Order order : page.getResults()) {
          System.out.printf(
              "%d) Order with ID %d and name '%s' was found.%n",
              i++,
              order.getId(),
              order.getName()
          );
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
365304
def addtrack(self, shipment_increment_id, carrier, title, track_number):
        
        return self.call(
            'sales_order_shipment.addTrack',
            [shipment_increment_id, carrier, title, track_number]
        )
1173913
def track(name, properties = {}, options = {})
      if exclude?
        debug "Event excluded"
      elsif missing_params?
        debug "Missing required parameters"
      else
        data = {
          visit_token: visit_token,
          user_id: user.try(:id),
          name: name.to_s,
          properties: properties,
          time: trusted_time(options[:time]),
          event_id: options[:id] || generate_id
        }.select { |_, v| v }

        @store.track_event(data)
      end
      true
    rescue => e
      report_exception(e)
    end
357134
public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException {
    // Get the ConversionTrackerService.
    ConversionTrackerServiceInterface service =
        adWordsServices.get(session, ConversionTrackerServiceInterface.class);

    List<ConversionTracker> conversionTrackers = new ArrayList<>();

    // Create an AdWords conversion tracker.
    AdWordsConversionTracker adWordsConversionTracker = new AdWordsConversionTracker();
    adWordsConversionTracker.setName("Earth to Mars Cruises Conversion # "
        + System.currentTimeMillis());
    adWordsConversionTracker.setCategory(ConversionTrackerCategory.DEFAULT);

    // You can optionally provide these field(s).
    adWordsConversionTracker.setStatus(ConversionTrackerStatus.ENABLED);
    adWordsConversionTracker.setViewthroughLookbackWindow(15);
    adWordsConversionTracker.setDefaultRevenueValue(1d);
    adWordsConversionTracker.setAlwaysUseDefaultRevenueValue(Boolean.TRUE);
    conversionTrackers.add(adWordsConversionTracker);

    // Create an upload conversion for offline conversion imports.
    UploadConversion uploadConversion = new UploadConversion();
    // Set an appropriate category. This field is optional, and will be set to
    // DEFAULT if not mentioned.
    uploadConversion.setCategory(ConversionTrackerCategory.LEAD);
    uploadConversion.setName("Upload Conversion #" + System.currentTimeMillis());
    uploadConversion.setViewthroughLookbackWindow(30);
    uploadConversion.setCtcLookbackWindow(90);

    // Optional: Set the default currency code to use for conversions
    // that do not specify a conversion currency. This must be an ISO 4217
    // 3-character currency code such as "EUR" or "USD".
    // If this field is not set on this UploadConversion, AdWords will use
    // the account's currency.
    uploadConversion.setDefaultRevenueCurrencyCode("EUR");

    // Optional: Set the default revenue value to use for conversions
    // that do not specify a conversion value. Note that this value
    // should NOT be in micros.
    uploadConversion.setDefaultRevenueValue(2.50);
    // Optional: To upload fractional conversion credits, mark the upload conversion
    // as externally attributed. See
    // https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions
    // to learn more about importing externally attributed conversions.

    // uploadConversion.setIsExternallyAttributed(true);

    conversionTrackers.add(uploadConversion);

    // Create operations.
    List<ConversionTrackerOperation> operations =
        conversionTrackers.stream()
            .map(
                conversionTracker -> {
                  ConversionTrackerOperation operation = new ConversionTrackerOperation();
                  operation.setOperator(Operator.ADD);
                  operation.setOperand(conversionTracker);
                  return operation;
                })
            .collect(Collectors.toList());

    // Add the conversions.
    ConversionTrackerReturnValue result =
        service.mutate(operations.toArray(new ConversionTrackerOperation[operations.size()]));

    // Display conversion.
    for (ConversionTracker conversionTracker : result.getValue()) {
      System.out.printf(
          "Conversion with ID %d, name '%s', status '%s', " + "category '%s' was added.%n",
          conversionTracker.getId(),
          conversionTracker.getName(),
          conversionTracker.getStatus(),
          conversionTracker.getCategory());
      if (conversionTracker instanceof AdWordsConversionTracker) {
        System.out.printf(
            "Google global site tag:%n%s%n%n", conversionTracker.getGoogleGlobalSiteTag());
        System.out.printf(
            "Google event snippet:%n%s%n%n", conversionTracker.getGoogleEventSnippet());
      }
    }
  }
755066
public void addParameter(Object owner, Parameter<?> param, TrackParameters track) {
    this.setBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED));
    ParameterConfigurator cfg = null;
    { // Find
      Object cur = owner;
      while(cur != null) {
        cfg = childconfig.get(cur);
        if(cfg != null) {
          break;
        }
        cur = track.getParent(cur);
      }
    }
    if(cfg != null) {
      cfg.addParameter(owner, param, track);
      return;
    }
    else {
      cfg = makeConfigurator(param);
      cfg.addChangeListener(this);
      children.add(cfg);
    }
  }
1130133
public void materialise(Session session) {

        PersistentStore store;

        // table constructors
        if (isDataExpression) {
            store = session.sessionData.getSubqueryRowStore(table);

            dataExpression.insertValuesIntoSubqueryTable(session, store);

            return;
        }

        Result result = queryExpression.getResult(session,
            isExistsPredicate ? 1
                              : 0);
        RowSetNavigatorData navigator =
            ((RowSetNavigatorData) result.getNavigator());

        if (uniqueRows) {
            navigator.removeDuplicates();
        }

        store = session.sessionData.getSubqueryRowStore(table);

        table.insertResult(store, result);
        result.getNavigator().close();
    }
443260
function getRangeRemote(start, limit, store) {
      // Request for data calling listRemote function
      store.listRemote(function() {
        // Get store data by range
        StoreMemory.getRange(start, limit, null, store);
        // Trigger user callback once data has been retrieved
        vcomet.triggerCallback("onGetRangeRemote", store);
      });
    }
1329158
function obtainInfo(action, id, cb) {
    request.post({
        url: action,
        form: {
            code: id,
            lng: 'en',
            type: 'update'
        },
        headers: {
            'Referer': 'https://track24.net',
            'Origin': 'https://track24.net'
        },
        timeout: 20000,
        maxAttempts: 2,
    }, function (error, response, body) {
        if (error || response.statusCode != 200) {
            cb(utils.errorDown())
            return
        }

        let data = null
        try {
            data = JSON.parse(body)
        } catch (error) {
            return cb(utils.errorParser(id, error.message))
        }

        if (data.status == undefined ||
            data.status != 'ok' ||
            (data.data.events.length == 1 &&
            data.data.events[0].operationAttributeTranslated == 'The track code is added to the database Track24.ru for automatic monitoring.')) {
            cb(utils.errorNoData())
            return
        }

        data.gearTrackID = id

        let entity = null
        try {
            entity = createTrackerEntity(data)
        } catch (error) {
            return cb(utils.errorParser(id, error.message))
        }

        if (entity != null) cb(null, entity)
    })
}
131232
def link_to_tracked_if(condition, name, track_path = "/", options = {}, html_options = {}, &block)
      raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
      html_options.merge!({:onclick => tracking_call(track_path)})
      link_to_unless !condition, name, options, html_options, &block
    end
1362213
public function saveTrackingInfo($visit_date) {
    $memberCampaignActivityStorage = $this->entityTypeManager->getStorage('openy_campaign_memb_camp_actv');
    /** @var \Drupal\taxonomy\TermStorageInterface $termStorage */
    $termStorage = $this->entityTypeManager->getStorage('taxonomy_term');
    $memberCampaignStorage = $this->entityTypeManager->getStorage('openy_campaign_member_campaign');
    $utilizationActivityStorage = $this->entityTypeManager->getStorage('openy_campaign_util_activity');
    /** @var \Drupal\node\NodeStorage $nodeStorage */
    $nodeStorage = $this->entityTypeManager->getStorage('node');

    $params = $this->request_stack->getCurrentRequest()->request->all();

    $config = $this->config('openy_campaign.general_settings');
    $activitiesCountMaxPerEntry = $config->get('activities_count_max_per_entry');
    $activitiesCountMaxPerActivity = $config->get('activities_count_max_per_activity');

    $dateRoute = \DateTime::createFromFormat('Y-m-d', $visit_date);
    $date = new \DateTime($dateRoute->format('d-m-Y'));
    $dateStamp = $date->format('U');
    if (!array_key_exists('activities', $params)) {
      $params['activities'] = NULL;
    }
    $activityIds = $params['activities'];
    $activities_count = isset($params['activities_count']) ? $params['activities_count'] : [];

    $memberCampaignId = $params['member_campaign_id'];

    // Invalidate all data of the active user.
    $this->cacheTagsInvalidator->invalidateTags(['member_campaign:' . $memberCampaignId]);

    $topTermId = $params['top_term_id'];

    /** @var \Drupal\taxonomy\Entity\Term $term */
    $term = $termStorage->load($topTermId);
    $childTerms = $termStorage->loadTree($term->getVocabularyId(), $topTermId, 1, TRUE);
    $activityTerms = [];
    /** @var \Drupal\taxonomy\Entity\Term $term */
    foreach ($childTerms as $term) {
      $activityTerms[] = $term->id();
    }

    // Delete all records first.
    $existingActivityIds = MemberCampaignActivity::getExistingActivities($memberCampaignId, $date, $activityTerms);

    $entities = $memberCampaignActivityStorage->loadMultiple($existingActivityIds);
    $memberCampaignActivityStorage->delete($entities);

    /** @var MemberCampaign $memberCampaign */
    $memberCampaign = $memberCampaignStorage->load($memberCampaignId);
    $campaignId = $memberCampaign->getCampaign()->id();

    $campaign = $nodeStorage->load($campaignId);

    $utilizationActivities = $campaign->get('field_utilization_activities')->getValue();
    $allowedActivities = [];
    foreach ($utilizationActivities as $utilizationActivity) {
      $allowedActivities[] = $utilizationActivity['value'];
    }
    $saveUtilizationActivity = in_array('tracking', $allowedActivities);
    $utilizationActivitySaved = FALSE;

    // Save new selection.
    if ($activityIds) {
      $activityIds = array_filter($activityIds);
    }
    else {
      $activityIds = [];
    }

    foreach ($activityIds as $activityTermId) {
      $activityCount = 0.0;
      // If Activity Counter is disabled save zero value.
      if ($campaign->field_enable_activities_counter->value) {
        if (
          isset($activities_count[$activityTermId]) &&
          $activities_count[$activityTermId] > 0
        ) {
          $activityCount = $activities_count[$activityTermId];
        }
      }

      // Validate the count value by entry and in total.
      if ($activityCount > $activitiesCountMaxPerEntry) {
        $activityCount = $activitiesCountMaxPerEntry;
      }

      if ($activityCount > 0) {
        /** @var \Drupal\Core\Database\Query\Select $query */
        $query = $this->connection->select('openy_campaign_memb_camp_actv', 'mca');
        $query->condition('mca.member_campaign', $memberCampaignId)
          ->condition('mca.activity', $activityTermId)
          ->condition('mca.date', $dateStamp);
        $query->addExpression('SUM(mca.count)', 'sum_count');

        $sumCount = $query->execute()->fetchField();
        if ($sumCount + $activityCount > $activitiesCountMaxPerActivity) {
          $activityCount = 0.0;
        }
      }

      // To prevent duplicate activities creation we need to check if the activity was not created earlier.
      $query = $memberCampaignActivityStorage->getQuery()
        ->condition('member_campaign', $memberCampaignId)
        ->condition('activity', $activityTermId)
        ->condition('date', $dateStamp)
        ->execute();
      if (!empty($query)) {
        continue;
      }

      $preparedData = [
        'created' => time(),
        'date' => $dateStamp,
        'member_campaign' => $memberCampaignId,
        'activity' => $activityTermId,
        'count' => floatval($activityCount),
      ];

      $activity = $memberCampaignActivityStorage->create($preparedData);
      $activity->save();

      // Mark user for activate utilization activity.
      if ($saveUtilizationActivity && !$utilizationActivitySaved) {
        $loadedEntity = $utilizationActivityStorage->getQuery()
          ->condition('member_campaign', $memberCampaignId)
          ->execute();

        if (empty($loadedEntity)) {
          $preparedActivityData = [
            'member_campaign' => $memberCampaignId,
            'created' => time(),
            'activity_type' => 'tracking'
          ];
          $campaignUtilizationActivity = $utilizationActivityStorage->create($preparedActivityData);
          $campaignUtilizationActivity->save();

          $utilizationActivitySaved = TRUE;
        }
      }
    }
    return new AjaxResponse();

  }
290638
@Override
    public void saveChanges() {
        BatchOperation saveChangeOperation = new BatchOperation(this);

        try (BatchCommand command = saveChangeOperation.createRequest()) {
            if (command == null) {
                return;
            }

            if (noTracking) {
                throw new IllegalStateException("Cannot execute saveChanges when entity tracking is disabled in session.");
            }

            _requestExecutor.execute(command, sessionInfo);
            updateSessionAfterSaveChanges(command.getResult());
            saveChangeOperation.setResult(command.getResult());
        }
    }
626624
function track(backend, eventName, action, label) {

        action = action || location.pathname;
        switch (backend) {

        // ##### Google-Analytics
        case "google-analytics":
            var pageTracker = window._gat && window._gat._getTracker(settings.backends[backend].accountid);
            if (! pageTracker) {
                return;
            }
            if (eventName == PAGEVIEW) {
                pageTracker._trackPageview(action);
            } else {
                // https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
                pageTracker._trackEvent("pilotfish:" + eventName, action, label || "");
            }
            break;

        // ##### Mixpanel
        case "mixpanel":
            if (eventName == PAGEVIEW) {
                window.mixpanel && window.mixpanel.track_pageview(action);
            } else {
                window.mixpanel && window.mixpanel.track(eventName, {action: action, label: label});
            }
            break;

        // ##### Pilotfish Session
        case "pilotfish-session":
            var session = window.sessionStorage;

            if (! session) {
                return;
            }
            if (eventName == PAGEVIEW) {
                // Increment a counter in sessionStorage.
                // Retrieve with `Pilotfish('session', 'pageViews')`
                Pilotfish('session', 'INCR', 'pageViews');
            } else {
                // Store events in a list in sessionStorage as JSON
                // Retrieve with `Pilotfish('session', 'events')`
                Pilotfish('session', 'PUSH', 'events', {eventName: eventName, action: action, label: label});
            }
            break;

        // ##### TODO: Pilotfish API as a backend

        // ##### Quantcast
        case "quantcast":
            if (eventName == PAGEVIEW) {
                window._qevents && window._qevents.push({qacct: settings.backends[backend].accountid});
                // Reload the js. It won't *actually* reload it network-wise, because it will be cached
                Pilotfish('loadScript', (location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js");
            }
            break;


        // ##### Unrecognized
        default:
            Pilotfish('perror', "Invalid backend for recorder");
            break;
        }
    }
27676
private static function getPredefinedCustomTargetingKeyIds(
        ServiceFactory $serviceFactory,
        AdManagerSession $session
    ) {
        $customTargetingKeyIds = [];

        $customTargetingService = $serviceFactory->createCustomTargetingService(
            $session
        );

        // Create a statement to get all custom targeting keys.
        $pageSize = StatementBuilder::SUGGESTED_PAGE_LIMIT;
        $statementBuilder = (new StatementBuilder())->where('type = :type')
            ->orderBy('id ASC')
            ->limit($pageSize)
            ->withBindVariableValue('type', CustomTargetingKeyType::PREDEFINED);

        // Retrieve a small amount of custom targeting keys at a time, paging
        // through until all custom targeting keys have been retrieved.
        $totalResultSetSize = 0;
        do {
            $page = $customTargetingService->getCustomTargetingKeysByStatement(
                $statementBuilder->toStatement()
            );

            if ($page->getResults() !== null) {
                $totalResultSetSize = $page->getTotalResultSetSize();
                $i = $page->getStartIndex();
                foreach ($page->getResults() as $customTargetingKey) {
                    printf(
                        "%d) Custom targeting key with ID %d, name '%s', and"
                        . " display name '%s' was found.%s",
                        $i++,
                        $customTargetingKey->getId(),
                        $customTargetingKey->getName(),
                        $customTargetingKey->getDisplayName(),
                        PHP_EOL
                    );
                    $customTargetingKeyIds[] = $customTargetingKey->getId();
                }
            }

            $statementBuilder->increaseOffsetBy($pageSize);
        } while ($statementBuilder->getOffset() < $totalResultSetSize);

        printf(
            "Number of keys found: %d%s%s",
            $totalResultSetSize,
            PHP_EOL,
            PHP_EOL
        );

        return $customTargetingKeyIds;
    }
100281
function obtainInfo(action, id, hash, cb) {
    request.post({
        url: action,
        form: {
            trackingNo: id,
            trackingNoString: id,
            __hash__: hash
        },
        jar: j,
        timeout: 30000
    }, function (error, response, body) {
        if (error || response.statusCode != 200) {
            cb(utils.errorDown())
            return
        }

        let $ = parser.load(body);
        let trs = $('.center_table table tbody tr');
        // Not found
        if (trs.length < 2) {
            cb(utils.errorNoData())
            return
        }

        let entity = null
        try {
            entity = createWinitEntity(
                trs[1].children[0].children[0].data,
                $('.center_table table tbody tr td a.poptips')[0].attribs['data-id'])
        } catch (error) {
            return cb(utils.errorParser(id, error.message))
        }

        cb(null, entity)
    })
}
218590
function utm(query){
  if ('?' == query.charAt(0)) query = query.substring(1);
  var query = query.replace(/\?/g, '&');
  var params = parse(query);
  var param;
  var ret = {};

  for (var key in params) {
    if (~key.indexOf('utm_')) {
      param = key.substr(4);
      if ('campaign' == param) param = 'name';
      ret[param] = params[key];
    }
  }

  return ret;
}
1084722
def _map_purchase_request_to_func(self, purchase_request_type):
        """"""
        
        if purchase_request_type in self._intent_view_funcs:
            view_func = self._intent_view_funcs[purchase_request_type]
        else:
            raise NotImplementedError('Request type "{}" not found and no default view specified.'.format(purchase_request_type)) 

        argspec = inspect.getargspec(view_func)
        arg_names = argspec.args
        arg_values = self._map_params_to_view_args(purchase_request_type, arg_names)

        print('_map_purchase_request_to_func', arg_names, arg_values, view_func, purchase_request_type)
        return partial(view_func, *arg_values)