Returns the unfinished papers of a user for a given exercise for the current day, if any.

@param Exercise $exercise
@param User     $user

@return Paper[]
542548
public function countUserFinishedDayPapers(Exercise $exercise, User $user)
    {
        $today = new \DateTime();
        $today->setTime(0, 0);
        $tomorrow = clone $today;
        $tomorrow->add(new \DateInterval('P1D'));

        return (int) $this->getEntityManager()
          ->createQuery('
              SELECT COUNT(p)
              FROM UJM\ExoBundle\Entity\Attempt\Paper AS p
              WHERE p.user = :user
                AND p.exercise = :exercise
                AND p.end >= :today
                AND p.end <= :tomorrow
          ')
          ->setParameters([
              'user' => $user,
              'exercise' => $exercise,
              'today' => $today,
              'tomorrow' => $tomorrow,
          ])
          ->getSingleScalarResult();
    }
176631
protected function getTableRowForUser(User $user)
    {
        $roleNames = [];
        $accountIdentifiers = [];
        foreach ($user->getAccounts() as $account) {
            /** @var Account $account */
            $authenticationProviderName = $account->getAuthenticationProviderName();
            if ($authenticationProviderName !== $this->userService->getDefaultAuthenticationProviderName()) {
                $authenticationProviderLabel = ' (' . (isset($this->authenticationProviderSettings[$authenticationProviderName]['label']) ? $this->authenticationProviderSettings[$authenticationProviderName]['label'] : $authenticationProviderName) . ')';
            } else {
                $authenticationProviderLabel = '';
            }
            $accountIdentifiers[] = $account->getAccountIdentifier() . $authenticationProviderLabel;
            foreach ($account->getRoles() as $role) {
                /** @var Role $role */
                $roleNames[] = $role->getIdentifier();
            }
        }
        return [$user->getName()->getFullName(), $user->getPrimaryElectronicAddress(), implode(', ', $accountIdentifiers), implode(', ', $roleNames), ($user->isActive() ? 'yes' : 'no')];
    }
1310301
public function isScoreAvailable(Exercise $exercise, Paper $paper)
    {
        $markMode = $exercise->getMarkMode();
        switch ($markMode) {
            case ShowScoreAt::AFTER_END:
                $available = !empty($paper->getEnd());
                break;
            case ShowScoreAt::NEVER:
                $available = false;
                break;
            case ShowScoreAt::WITH_CORRECTION:
            default:
                $available = $this->isSolutionAvailable($exercise, $paper);
                break;
        }

        return $available;
    }
602755
public function completed(UserInterface $user)
    {
        $queryBuilder = $this->createQueryBuilder('a');

        $queryBuilder
            ->where('a.user = :user')
            ->andWhere('a.completed = :completed');

        $queryBuilder
            ->setParameters([
                'user' => $user,
                'completed' => true
            ]);

        try
        {
            return $queryBuilder->getQuery()->getSingleResult();
        }
        catch (NoResultException $e)
        {
            return false;
        }
    }
629644
public function get_user_completion($user_id, $criteria) {
        $params = array(
            'course'        => $this->course_id,
            'userid'        => $user_id,
            'criteriaid'    => $criteria->id,
        );

        $completion = new completion_criteria_completion($params);
        return $completion;
    }
893789
public function userWorkspaceListAction(User $user, $page, $max)
    {
        $pager = $this->workspaceManager->getOpenableWorkspacesByRolesPager($user->getRoles(), $page, $max);

        return array('user' => $user, 'pager' => $pager, 'page' => $page, 'max' => $max);
    }
629760
public function getStatistics(Exercise $exercise, $maxScore)
    {
        return [
            'maxScore' => $maxScore,
            'nbSteps' => $exercise->getSteps()->count(),
            'nbQuestions' => $this->exerciseRepository->countExerciseQuestion($exercise),
            'nbPapers' => $this->paperManager->countExercisePapers($exercise),
            'nbRegisteredUsers' => $this->paperManager->countPapersUsers($exercise),
            'nbAnonymousUsers' => $this->paperManager->countAnonymousPapers($exercise),
            'minMaxAndAvgScores' => $this->getMinMaxAverageScores($exercise, $maxScore),
            'paperSuccessDistribution' => $this->getPapersSuccessDistribution($exercise, $maxScore),
            'paperScoreDistribution' => $this->getPaperScoreDistribution($exercise, $maxScore),
            'questionsDifficultyIndex' => $this->getQuestionsDifficultyIndex($exercise),
            'discriminationCoefficient' => $this->getDiscriminationCoefficient($exercise),
        ];
    }
1053854
private function getDiscriminationCoefficient(Exercise $exercise)
    {
        // get all scores for the exercise
        $papers = $this->paperRepository->findBy([
            'exercise' => $exercise,
        ]);

        $itemRepository = $this->om->getRepository('UJMExoBundle:Item\Item');
        $reportScoreOn = 100;
        // all scores obtained for an exercise
        $exerciseScores = $this->getPapersScores($papers, $reportScoreOn);
        // exercise standard deviation
        $standardDeviationE = $this->getStandardDeviation($exerciseScores);
        // get average score per exercise
        $exerciseAverageScore = $this->getMinMaxAverageScores($exercise, $reportScoreOn)['avg'];
        // all scores obtained per question
        $questionsScores = [];
        // all average scores per question
        $questionsAvgScores = [];
        // all margin marks per question
        $questionsMarginMark = [];
        // computed result to return
        $discriminationCoef = [];

        /** @var Paper $paper */
        foreach ($papers as $paper) {
            // base success compution on paper structure
            $structure = json_decode($paper->getStructure(), true);

            foreach ($structure['steps'] as $step) {
                foreach (array_filter($step['items'], function ($item) {
                    return ItemType::isSupported($item['type']);
                }) as $item) {
                    // since the compution is based on the structure the same item can come several times
                    if (!array_key_exists($item['id'], $discriminationCoef)) {
                        $itemEntity = $itemRepository->findOneBy(['uuid' => $item['id']]);
                        // set questions scores
                        $questionsScores[$item['id']] = $this->itemManager->getItemScores($exercise, $itemEntity);
                        // get average score for the item
                        $questionsAvgScores[$item['id']] = array_sum($questionsScores[$item['id']]) / count($questionsScores[$item['id']]);
                        $i = 0;

                        foreach ($questionsScores[$item['id']] as $score) {
                            $questionsMarginMark[$item['id']][] = ($score - $questionsAvgScores[$item['id']]) * ($exerciseScores[$i] - $exerciseAverageScore);
                            ++$i;
                        }

                        $questionProductMarginMark = $questionsMarginMark[$item['id']];
                        $sumPenq = array_sum($questionProductMarginMark);
                        $sumPenq = round($sumPenq, 3);
                        $standardDeviationQ = $this->getStandardDeviation($questionsScores[$item['id']]);
                        $n = count($questionProductMarginMark);
                        $nSxSy = $n * $standardDeviationQ * $standardDeviationE;
                        $coef = $nSxSy === floatval(0) ? 0 : round($sumPenq / ($nSxSy), 3);

                        $discriminationCoef[$item['id']] = [
                            'xData' => $itemEntity->getTitle() ? strip_tags($itemEntity->getTitle()) : strip_tags($itemEntity->getContent()),
                            'yData' => $coef,
                        ];
                    }
                }
            }
        }

        return $discriminationCoef;
    }
583166
public function getExceeded($user_id, $existing = null)
    {
        $limit = $this->getLimit($user_id);

        if (empty($limit)) {
            return array();
        }

        if (!isset($existing)) {
            $existing = $this->getList(array('user_id' => $user_id));
        }

        $count = count($existing);

        if (empty($count) || $count <= $limit) {
            return array();
        }

        return array_slice((array) $existing, 0, ($count - $limit));
    }
1320871
public function getUserAssertionsAction(Request $request, User $user)
    {
        $assertions = $this->finder->search(Assertion::class, array_merge(
            $request->query->all(),
            ['hiddenFilters' => ['recipient' => $user->getUuid()]]
        ));

        return new JsonResponse($assertions);
    }
771079
public function findLastEntriesByUser($game, $user, $dateLimit)
    {
        $query = $this->em->createQuery(
            'SELECT e.id FROM PlaygroundGame\Entity\Entry e 
             WHERE e.user = :user AND e.game = :game AND (e.bonus = 0 OR e.bonus IS NULL) AND e.created_at >= :date'
        );
        $query->setParameter('user', $user);
        $query->setParameter('game', $game);
        $query->setParameter('date', $dateLimit);

        $total = $query->getResult();

        return $total;
    }
555234
@Programmatic
    public List<PublishedEvent> findRecentByUser(final String user) {
        return repositoryService.allMatches(
                new QueryDefault<>(PublishedEvent.class, "findRecentByUser", "user", user));

    }
1319775
public function getRegistrationsSummaryForUser(User $user)
    {
        $data = [];
        $rsm = $this->createResultSetMappingBuilder('d');
        $rsm->addScalarResult('sbas_id','sbas_id');
        $rsm->addScalarResult('base_id','base_id');
        $rsm->addScalarResult('dbname','dbname');
        $rsm->addScalarResult('time_limited', 'time_limited');
        $rsm->addScalarResult('limited_from', 'limited_from');
        $rsm->addScalarResult('limited_to', 'limited_to');
        $rsm->addScalarResult('actif', 'actif');

        $sql = "
        SELECT dbname, sbas.sbas_id, time_limited,
               UNIX_TIMESTAMP( limited_from ) AS limited_from,
               UNIX_TIMESTAMP( limited_to ) AS limited_to,
               bas.server_coll_id, Users.id, basusr.actif,
               bas.base_id, " . $rsm->generateSelectClause(['d' => 'd',]) . "
        FROM (Users, bas, sbas)
          LEFT JOIN basusr ON ( Users.id = basusr.usr_id AND bas.base_id = basusr.base_id )
          LEFT JOIN Registrations d ON ( d.user_id = Users.id AND bas.base_id = d.base_id )
        WHERE basusr.actif = 1 AND bas.sbas_id = sbas.sbas_id
        AND Users.id = ?";

        $query = $this->_em->createNativeQuery($sql, $rsm);
        $query->setParameter(1, $user->getId());

        foreach ($query->getResult() as $row) {
            $registrationEntity = $row[0];
            $data[$row['sbas_id']][$row['base_id']] = [
                'base-id' => $row['base_id'],
                'db-name' => $row['dbname'],
                'active' => (Boolean) $row['actif'],
                'time-limited' => (Boolean) $row['time_limited'],
                'in-time' => $row['time_limited'] && ! ($row['limited_from'] >= time() && $row['limited_to'] <= time()),
                'registration' => $registrationEntity
            ];
        }

        return $data;
    }
595478
public function getAssignments(User $user)
    {
        $assignments = [];
        foreach ($this->getInternalServices() as $service) {
            $assignments = array_merge($assignments, $service->getAssignments($user));
        }

        return $assignments;
    }
478376
public function get_files(stdClass $submission, stdClass $user) {
        $result = array();
        $fs = get_file_storage();

        $files = $fs->get_area_files($this->assignment->get_context()->id,
                                     'assignsubmission_file',
                                     ASSIGNSUBMISSION_FILE_FILEAREA,
                                     $submission->id,
                                     'timemodified',
                                     false);

        foreach ($files as $file) {
            // Do we return the full folder path or just the file name?
            if (isset($submission->exportfullpath) && $submission->exportfullpath == false) {
                $result[$file->get_filename()] = $file;
            } else {
                $result[$file->get_filepath().$file->get_filename()] = $file;
            }
        }
        return $result;
    }
408671
public function usersWorkflows(Member $user)
    {

        $groupIds = $user->Groups()->column('ID');

        $groupInstances = null;

        $filter = array('');

        if (is_array($groupIds)) {
            $groupInstances = DataList::create(WorkflowInstance::class)
                ->filter(array('Group.ID:ExactMatchMulti' => $groupIds))
                ->where('"WorkflowStatus" != \'Complete\'');
        }

        $userInstances = DataList::create(WorkflowInstance::class)
            ->filter(array('Users.ID:ExactMatch' => $user->ID))
            ->where('"WorkflowStatus" != \'Complete\'');

        if ($userInstances) {
            $userInstances = $userInstances->toArray();
        } else {
            $userInstances = array();
        }

        if ($groupInstances) {
            $groupInstances = $groupInstances->toArray();
        } else {
            $groupInstances = array();
        }

        $all = array_merge($groupInstances, $userInstances);

        return ArrayList::create($all);
    }
849949
public function getAvailableRoutes($user = null): array
    {
        if ($user instanceof ModelDecoratorInterface) {
            $user = $user->getModel();
        }
        if (is_null($user)) {
            $user = $this->helper->getCurrentUser();
        }

        $routes = [];
        foreach ($this->router->getRouteCollection()->getIterator() as $routeName => $route) {
            if (!$this->checkRouteAccess($routeName, $user)) {
                continue;
            }

            if (!isset($routes['routes'])) {
                $routes['routes'] = [];
            }
            $routes['routes'][$route->getPath()] = $route->getPath();
        }

        $tree = $this->treeBuilder->getTree();
        if (!empty($tree['route_patterns'])) {
            foreach ($tree['route_patterns'] as $pattern => $permissions) {
                if (!$this->la->checkAccess($permissions, ['user' => $user])) {
                    continue;
                }

                if (!isset($routes['route_patterns'])) {
                    $routes['route_patterns'] = [];
                }
                $routes['route_patterns'][$pattern] = $pattern;
            }
        }

        return $routes;
    }