Initiates a semester"s worth of workshift, with the option to copy
    workshift types from the previous semester.
505270
def start_semester_view(request):
    
    page_name = "Start Semester"
    year, season = utils.get_year_season()
    start_date, end_date = utils.get_semester_start_end(year, season)

    semester_form = SemesterForm(
        data=request.POST or None,
        initial={
            "year": year,
            "season": season,
            "start_date": start_date.strftime(date_formats[0]),
            "end_date": end_date.strftime(date_formats[0]),
        },
        prefix="semester",
    )

    pool_forms = []
    try:
        prev_semester = Semester.objects.latest("end_date")
    except Semester.DoesNotExist:
        pass
    else:
        pools = WorkshiftPool.objects.filter(
            semester=prev_semester,
            is_primary=False,
        )
        for pool in pools:
            form = StartPoolForm(
                data=request.POST or None,
                initial={
                    "title": pool.title,
                    "hours": pool.hours,
                },
                prefix="pool-{}".format(pool.pk),
            )
            pool_forms.append(form)

    if semester_form.is_valid() and all(i.is_valid() for i in pool_forms):
        # And save this semester
        semester = semester_form.save()
        for pool_form in pool_forms:
            pool_form.save(semester=semester)
        return HttpResponseRedirect(wurl("workshift:manage",
                                         sem_url=semester.sem_url))

    return render_to_response("start_semester.html", {
        "page_name": page_name,
        "semester_form": semester_form,
        "pool_forms": pool_forms,
    }, context_instance=RequestContext(request))
576211
private void addNewWorkUnits(MultiWorkUnitWeightedQueue multiWorkUnitWeightedQueue) {
    try {
      List<PartitionAwareFileRetriever.FileInfo> filesToPull =
          retriever.getFilesToProcess(this.lowWaterMark, this.maxFilesPerJob - this.fileCount);
      Collections.sort(filesToPull);
      String topicName = this.sourceDir.getName();
      String namespace = this.sourceState.getProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY);

      Map<Long, Extract> extractMap = new HashMap<>();
      for (PartitionAwareFileRetriever.FileInfo file : filesToPull) {
        Extract extract = getExtractForFile(file, topicName, namespace, extractMap);

        LOG.info("Will process file " + file.getFilePath());

        WorkUnit singleWorkUnit = WorkUnit.create(extract);
        singleWorkUnit.setProp(ConfigurationKeys.SOURCE_ENTITY, topicName);
        singleWorkUnit.setProp(ConfigurationKeys.SOURCE_FILEBASED_FILES_TO_PULL, file.getFilePath());
        singleWorkUnit.setProp(ConfigurationKeys.WORK_UNIT_LOW_WATER_MARK_KEY, file.getWatermarkMsSinceEpoch());
        singleWorkUnit.setProp(ConfigurationKeys.WORK_UNIT_HIGH_WATER_MARK_KEY, file.getWatermarkMsSinceEpoch());
        singleWorkUnit.setProp(ConfigurationKeys.WORK_UNIT_DATE_PARTITION_KEY, file.getWatermarkMsSinceEpoch());
        singleWorkUnit.setProp(ConfigurationKeys.WORK_UNIT_DATE_PARTITION_NAME, file.getPartitionName());
        if (this.sourceState.getPropAsBoolean(ConfigurationKeys.SCHEMA_IN_SOURCE_DIR,
            ConfigurationKeys.DEFAULT_SCHEMA_IN_SOURCE_DIR)) {
          addSchemaFile(file, singleWorkUnit);
        }

        multiWorkUnitWeightedQueue.addWorkUnit(singleWorkUnit, file.getFileSize());

        this.fileCount++;
      }

      LOG.info("Total number of files extracted for the current run: " + filesToPull.size());
    } catch (IOException e) {
      Throwables.propagate(e);
    }
  }
56640
def initialize_copy(other)
      @fields = {}

      self.type = other.type
      self.key = other.key

      add(other.fields)
    end
86439
def semester_view(request, semester, profile=None):
    
    template_dict = {}
    template_dict["page_name"] = "Workshift for {} {}".format(
        semester.get_season_display(),
        semester.year,
    )

    today = localtime(now()).date()
    template_dict["semester_percentage"] = int(
        (today - semester.start_date).days /
        (semester.end_date - semester.start_date).days * 100
    )

    # We want a form for verification, a notification of upcoming shifts, and a
    # chart displaying the entire house's workshift for the day as well as
    # weekly shifts.
    #
    # The chart should have left and right arrows on the sides to switch the
    # day, with a dropdown menu to select the day from a calendar. Ideally,
    # switching days should use AJAX to appear more seemless to users.

    # Recent History
    day = _get_date(request, "day", today)
    start_date = _get_date(request, "start_date", day)
    end_date = _get_date(request, "end_date", day)

    template_dict["day"] = day
    template_dict["start_date"] = start_date
    template_dict["end_date"] = end_date
    template_dict["long_range"] = (end_date - start_date).days > 7

    if day > semester.start_date:
        template_dict["prev_day"] = (start_date - timedelta(days=1)).strftime("%Y-%m-%d")
    if day < semester.end_date:
        template_dict["next_day"] = (end_date + timedelta(days=1)).strftime("%Y-%m-%d")

    if Semester.objects.count() > 1:
        switch_form = SwitchSemesterForm(
            data=request.POST if "switch_semester" in request.POST else None
        )
        template_dict["switch_form"] = switch_form

        if switch_form.is_valid():
            semester = switch_form.save()
            return HttpResponseRedirect(semester.get_view_url())

    # Grab the shifts for just today, as well as week-long shifts
    day_shifts = WorkshiftInstance.objects.filter(
        date__gte=start_date,
        date__lte=end_date,
    ).exclude(
        Q(weekly_workshift__week_long=True) |
        Q(info__week_long=True),
    )

    last_monday = start_date - timedelta(days=start_date.weekday())
    next_sunday = end_date - timedelta(days=end_date.weekday() + 1) + timedelta(weeks=1)

    week_shifts = WorkshiftInstance.objects.filter(
        Q(weekly_workshift__week_long=True) |
        Q(info__week_long=True),
        date__gte=last_monday, date__lte=next_sunday,
    )

    template_dict["last_monday"] = last_monday.strftime("%Y-%m-%d")
    template_dict["next_sunday"] = next_sunday.strftime("%Y-%m-%d")

    # Add a login form for anonymous user
    if profile is None and request.user.username == ANONYMOUS_USERNAME:
        anonymous_form = AnonymousUserLogin(
            data=request.POST or None,
            prefix="anon",
            semester=semester,
        )

        if anonymous_form.is_valid():
            profile = anonymous_form.save()

        template_dict["anonymous_form"] = anonymous_form

    template_dict["day_shifts"] = [
        (shift, _get_forms(
            profile, shift, request,
            undo=utils.can_manage(request.user, semester=semester, pool=shift.pool),
        ))
        for shift in day_shifts
    ]
    template_dict["week_shifts"] = [
        (shift, _get_forms(
            profile, shift, request,
            undo=utils.can_manage(request.user, semester=semester, pool=shift.pool),
        ))
        for shift in week_shifts
    ]

    # Save any forms that were submitted
    all_forms = [
        form
        for instance, forms in template_dict["day_shifts"]
        for form in forms
    ] + [
        form
        for instance, forms in template_dict["week_shifts"]
        for form in forms
    ]
    for form in all_forms:
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(
                semester.get_view_url() + _get_date_params(request)
            )
        else:
            for error in form.errors.values():
                messages.add_message(request, messages.ERROR, error)

    return render_to_response(
        "semester.html",
        template_dict,
        context_instance=RequestContext(request),
    )
684583
def copy(self):
        
        # new objects are constructed for each, so we just need to pass them in
        return BinaryQuadraticModel(self.linear, self.quadratic, self.offset, self.vartype, **self.info)
1022846
def copy(self):
        
        new = type(self)(str(self))
        new._init_from_channel(self)
        return new
906408
def copy(self):
        """"""
        return self.__class__(self._key, self._load, self._iteritems())
1221876
def copy(self):
        """"""
        return self.__class__(self, key=self._key, load=self._load)
337710
private void introduceMoveOperation() {
        for (int i = 0; i < diffs.size(); i++) {
            Diff diff1 = diffs.get(i);

            // if not remove OR add, move to next diff
            if (!(Operation.REMOVE == diff1.getOperation() ||
                    Operation.ADD == diff1.getOperation())) {
                continue;
            }

            for (int j = i + 1; j < diffs.size(); j++) {
                Diff diff2 = diffs.get(j);
                if (!diff1.getValue().equals(diff2.getValue())) {
                    continue;
                }

                Diff moveDiff = null;
                if (Operation.REMOVE == diff1.getOperation() &&
                        Operation.ADD == diff2.getOperation()) {
                    JsonPointer relativePath = computeRelativePath(diff2.getPath(), i + 1, j - 1, diffs);
                    moveDiff = new Diff(Operation.MOVE, diff1.getPath(), relativePath);

                } else if (Operation.ADD == diff1.getOperation() &&
                        Operation.REMOVE == diff2.getOperation()) {
                    JsonPointer relativePath = computeRelativePath(diff2.getPath(), i, j - 1, diffs); // diff1's add should also be considered
                    moveDiff = new Diff(Operation.MOVE, relativePath, diff1.getPath());
                }
                if (moveDiff != null) {
                    diffs.remove(j);
                    diffs.set(i, moveDiff);
                    break;
                }
            }
        }
    }
56062
def _copy_default(cls, default):
        ''' 

        '''
        if not isinstance(default, types.FunctionType):
            return copy(default)
        else:
            return default()
516522
def new_workunit(self, name, labels=None, cmd='', log_config=None):
    
    with self.run_tracker.new_workunit(name=name, labels=labels, cmd=cmd, log_config=log_config) as workunit:
      yield workunit
628793
def list_types_view(request, semester, profile=None):
    
    page_name = "Workshift Types"
    full_management = utils.can_manage(request.user, semester)
    any_management = utils.can_manage(request.user, semester, any_pool=True)

    types = WorkshiftType.objects.all()
    type_shifts = [
        RegularWorkshift.objects.filter(
            workshift_type=i,
            pool__semester=semester,
        ).order_by("day")
        for i in types
    ]
    shift_edits = [
        [
            (
                shift,
                full_management or
                utils.can_manage(request.user, semester, pool=shift.pool),
            )
            for shift in shifts
        ]
        for shifts in type_shifts
    ]

    return render_to_response("list_types.html", {
        "page_name": page_name,
        "type_tuples": zip(types, shift_edits),
        "can_edit": any_management,
    }, context_instance=RequestContext(request))
1224888
def copy(self):
        
        out = type(self)()
        for series in self:
            out.append(series.copy())
        return out
501071
def edit_shift_view(request, semester, pk, profile=None):
    
    shift = get_object_or_404(RegularWorkshift, pk=pk)

    if shift.is_manager_shift:
        # XXX: Bad way of doing this, we should make manager_shift point to
        # the related Manager object directly
        try:
            manager = Manager.objects.get(title=shift.workshift_type.title)
        except Manager.DoesNotExist:
            pass
        else:
            return HttpResponseRedirect(manager.get_edit_url())

    if not utils.can_manage(request.user, semester=semester, pool=shift.pool):
        messages.add_message(
            request,
            messages.ERROR,
            MESSAGES["ADMINS_ONLY"],
        )
        return HttpResponseRedirect(semester.get_view_url())

    edit_form = RegularWorkshiftForm(
        data=request.POST if "edit" in request.POST else None,
        instance=shift,
        semester=semester,
    )

    if "delete" in request.POST:
        # Open instances are deleted automatically
        shift.delete()
        return HttpResponseRedirect(wurl(
            "workshift:manage",
            sem_url=semester.sem_url,
        ))
    elif edit_form.is_valid():
        shift = edit_form.save()
        return HttpResponseRedirect(shift.get_view_url())

    page_name = "Edit {}".format(shift)

    return render_to_response("edit_shift.html", {
        "page_name": page_name,
        "shift": shift,
        "edit_form": edit_form,
    }, context_instance=RequestContext(request))
448221
private PiggyBack existingPiggyBackForInserting() {
    Object _misc = misc;
    if (_misc instanceof SimpleTimerTask) {
      return new TaskPiggyBack((SimpleTimerTask) _misc, null);
    }
    return (PiggyBack) _misc;
  }
887395
def copy(self):
        """"""
        if self.has_selected_text():
            ConsoleBaseWidget.copy(self)
        elif not sys.platform == 'darwin':
            self.interrupt()
594451
private void updateWork(Task parentTask)
   {
      if (parentTask.hasChildTasks())
      {
         ProjectProperties properties = m_project.getProjectProperties();

         Duration actualWork = null;
         Duration baselineWork = null;
         Duration remainingWork = null;
         Duration work = null;

         for (Task task : parentTask.getChildTasks())
         {
            updateWork(task);

            actualWork = Duration.add(actualWork, task.getActualWork(), properties);
            baselineWork = Duration.add(baselineWork, task.getBaselineWork(), properties);
            remainingWork = Duration.add(remainingWork, task.getRemainingWork(), properties);
            work = Duration.add(work, task.getWork(), properties);
         }

         parentTask.setActualWork(actualWork);
         parentTask.setBaselineWork(baselineWork);
         parentTask.setRemainingWork(remainingWork);
         parentTask.setWork(work);
      }
   }