问:
How would I use the `...` C operator to get a function to print out all it's args?
Here's what I tried... but failed:</p>

```<code>void testfunc(...){
    printf(...);
}
</code>```

答:
You can use the va_start() and va_end() macros, but you'll have to have at least one argument:

```<code>void testfunc(int n, ...)
{
    va_list vl;
    va_start(vl, n); // initialize the va_list
    // something useful
    va_end(vl); // deinitializes vl
}
</code>```

You can sequentially access the arguments with va_arg(vl, type) (e.g. int x = va_arg(vl, int)). Also, va_copy is occasionally useful if you want to copy the current state of the va_list

Body:
Here's what I tried... but failed:

void testfunc(...){
    printf(...);
}

Body:
You can use the va_start() and va_end() macros, but you'll have to have at least one argument:

void testfunc(int n, ...)
{
    va_list vl;
    va_start(vl, n); // initialize the va_list
    // something useful
    va_end(vl); // deinitializes vl
}

You can sequentially access the arguments with va_arg(vl, type) (e.g. int x = va_arg(vl, int)). Also, va_copy is occasionally useful if you want to copy the current state of the va_list


来源: stackexchange

问:
It is possible to delete components (pipe - ect) from Angular CLI
For example if I use the following:

```<code>ng g c my-new-component:
</code>```

add a component in application

He creates the files, the routes and all the history, Angular CLI is very cool. But if at some point I want to delete a component, I have to delete everything by hand and edit the files ect.

I thought maybe using r or remove this would work, but it is not so:

```<code> ng r c my-new-component:
</code>```

The specified command r is invalid. For available options, see ng help.

I have looked at the github but I have not seen anything.

I am sorry for my bad english.

My question is if this is possible, if that's how I can do it?

答:
Its not possible currently.

We can track this issue: https://github.com/angular/angular-cli/issues/900

ContentLicense: CC BY-SA 3.0

Body:
For example if I use the following:

ng g c my-new-component:

add a component in application

He creates the files, the routes and all the history, Angular CLI is very cool. But if at some point I want to delete a component, I have to delete everything by hand and edit the files ect.

I thought maybe using r or remove this would work, but it is not so:

 ng r c my-new-component:

The specified command r is invalid. For available options, see ng help.

I have looked at the github but I have not seen anything.

I am sorry for my bad english.

My question is if this is possible, if that's how I can do it?


问:
Django - user restriction from getting access to same value
I have a calendar which is suppose to be connected to the current admins-association. Admin picks a date in the calendar and register the form so that event is set. But when i log in with another admins-association, i still can see the event from the last admin:

I want to keep them separately from each other.

These data seems correct to me as no other admins who does not have the same association_id will see the event.

Still a newbie so guide me in the right way and appreciate all your help, folks!

models.py

```<code>class Administrator(AbstractUser):
        # inherits the standard User-model
        ...
        association = models.ForeignKey(Association)

class Event(models.Model):
      name = models.CharField(max_length=50)
      location = models.CharField(max_length=100)
      start = models.DateTimeField(blank=False)
      end = models.DateTimeField(blank=False)
      allday = models.BooleanField()
      description = models.TextField(max_length=200)
      synced = models.BooleanField(default=False)
      gid = models.CharField(default='', max_length=100)
      association = models.ForeignKey(Association)

class Association(models.Model):
        asoc_name = models.CharField(max_length=50, null=True, blank=True)
</code>```

views.py

```<code>class calendar(ListView):

   template_name = 'calapp/calendar.html'

   def get_queryset(self):
       queryset =  Event.objects.filter(association=self.request.user.association)
       return queryset

def event_add_edit(request):
   if request.method == 'POST':
       res = {'success': False}

       action = request.POST['action']
       name = request.POST['name']
       location = request.POST['location']
       start = request.POST['start']
       end = request.POST['end']
       allday = request.POST['allday'] == 'true'
       description = request.POST['description']
       synced = request.POST['synced'] == 'true'
       association = Association.objects.filter(asoc_name=request.user.association)
       asoc = Association.objects.get(id=association)

       if action == 'add':
           Event.objects.create(
              name=name,
              location=location,
              start=start,
              end=end,
              allday=allday,
              description=description,
              synced=synced,
              association=asoc
           )

           res['success'] = True
           res['message'] = 'added'
           eid = Event.objects.latest('id').id
           res['eid'] = eid
           res['data'] = Event.objects.values().get(id=eid)
       elif action == 'edit':

           eid = request.POST['eid']
           event = Event.objects.get(id=eid)
           event.name = name
           event.location = location
           event.start = start
           event.end = end
           event.allday = allday
           event.description = description
           event.synced = synced
           event.save()

           res['success'] = True
           res['message'] = 'edited'
           res['eid'] = eid
           res['data'] = Event.objects.values().get(id=eid)

       return JsonResponse(res)
   else:
       raise Http404

def event_get(request, start, end):
   res = {'success': False}
   try:
       datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%fZ')
       datetime.strptime(end, '%Y-%m-%dT%H:%M:%S.%fZ')
   except ValueError:
       res['message'] = \
           'Invalid params: ISO format start end dates expected'
       return JsonResponse(res)
   result = Event.objects.filter(start__range=(start,
                                            end)).order_by('start').values()

   res['data'] = list(result)
   res['success'] = True
   return JsonResponse(res)
</code>```

urls.py

```<code>urlpatterns = [
url(r'^calendar/event/get/(?P<start>.+)/(?P<end>.+)/', views.event_get),
url(r'^calendar/event/addedit/', views.event_add_edit),
url(r'^calendar/', views.calendar.as_view(), name='calendar'),
</code>```

]

calendar.js (parts of it)

This display the values in the picture of calendar above, i suspect this may be the issue of not getting filtered according to the current user.

```<code>    //generate event li
getEventli: function (event) {
    var $li = $("<li class='event-li'>");

    var $ename = $("<span class='event-li-name'>");
    $ename.text(event.name);

    $li.append($ename);

    var $etime = $("<span class='event-li-time'>");
    var start = new Date(event.start),
        h = cal.getHourStr(start.getHours());

    $etime.text(h);
    $li.append($etime);

    // add data-eid attribute for detail show
    $li.data("eid", event.id);
    $li.click(cal.showDetailForm);

    cal.eventsById[event.id].eventli.push($li);

    return $li;
}
</code>```

calendar.html

```<code><div id="cal-content">
        <div id="cal-content-top">
            <span id="cal-content-top-month">
                <span class="btn-fa" id="cal-content-month-up">
                    <i class="fa fa-chevron-up"></i>
                </span>
            <span class="btn-fa" id="cal-content-month-dn">
                    <i class="fa fa-chevron-down"></i>
                </span>
            <span class="month-long">November</span>
            <span class="year">2015</span>
            </span>
            <span id="cal-content-top-icon">
                <span class="btn-fa" id="btn-sync" id="icon-sync">
                    <i class="fa fa-refresh"></i>
                </span>

        <div id="cal-content-grid">
            <div id="week-days">
                <ul>
                    <li class="week-day">Sunday</li>
                    <li class="week-day">Monday</li>
                    <li class="week-day selected">Tuesday</li>
                    <li class="week-day">Wednesday</li>
                    <li class="week-day">Thursday</li>
                    <li class="week-day">Friday</li>
                    <li class="week-day">Saturday</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell disabled">1</li>
                    <li class="week-row-cell disabled">2</li>
                    <li class="week-row-cell disabled">3</li>
                    <li class="week-row-cell disabled">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell selected">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
            <div class="week-row last">
                <ul>
                    <li class="week-row-cell">1</li>
                    <li class="week-row-cell">2</li>
                    <li class="week-row-cell">3</li>
                    <li class="week-row-cell">4</li>
                    <li class="week-row-cell">5</li>
                    <li class="week-row-cell">6</li>
                    <li class="week-row-cell last">7</li>
                </ul>
            </div>
        </div>
    </div>
</div>
</code>```

calendar.js (most codes that may be for help)

```<code>// object to manage calendar

var cal = {
   //today's date
   currDate: new Date(),
   //current calendar grid month date
   gridDate: new Date(),
   //stores event with event.id as key
   eventsById: {},
   //stores current month day-cells
   dayCells: [],
   $weekdays: $("#week-days li.week-day"),
   $monthLong: $(".month-long"),
   $year: $(".year"),
   $calThumb: $("#cal-thumb-content-grid"),
   $calContentGrid: $("#cal-content-grid"),
   $monthup: $("#cal-content-month-up"),
   $monthdn: $("#cal-content-month-dn"),

   //select cuurent date week

   selectWeekDay: function () {
       cal.$weekdays
           .removeClass("selected");
       cal.$weekdays
           .eq(cal.currDate.getDay())
           .addClass("selected");
   },

   // generate the calendar grid and thumb

   render: function () {
       //update grid month name and year
       cal.$monthLong
               .html(cal.gridDate.toLocaleDateString("en-us", {
               month: "long"
           }));
       cal.$year.html(cal.gridDate.getFullYear());

       //remove previous days from grid and thumb grid

       cal.dayCells = [];
       $(".week-row").remove();
       $(".thumb-week-row").remove();

       //shift date to first cell date

       var date = new Date(cal.gridDate.getFullYear(), cal.gridDate.getMonth(), 1);
       date.shiftDay(-date.getDay());

       for (var r = 1; r <= 6; ++r) {
           var $weekrow = $("<div class='week-row'><ul></ul></div>"),
               $weekrowul = $weekrow.find("ul:first");

           var $thumbweekrow = $("<div class='thumb-week-row'><ul></ul></div>"),
               $thumbweekrowul = $thumbweekrow.find("ul:first");

           for (var c = 1; c <= 7; ++c) {
               var cls = "week-row-cell",
                   thumbcls = "";
               if (date.getMonth() != cal.gridDate.getMonth()) {
                   cls += " disabled";
                   thumbcls += "disabled";
               }

               if (c == 7) {
                   cls += " last";
               }

               if (date.toDateString() == cal.currDate.toDateString()) {
                   cls += " selected";
                   thumbcls += " selected";
               }
               // append to thumb cal and cal grid
               $thumbweekrowul.append(cal.getThumbWeekCell(date.getDate(), thumbcls));
               var $dayCell = cal.getWeekCell(date, cls);
               $weekrowul.append($dayCell);

               if (date.getMonth() == cal.gridDate.getMonth())
                   cal.dayCells.push($dayCell);

               // date.shiftDay(1);
               date.shiftDay(1);
           }

           if (r == 6) {
               $weekrow.addClass("last");
           }

           cal.$calContentGrid.append($weekrow);
           cal.$calThumb.append($thumbweekrow);
       }

       cal.getMonthEvents();
  },

   //generate cell li of week row of calendar grid

   getWeekCell: function (date, cls) {
       var $li = $("<li>", {
           class: cls
       });

    var $litop = $("<div class='cell-top'>");

    var $dayno = $("<span class='cell-dayno'>");
    $dayno.text(date.getDate());
    $litop.append($dayno);

    var $weather = $("<span class='cell-weather'>");
    $litop.append($weather);

    var $addevent = $("<span class='btn-fa btn-add'>");
    $addevent.data("date", date.toISOString());
    $addevent.html("<i class='fa fa-calendar-plus-o'></i>");
    $addevent.click(cal.showAddForm);

    $litop.append($addevent);

    $li.append($litop);

    var $celllist = $("<div class='cell-list'><ul></ul></div>");
    $li.append($celllist);

    return $li;
},

//generate cell li of thumb calendar

getThumbWeekCell: function (dayno, cls) {
    var $li = $("<li>", {
        class: cls
    });
    $li.html(dayno);
    return $li;
},

// get current month events form db

getMonthEvents: function () {
    var start = new Date(cal.gridDate.getTime());
    start.setDate(1);
    var end = new Date(start.getTime());
    end.shiftMonth(1);

    cal.getEvents(start, end, function (response) {
        if (response.success) {
            response.data.forEach(function (event) {
                //console.log(event);
                cal.addEventLi(event);
            });

            sync.syncEvents();
        }
    })
},

// gets events with start date within [start,end)

getEvents: function (start, end, callback) {
    if (callback === undefined)
        return;

    var url = "/calendar/event/get/";
    url += start.toISOString() + "/";
    url += end.toISOString() + "/";
    console.log(url);

    $.get({
        url: url,
        success: function (response) {
            callback(response);
        }
    })
},

//generate event li

getEventli: function (event) {
    var $li = $("<li class='event-li'>");

    var $ename = $("<span class='event-li-name'>");
    $ename.text(event.name);

    $li.append($ename);

    var $etime = $("<span class='event-li-time'>");
    var start = new Date(event.start),
        h = cal.getHourStr(start.getHours());

    $etime.text(h);
    $li.append($etime);

    // add data-eid attribute for detail show
    $li.data("eid", event.id);
    $li.click(cal.showDetailForm);

    cal.eventsById[event.id].eventli.push($li);

    return $li;
},

//get events to fill today ul

getTodayEvents: function () {
    var start = new Date(cal.currDate.getTime());
    var end = new Date(start.getTime());
    end.shiftHour(5);

    var $lis={};
    var $ul = cal.$todayEvents.find("ul:first");
    $ul.children().remove();
    for (var x = new Date(start.getTime()), i = 0; i < 5; ++i) {
        var h=x.getHours(),
            hstr = cal.getHourStr(h),
            $li = $("<li>" + hstr + "</li>");

        $ul.append($li);
        $lis[h] = $li;

        x.shiftHour(1);
    }

    cal.getEvents(start, end, function (response) {
        if (response.success) {
            console.log("today events", response);
            response.data.forEach(function(event){
                var h = new Date(event.start).getHours();
                $lis[h].append(" - "+event.name);
            })
        }
    });
},

//go to previous month

prevMonth: function () {
    cal.gridDate.shiftMonth(-1);
    cal.render();
},

//go to next month

nextMonth: function () {
    cal.gridDate.shiftMonth(1);
    cal.render();
},

$formwrappers: $(".form-wrapper"),
$formclose: $(".form-close"),

$addEventForm: $("#add-event-form"),
$addEventAction: $("#add-event-action"),
$addEventEid: $("#add-event-eid"),
$addEventSynced: $("#add-event-synced"),
$addEventTop: $("#add-event-top"),
$addEventName: $("#add-event-name"),
$addEventLocation: $("#add-event-location"),
$addEventSdate: $("#add-event-sdate"),
$addEventStime: $("#add-event-stime"),
$addEventEdate: $("#add-event-edate"),
$addEventEtime: $("#add-event-etime"),
$addEventAllday: $("#add-event-allday"),
$addEventDesc: $("#add-event-desc"),

$detailEventForm: $("#detail-event-form"),
$detailEventName: $("#detail-event-name"),
$detailEventLocation: $("#detail-event-location"),
$detailEventDate: $("#detail-event-date"),
$detailEventDescription: $("#detail-event-desc"),
$btnEdit: $("#btn-edit"),
$btnDelete: $("#btn-delete"),

//to show add event form

showAddForm: function () {
    cal.$addEventAction.val("add");
    cal.$addEventSynced.val("false");

    //init inputs

    cal.$addEventName.val("");
    cal.$addEventLocation.val("");
    cal.$addEventAllday[0].checked = false;
    cal.$addEventDesc.val("");
    var date = new Date($(this).data("date"));
    cal.$addEventTop.text(date.toDateString());

    date.setHours(cal.currDate.getHours());
    date.setMinutes(cal.currDate.getMinutes());

    cal.$addEventSdate.val(date.toDateInput());
    cal.$addEventStime.val(date.toTimeInput());
    date.shiftHour(1);
    cal.$addEventEdate.val(date.toDateInput());
    cal.$addEventEtime.val(date.toTimeInput());

    cal.$addEventForm.addClass("visible");
},

//to show details form

showDetailForm: function () {
    var eid = $(this).data("eid"),
        event = cal.eventsById[eid];

    cal.$detailEventName.text(event.name);
    cal.$detailEventLocation.text(event.location);

    var date = new Date(event.start),
        datestr = date.toTimeInput() + ", " + date.toDateString();
    cal.$detailEventDate.text(datestr);

    cal.$detailEventDescription.text(event.description);
    cal.$btnEdit.data("eid", event.id);
    cal.$btnDelete.data("eid", event.id);

    cal.$detailEventForm.addClass("visible");
},

//add event li

addEventLi: function (event) {
    cal.syncedGids[event.gid] = event.id;
    cal.eventsById[event.id] = event;
    cal.eventsById[event.id].eventli = [];

    var start = new Date(event.start),
        end = new Date(event.end);

    if (event.allday) {
        end.shiftDay(-1);
    }

    for (var d = start.getDate(); d <= end.getDate(); ++d) {
        cal.dayCells[d - 1]
            .find("ul:first")
            .append(cal.getEventli(event));
    }
},
</code>```

答:
Maybe I do not understand what you want. But I'll advise you about your code.

request.user.association is asoc.

```<code># before ---------
association = Association.objects.filter(asoc_name=request.user.association)
asoc = Association.objects.get(id=association)

# after -----------
asoc = request.user.association
</code>```

Event.objects.create return Event object.

```<code># before -------
Event.objects.create(
# omit
)
# omit
eid = Event.objects.latest('id').id
res['eid'] = eid
res['data'] = Event.objects.values().get(id=eid)

# after -------
event = Event.objects.create(
# omit
)
# omit
res['eid'] = event.id
res['data'] = event
</code>```

UPDATE

you should change event_get view as follows

```<code>def event_get(request, start, end):
   res = {'success': False}
   try:
       datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%fZ')
       datetime.strptime(end, '%Y-%m-%dT%H:%M:%S.%fZ')
   except ValueError:
       res['message'] = \
           'Invalid params: ISO format start end dates expected'
       return JsonResponse(res)

   result = Event.objects.filter(
        association=request.user.association,  # Add filter
        start__range=(start, end)
   ).order_by('start').values()

   res['data'] = list(result)
   res['success'] = True
   return JsonResponse(res)
</code>```

Also, you should protect this view with login_required.
https://docs.djangoproject.com/en/1.10/topics/auth/default/#the-login-required-decorator

Body:
I have a calendar which is suppose to be connected to the current admins-association. Admin picks a date in the calendar and register the form so that event is set. But when i log in with another admins-association, i still can see the event from the last admin:

I want to keep them separately from each other.

These data seems correct to me as no other admins who does not have the same association_id will see the event.

Still a newbie so guide me in the right way and appreciate all your help, folks!

models.py

class Administrator(AbstractUser):
        # inherits the standard User-model
        ...
        association = models.ForeignKey(Association)

class Event(models.Model):
      name = models.CharField(max_length=50)
      location = models.CharField(max_length=100)
      start = models.DateTimeField(blank=False)
      end = models.DateTimeField(blank=False)
      allday = models.BooleanField()
      description = models.TextField(max_length=200)
      synced = models.BooleanField(default=False)
      gid = models.CharField(default='', max_length=100)
      association = models.ForeignKey(Association)

class Association(models.Model):
        asoc_name = models.CharField(max_length=50, null=True, blank=True)

views.py

class calendar(ListView):

   template_name = 'calapp/calendar.html'

   def get_queryset(self):
       queryset =  Event.objects.filter(association=self.request.user.association)
       return queryset

def event_add_edit(request):
   if request.method == 'POST':
       res = {'success': False}

       action = request.POST['action']
       name = request.POST['name']
       location = request.POST['location']
       start = request.POST['start']
       end = request.POST['end']
       allday = request.POST['allday'] == 'true'
       description = request.POST['description']
       synced = request.POST['synced'] == 'true'
       association = Association.objects.filter(asoc_name=request.user.association)
       asoc = Association.objects.get(id=association)

       if action == 'add':
           Event.objects.create(
              name=name,
              location=location,
              start=start,
              end=end,
              allday=allday,
              description=description,
              synced=synced,
              association=asoc
           )

           res['success'] = True
           res['message'] = 'added'
           eid = Event.objects.latest('id').id
           res['eid'] = eid
           res['data'] = Event.objects.values().get(id=eid)
       elif action == 'edit':

           eid = request.POST['eid']
           event = Event.objects.get(id=eid)
           event.name = name
           event.location = location
           event.start = start
           event.end = end
           event.allday = allday
           event.description = description
           event.synced = synced
           event.save()

           res['success'] = True
           res['message'] = 'edited'
           res['eid'] = eid
           res['data'] = Event.objects.values().get(id=eid)

       return JsonResponse(res)
   else:
       raise Http404

def event_get(request, start, end):
   res = {'success': False}
   try:
       datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%fZ')
       datetime.strptime(end, '%Y-%m-%dT%H:%M:%S.%fZ')
   except ValueError:
       res['message'] = \
           'Invalid params: ISO format start end dates expected'
       return JsonResponse(res)
   result = Event.objects.filter(start__range=(start,
                                            end)).order_by('start').values()

   res['data'] = list(result)
   res['success'] = True
   return JsonResponse(res)

urls.py

urlpatterns = [
url(r'^calendar/event/get/(?P<start>.+)/(?P<end>.+)/', views.event_get),
url(r'^calendar/event/addedit/', views.event_add_edit),
url(r'^calendar/', views.calendar.as_view(), name='calendar'),

]

calendar.js (parts of it)

This display the values in the picture of calendar above, i suspect this may be the issue of not getting filtered according to the current user.

    //generate event li
getEventli: function (event) {
    var $li = $("
");

    var $ename = $("");
    $ename.text(event.name);

    $li.append($ename);

    var $etime = $("");
    var start = new Date(event.start),
        h = cal.getHourStr(start.getHours());

    $etime.text(h);
    $li.append($etime);

    // add data-eid attribute for detail show
    $li.data("eid", event.id);
    $li.click(cal.showDetailForm);

    cal.eventsById[event.id].eventli.push($li);

    return $li;
}

calendar.html

            November
            2015

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

1

2

3

4

5

6

7

1

2

3

4

5

6

7

1

2

3

4

5

6

7

1

2

3

4

5

6

7

1

2

3

4

5

6

7

1

2

3

4

5

6

7

calendar.js (most codes that may be for help)

// object to manage calendar

var cal = {
   //today's date
   currDate: new Date(),
   //current calendar grid month date
   gridDate: new Date(),
   //stores event with event.id as key
   eventsById: {},
   //stores current month day-cells
   dayCells: [],
   $weekdays: $("#week-days li.week-day"),
   $monthLong: $(".month-long"),
   $year: $(".year"),
   $calThumb: $("#cal-thumb-content-grid"),
   $calContentGrid: $("#cal-content-grid"),
   $monthup: $("#cal-content-month-up"),
   $monthdn: $("#cal-content-month-dn"),

   //select cuurent date week

   selectWeekDay: function () {
       cal.$weekdays
           .removeClass("selected");
       cal.$weekdays
           .eq(cal.currDate.getDay())
           .addClass("selected");
   },

   // generate the calendar grid and thumb

   render: function () {
       //update grid month name and year
       cal.$monthLong
               .html(cal.gridDate.toLocaleDateString("en-us", {
               month: "long"
           }));
       cal.$year.html(cal.gridDate.getFullYear());

       //remove previous days from grid and thumb grid

       cal.dayCells = [];
       $(".week-row").remove();
       $(".thumb-week-row").remove();

       //shift date to first cell date

       var date = new Date(cal.gridDate.getFullYear(), cal.gridDate.getMonth(), 1);
       date.shiftDay(-date.getDay());

       for (var r = 1; r <= 6; ++r) {
           var $weekrow = $("

"),
               $weekrowul = $weekrow.find("ul:first");

           var $thumbweekrow = $("

"),
               $thumbweekrowul = $thumbweekrow.find("ul:first");

           for (var c = 1; c <= 7; ++c) {
               var cls = "week-row-cell",
                   thumbcls = "";
               if (date.getMonth() != cal.gridDate.getMonth()) {
                   cls += " disabled";
                   thumbcls += "disabled";
               }

               if (c == 7) {
                   cls += " last";
               }

               if (date.toDateString() == cal.currDate.toDateString()) {
                   cls += " selected";
                   thumbcls += " selected";
               }
               // append to thumb cal and cal grid
               $thumbweekrowul.append(cal.getThumbWeekCell(date.getDate(), thumbcls));
               var $dayCell = cal.getWeekCell(date, cls);
               $weekrowul.append($dayCell);

               if (date.getMonth() == cal.gridDate.getMonth())
                   cal.dayCells.push($dayCell);

               // date.shiftDay(1);
               date.shiftDay(1);
           }

           if (r == 6) {
               $weekrow.addClass("last");
           }

           cal.$calContentGrid.append($weekrow);
           cal.$calThumb.append($thumbweekrow);
       }

       cal.getMonthEvents();
  },

   //generate cell li of week row of calendar grid

   getWeekCell: function (date, cls) {
       var $li = $("
", {
           class: cls
       });

    var $litop = $("
");

    var $dayno = $("");
    $dayno.text(date.getDate());
    $litop.append($dayno);

    var $weather = $("");
    $litop.append($weather);

    var $addevent = $("");
    $addevent.data("date", date.toISOString());
    $addevent.html("");
    $addevent.click(cal.showAddForm);

    $litop.append($addevent);

    $li.append($litop);

    var $celllist = $("

");
    $li.append($celllist);

    return $li;
},

//generate cell li of thumb calendar

getThumbWeekCell: function (dayno, cls) {
    var $li = $("
", {
        class: cls
    });
    $li.html(dayno);
    return $li;
},

// get current month events form db

getMonthEvents: function () {
    var start = new Date(cal.gridDate.getTime());
    start.setDate(1);
    var end = new Date(start.getTime());
    end.shiftMonth(1);

    cal.getEvents(start, end, function (response) {
        if (response.success) {
            response.data.forEach(function (event) {
                //console.log(event);
                cal.addEventLi(event);
            });

            sync.syncEvents();
        }
    })
},

// gets events with start date within [start,end)

getEvents: function (start, end, callback) {
    if (callback === undefined)
        return;

    var url = "/calendar/event/get/";
    url += start.toISOString() + "/";
    url += end.toISOString() + "/";
    console.log(url);

    $.get({
        url: url,
        success: function (response) {
            callback(response);
        }
    })
},

//generate event li

getEventli: function (event) {
    var $li = $("
");

    var $ename = $("");
    $ename.text(event.name);

    $li.append($ename);

    var $etime = $("");
    var start = new Date(event.start),
        h = cal.getHourStr(start.getHours());

    $etime.text(h);
    $li.append($etime);

    // add data-eid attribute for detail show
    $li.data("eid", event.id);
    $li.click(cal.showDetailForm);

    cal.eventsById[event.id].eventli.push($li);

    return $li;
},

//get events to fill today ul

getTodayEvents: function () {
    var start = new Date(cal.currDate.getTime());
    var end = new Date(start.getTime());
    end.shiftHour(5);

    var $lis={};
    var $ul = cal.$todayEvents.find("ul:first");
    $ul.children().remove();
    for (var x = new Date(start.getTime()), i = 0; i < 5; ++i) {
        var h=x.getHours(),
            hstr = cal.getHourStr(h),
            $li = $("
" + hstr + "
");

        $ul.append($li);
        $lis[h] = $li;

        x.shiftHour(1);
    }

    cal.getEvents(start, end, function (response) {
        if (response.success) {
            console.log("today events", response);
            response.data.forEach(function(event){
                var h = new Date(event.start).getHours();
                $lis[h].append(" - "+event.name);
            })
        }
    });
},

//go to previous month

prevMonth: function () {
    cal.gridDate.shiftMonth(-1);
    cal.render();
},

//go to next month

nextMonth: function () {
    cal.gridDate.shiftMonth(1);
    cal.render();
},

$formwrappers: $(".form-wrapper"),
$formclose: $(".form-close"),

$addEventForm: $("#add-event-form"),
$addEventAction: $("#add-event-action"),
$addEventEid: $("#add-event-eid"),
$addEventSynced: $("#add-event-synced"),
$addEventTop: $("#add-event-top"),
$addEventName: $("#add-event-name"),
$addEventLocation: $("#add-event-location"),
$addEventSdate: $("#add-event-sdate"),
$addEventStime: $("#add-event-stime"),
$addEventEdate: $("#add-event-edate"),
$addEventEtime: $("#add-event-etime"),
$addEventAllday: $("#add-event-allday"),
$addEventDesc: $("#add-event-desc"),

$detailEventForm: $("#detail-event-form"),
$detailEventName: $("#detail-event-name"),
$detailEventLocation: $("#detail-event-location"),
$detailEventDate: $("#detail-event-date"),
$detailEventDescription: $("#detail-event-desc"),
$btnEdit: $("#btn-edit"),
$btnDelete: $("#btn-delete"),

//to show add event form

showAddForm: function () {
    cal.$addEventAction.val("add");
    cal.$addEventSynced.val("false");

    //init inputs

    cal.$addEventName.val("");
    cal.$addEventLocation.val("");
    cal.$addEventAllday[0].checked = false;
    cal.$addEventDesc.val("");
    var date = new Date($(this).data("date"));
    cal.$addEventTop.text(date.toDateString());

    date.setHours(cal.currDate.getHours());
    date.setMinutes(cal.currDate.getMinutes());

    cal.$addEventSdate.val(date.toDateInput());
    cal.$addEventStime.val(date.toTimeInput());
    date.shiftHour(1);
    cal.$addEventEdate.val(date.toDateInput());
    cal.$addEventEtime.val(date.toTimeInput());

    cal.$addEventForm.addClass("visible");
},

//to show details form

showDetailForm: function () {
    var eid = $(this).data("eid"),
        event = cal.eventsById[eid];

    cal.$detailEventName.text(event.name);
    cal.$detailEventLocation.text(event.location);

    var date = new Date(event.start),
        datestr = date.toTimeInput() + ", " + date.toDateString();
    cal.$detailEventDate.text(datestr);

    cal.$detailEventDescription.text(event.description);
    cal.$btnEdit.data("eid", event.id);
    cal.$btnDelete.data("eid", event.id);

    cal.$detailEventForm.addClass("visible");
},

//add event li

addEventLi: function (event) {
    cal.syncedGids[event.gid] = event.id;
    cal.eventsById[event.id] = event;
    cal.eventsById[event.id].eventli = [];

    var start = new Date(event.start),
        end = new Date(event.end);

    if (event.allday) {
        end.shiftDay(-1);
    }

    for (var d = start.getDate(); d <= end.getDate(); ++d) {
        cal.dayCells[d - 1]
            .find("ul:first")
            .append(cal.getEventli(event));
    }
},

Body:
Maybe I do not understand what you want. But I'll advise you about your code.

request.user.association is asoc.

# before ---------
association = Association.objects.filter(asoc_name=request.user.association)
asoc = Association.objects.get(id=association)

# after -----------
asoc = request.user.association

Event.objects.create return Event object.

# before -------
Event.objects.create(
# omit
)
# omit
eid = Event.objects.latest('id').id
res['eid'] = eid
res['data'] = Event.objects.values().get(id=eid)

# after -------
event = Event.objects.create(
# omit
)
# omit
res['eid'] = event.id
res['data'] = event

UPDATE

you should change event_get view as follows

def event_get(request, start, end):
   res = {'success': False}
   try:
       datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%fZ')
       datetime.strptime(end, '%Y-%m-%dT%H:%M:%S.%fZ')
   except ValueError:
       res['message'] = \
           'Invalid params: ISO format start end dates expected'
       return JsonResponse(res)

   result = Event.objects.filter(
        association=request.user.association,  # Add filter
        start__range=(start, end)
   ).order_by('start').values()

   res['data'] = list(result)
   res['success'] = True
   return JsonResponse(res)

Also, you should protect this view with login_required.
https://docs.djangoproject.com/en/1.10/topics/auth/default/#the-login-required-decorator


问:
Check if image source is equal to an image
My current code exists as:

```<code><img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
    function pictureChange(){
        if(fixedScreenimg.src == "img/homeScreen.png"){
            document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg");
        }else{
            document.getElementByID("fixedScreenimg").src="img/homeScreen.png");
        }
    }
</script>
</code>```

As  you can see, I'm attempting to check whether the image source of an element matches a given path to an image, and if so, change the result of the image changing when a button is pressed. However, this doesn't seem to work.

I've attempted to use getAttribute and the like.

Any pointers?

Thanks.

答:
You added a bracket at the end of your lines</p>

```<code>document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg";
</code>```

Body:
My current code exists as:

As  you can see, I'm attempting to check whether the image source of an element matches a given path to an image, and if so, change the result of the image changing when a button is pressed. However, this doesn't seem to work.

I've attempted to use getAttribute and the like.

Any pointers?

Thanks.

Body:
You added a bracket at the end of your lines

document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg";


答:
You actually are adding a closing bracket )

Try the following:

```<code> function pictureChange(){

    var elem = document.getElementById("fixedScreenimg");

    if(elem.src === "img/homeScreen.png"){
        elem.src="img/fixedScreen.jpg";
    }else{
        elem.src="img/homeScreen.png";
    }
}
</code>```

Title: Check if image source is equal to an image

Body:
You actually are adding a closing bracket )

Try the following:

 function pictureChange(){

    var elem = document.getElementById("fixedScreenimg");

    if(elem.src === "img/homeScreen.png"){
        elem.src="img/fixedScreen.jpg";
    }else{
        elem.src="img/homeScreen.png";
    }
}


问:
How to empty a SQL database?
I'm searching for a simple way to delete all data from a database and keep the structure (table, relationship, etc...).
I using postgreSQL but I think, if there a command to do that, it's not specific to postgres.

Thanks,

Damien

答:
In pgAdmin you can do:

Right-click database -> backup, select "Schema only"

Drop the database

Create a new database and name it like the former

Right-click the new database -> restore -> select the backup, select "Schema only"

ContentLicense: CC BY-SA 2.5

Title: How to empty a SQL database?


问:
best CMS for a custom and new employees?
we're moving to use an OPENSOURCE CMS system, for years we been using our own CMS, and it's time to move to OPENSOURCE. so which of Drupal, Joomla, WordPress is the best choice if

the team needs to learn it ...

supporting multi languages and RTL directions

easy to use ( for end users )

customization and templating

or if there are any other CMS that would make the process faster.

thanks all

答:
I've used all 3, and they all have different advantages. It would help to know what exactly you're doing, but here are some vague generalities:

Wordpress is very focused on the task of blogging, so visual design and usability tend to be much better. Joomla has more resale-friendly licensing, so there's more money to be made in that business model. Drupal is more of a generic framework, so good for heavy customization.

Ease of learning really depends on what you're doing with it. Drupal is more complex to learn, but can do a lot. Wordpress is easiest, but is still very focused on blogs. So if you're primarily doing blogs, go with Wordpress. If you're doing more, consider Drupal.

They all support multiple languages and RTL, so that's not a big difference.

This is pretty much the same as #1. Wordpress wins at what it does, but if that's not what you're doing, it's irrelevant.

4a. I think Drupal wins hands-down for customization. Drupal's the only system that allows you to heavily alter what others have created without managing their codebase. For example, Drupal creates all forms as arrays and exposes them to any code to modify after they're created. Both Wordpress and Joomla create forms as straight HTML, so you can only alter it by altering the code that creates it, which quickly turns into a maintenance headache.

4b. I think Wordpress wins for templating. It has a clean division between code and design, which Drupal lacks, and some established standards for markup, which Joomla lacks.

As you can see, Joomla doesn't win at all here, so I wouldn't suggest it. I'm guessing your needs are more complex than what Wordpress does well, but that's just a guess. Based on that guess, I'd suggest Drupal.


问:
laravel echo server , redis
i have a problem with remote connections.

my vhost is : redis.test

i added this on blade file:

```<code><script src="//redis.test:6001/socket.io/socket.io.js"></script>
</code>```

.env file

```<code>BROADCAST_DRIVER=redis
REDIS_HOST=redis.test
REDIS_PASSWORD=null
REDIS_PORT=6379
</code>```

echo configuration

```<code>import Echo from "laravel-echo"

window.Echo = new Echo({
   broadcaster: 'socket.io',
   host: 'http://redis.test:6001'
});
</code>```

laravel-exho-server.json

```<code>{
    "authHost": "http://redis.test",
    "authEndpoint": "/broadcasting/auth",
    "clients": [
        {
            "appId": "f27485125ac2627f",
            "key": "6328e672f42cbf4cba1de3da215ec41a"
        }
    ],
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "redis.test"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "redis.test",
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}
</code>```

it works when i try to broadcast with a local connection (2 browsers - same pc), but when i try to send a "message" from other pc on lan network (192.168.1.50) i have this error

```<code>GET: http://redis.test:6001/socket.io/socket.io.js net::err_connection_refused

[vue_warn] error in created hook
</code>```

how ca i resolve this?

答: It may be a firewall issue as I can see, try to open redis port in the firewall</p>

Title: laravel echo server , redis

Body:
i have a problem with remote connections.

my vhost is : redis.test

i added this on blade file:

.env file

BROADCAST_DRIVER=redis
REDIS_HOST=redis.test
REDIS_PASSWORD=null
REDIS_PORT=6379

echo configuration

import Echo from "laravel-echo"

window.Echo = new Echo({
   broadcaster: 'socket.io',
   host: 'http://redis.test:6001'
});

laravel-exho-server.json

{
    "authHost": "http://redis.test",
    "authEndpoint": "/broadcasting/auth",
    "clients": [
        {
            "appId": "f27485125ac2627f",
            "key": "6328e672f42cbf4cba1de3da215ec41a"
        }
    ],
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "redis.test"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "redis.test",
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}

it works when i try to broadcast with a local connection (2 browsers - same pc), but when i try to send a "message" from other pc on lan network (192.168.1.50) i have this error

GET: http://redis.test:6001/socket.io/socket.io.js net::err_connection_refused

[vue_warn] error in created hook

how ca i resolve this?


问:
Vlookup across two worksheets using VBA
Source sheet ("Sheet2")
Output sheet ("Sheet3")

I have a list of names and associated values in "Sheet2".  I have another list of names in "Sheet3".  Where the name in sheet2 can also be found in Sheet3, i would like to add in the associated value in the column adjacent to the name in Sheet3.

To do this, I've created a nested loop which behaves as follows;

Loops over all names ("X") in "sheet2"

For each of these names iterate over all names ("Y") in "sheet 3"

where the values match, perform a VLookup on "Sheet2" and highlight the cell to flag that a value was added.

This code worked fine when the two tables were hosted in the same worksheet.  On attempting to replicate this behaviour across two different worksheets (by ensuring that explicit worksheet references were added to all ranges) it doesnt do anything.

Any help would be much appreciated

```<code>Sub colincrosssheet()

On Error Resume Next

Dim inputrange As Range
Dim outputrange As Range
Dim X As Range
Dim Y As Range
Dim inputtoprow As Integer
Dim inputbottomrow As Integer
Dim inputcolumn As Integer
Dim outputtoprow As Integer
Dim outputbottomrow As Integer
Dim outputcolumn As Integer
Dim rngFindin As Range
Dim rngFindout As Range
Dim vlookuprange As Range

'set input column, which contains the line item ids from Pacing Tool, and also sets bottom row
Set rngFindin = Worksheets("Sheet2").Cells.Find("nameinput", LookIn:=xlValues, lookat:=xlWhole)
If rngFindin Is Nothing Then
    MsgBox "Could not find 'Line Item Id' column in your SDF. Please review file.", vbOKOnly, "Column not found"
Else
    inputtoprow = Worksheets("Sheet2").rngFindin.Row + 1
    inputcolumn = Worksheets("Sheet2").rngFindin.Column
    inputbottomrow = Worksheets("Sheet2").Cells(Rows.Count, inputcolumn).End(xlUp).Row
End If

'set output column, which contains the line item ids in the SDF, and also sets bottom row
Set rngFindout = Worksheets("Sheet3").Cells.Find("nameoutput", LookIn:=xlValues, lookat:=xlWhole)
If rngFindout Is Nothing Then
    MsgBox "Could not find 'Line Item Id' column in your SDF. Please review file.", vbOKOnly, "Column not found"
Else
    outputtoprow = Worksheets("Sheet3").rngFindout.Row + 1
    outputcolumn = Worksheets("Sheet3").rngFindout.Column
    outputbottomrow = Worksheets("Sheet3").Cells(Rows.Count, outputcolumn).End(xlUp).Row
End If

'define Vlookup range'
Set vlookuprange = Worksheets("Sheet2").Range(Cells(inputtoprow, inputcolumn), Cells(inputbottomrow, inputcolumn + 1))

'defines input and output range which contain line item ids
Set inputrange = Worksheets("Sheet2").Range(Cells(inputtoprow, inputcolumn), Cells(inputbottomrow, inputcolumn))
Set outputrange = Worksheets("Sheet3").Range(Cells(outputtoprow, outputcolumn), Cells(outputbottomrow, outputcolumn))

'loop through input range and update relevant column in SDF with new bid values
For Each X In Worksheets("Sheet2").inputrange
    For Each Y In Worksheets("Sheet3").outputrange
        If Worksheets("Sheet3").Y.Value = Worksheets("Sheet2").X.Value Then
            Worksheets("Sheet3").Y.Offset(ColumnOffset:=1).Value = Application.WorksheetFunction.VLookup(Worksheets("Sheet2").X.Value, Worksheets("Sheet2").vlookuprange, 2, False)
            Worksheets("Sheet3").Y.Offset(ColumnOffset:=1).Interior.ColorIndex = 28
        End If
    Next Y
Next X

End Sub
</code>```

答:
The Answer (code and explanation) are a little long, but I wanted to share some of the reasons your code didn't work, and what I've done in my updated version below:

First, organzied data related to your InputSheet ("Sheet2") in one section, under With Worksheets("Sheet2"). The same for your OutputSheet ("Sheet3"), under With Worksheets("Sheet3").

Second, I've replaced your double For loop and Application.WorksheetFunction.VLookup with one For and a Application.Match - that will save you a lot of run time.

Some of the errors you have:

Since you aready Set outputrange before, when you run this line For Each Y in Worksheets("Sheet3").outputrange will raise an error, instead you can use For Each Y In OutputRange

Some of your "lastrow" and "lastcolumn" value are not fully qualified, inputbottomrow = Worksheets("Sheet2").Cells(Rows.Count, inputcolumn).End(xlUp).Row needs to be inputbottomrow = Worksheets("Sheet2").Cells(Worksheets("Sheet2").Rows.Count, inputcolumn).End(xlUp).Row. That's why I either defined a variable of type Worksheet and assign it to it, or use a With statement.

Side-Note: I've modified the variables with CAPITAL letters in the begining (it's my way to debug I don't have any Typos when coding)

Code

```<code>Option Explicit

Sub colincrosssheet()

On Error Resume Next

Dim InputtopRow As Long
Dim InputbottomRow As Long
Dim Inputcolumn As Long
Dim OutputtopRow As Long
Dim OutputbottomRow As Long
Dim OutputColumn As Long

Dim rngFindin As Range
Dim rngFindout As Range
Dim VlookupRange As Range
Dim InputRange As Range
Dim OutputRange As Range
Dim X As Range
Dim Y As Range

' set input column, which contains the line item ids from Pacing Tool, and also sets bottom row
With Worksheets("Sheet2")
    Set rngFindin = .Cells.Find("nameinput", LookIn:=xlValues, lookat:=xlWhole)
    If rngFindin Is Nothing Then
        MsgBox "Could not find 'Line Item Id' column in your SDF. Please review file.", vbOKOnly, "Column not found"
    Else
        InputtopRow = rngFindin.Row + 1
        Inputcolumn = rngFindin.Column
        InputbottomRow = .Cells(.Rows.Count, Inputcolumn).End(xlUp).Row
    End If

    ' define input range which contain line item ids
    Set InputRange = .Range(.Cells(InputtopRow, Inputcolumn), .Cells(InputbottomRow, Inputcolumn))
End With

'set output column, which contains the line item ids in the SDF, and also sets bottom row
With Worksheets("Sheet3")
    Set rngFindout = .Cells.Find("nameoutput", LookIn:=xlValues, lookat:=xlWhole)
    If rngFindout Is Nothing Then
        MsgBox "Could not find 'Line Item Id' column in your SDF. Please review file.", vbOKOnly, "Column not found"
    Else
        OutputtopRow = rngFindout.Row + 1
        OutputColumn = rngFindout.Column
        OutputbottomRow = .Cells(.Rows.Count, OutputColumn).End(xlUp).Row
    End If
    ' define output range which contain line item ids
    Set OutputRange = .Range(.Cells(OutputtopRow, OutputColumn), .Cells(OutputbottomRow, OutputColumn))
End With

Dim MatchRow As Variant
' loop through outputrange and update relevant column in SDF with new bid values
For Each Y In OutputRange
    If Not IsError(Application.Match(Y.value, InputRange, 0)) Then ' check if Y is found anywhere in inputrange using the Match
        MatchRow = Application.Match(Y.value, InputRange, 0) + rngFindin.Row

        Y.Offset(, 1).Value = Worksheets("Sheet2").Cells(MatchRow, Inputcolumn + 1)
        Y.Offset(, 1).Interior.ColorIndex = 28
    End If
Next Y

End Sub
</code>```

Title: Vlookup across two worksheets using VBA

Body:
Source sheet ("Sheet2")
Output sheet ("Sheet3")

I have a list of names and associated values in "Sheet2".  I have another list of names in "Sheet3".  Where the name in sheet2 can also be found in Sheet3, i would like to add in the associated value in the column adjacent to the name in Sheet3.

To do this, I've created a nested loop which behaves as follows;

Loops over all names ("X") in "sheet2"

For each of these names iterate over all names ("Y") in "sheet 3"

where the values match, perform a VLookup on "Sheet2" and highlight the cell to flag that a value was added.

This code worked fine when the two tables were hosted in the same worksheet.  On attempting to replicate this behaviour across two different worksheets (by ensuring that explicit worksheet references were added to all ranges) it doesnt do anything.

Any help would be much appreciated

Sub colincrosssheet()

On Error Resume Next

Dim inputrange As Range
Dim outputrange As Range
Dim X As Range
Dim Y As Range
Dim inputtoprow As Integer
Dim inputbottomrow As Integer
Dim inputcolumn As Integer
Dim outputtoprow As Integer
Dim outputbottomrow As Integer
Dim outputcolumn As Integer
Dim rngFindin As Range
Dim rngFindout As Range
Dim vlookuprange As Range

'set input column, which contains the line item ids from Pacing Tool, and also sets bottom row
Set rngFindin = Worksheets("Sheet2").Cells.Find("nameinput", LookIn:=xlValues, lookat:=xlWhole)
If rngFindin Is Nothing Then
    MsgBox "Could not find 'Line Item Id' column in your SDF. Please review file.", vbOKOnly, "Column not found"
Else
    inputtoprow = Worksheets("Sheet2").rngFindin.Row + 1
    inputcolumn = Worksheets("Sheet2").rngFindin.Column
    inputbottomrow = Worksheets("Sheet2").Cells(Rows.Count, inputcolumn).End(xlUp).Row
End If

'set output column, which contains the line item ids in the SDF, and also sets bottom row
Set rngFindout = Worksheets("Sheet3").Cells.Find("nameoutput", LookIn:=xlValues, lookat:=xlWhole)
If rngFindout Is Nothing Then
    MsgBox "Could not find 'Line Item Id' column in your SDF. Please review file.", vbOKOnly, "Column not found"
Else
    outputtoprow = Worksheets("Sheet3").rngFindout.Row + 1
    outputcolumn = Worksheets("Sheet3").rngFindout.Column
    outputbottomrow = Worksheets("Sheet3").Cells(Rows.Count, outputcolumn).End(xlUp).Row
End If

'define Vlookup range'
Set vlookuprange = Worksheets("Sheet2").Range(Cells(inputtoprow, inputcolumn), Cells(inputbottomrow, inputcolumn + 1))

'defines input and output range which contain line item ids
Set inputrange = Worksheets("Sheet2").Range(Cells(inputtoprow, inputcolumn), Cells(inputbottomrow, inputcolumn))
Set outputrange = Worksheets("Sheet3").Range(Cells(outputtoprow, outputcolumn), Cells(outputbottomrow, outputcolumn))

'loop through input range and update relevant column in SDF with new bid values
For Each X In Worksheets("Sheet2").inputrange
    For Each Y In Worksheets("Sheet3").outputrange
        If Worksheets("Sheet3").Y.Value = Worksheets("Sheet2").X.Value Then
            Worksheets("Sheet3").Y.Offset(ColumnOffset:=1).Value = Application.WorksheetFunction.VLookup(Worksheets("Sheet2").X.Value, Worksheets("Sheet2").vlookuprange, 2, False)
            Worksheets("Sheet3").Y.Offset(ColumnOffset:=1).Interior.ColorIndex = 28
        End If
    Next Y
Next X

End Sub

Body:
The Answer (code and explanation) are a little long, but I wanted to share some of the reasons your code didn't work, and what I've done in my updated version below:

First, organzied data related to your InputSheet ("Sheet2") in one section, under With Worksheets("Sheet2"). The same for your OutputSheet ("Sheet3"), under With Worksheets("Sheet3").

Second, I've replaced your double For loop and Application.WorksheetFunction.VLookup with one For and a Application.Match - that will save you a lot of run time.

Some of the errors you have:

Since you aready Set outputrange before, when you run this line For Each Y in Worksheets("Sheet3").outputrange will raise an error, instead you can use For Each Y In OutputRange

Some of your "lastrow" and "lastcolumn" value are not fully qualified, inputbottomrow = Worksheets("Sheet2").Cells(Rows.Count, inputcolumn).End(xlUp).Row needs to be inputbottomrow = Worksheets("Sheet2").Cells(Worksheets("Sheet2").Rows.Count, inputcolumn).End(xlUp).Row. That's why I either defined a variable of type Worksheet and assign it to it, or use a With statement.

Side-Note: I've modified the variables with CAPITAL letters in the begining (it's my way to debug I don't have any Typos when coding)

Code

Option Explicit

Sub colincrosssheet()

On Error Resume Next

Dim InputtopRow As Long
Dim InputbottomRow As Long
Dim Inputcolumn As Long
Dim OutputtopRow As Long
Dim OutputbottomRow As Long
Dim OutputColumn As Long

Dim rngFindin As Range
Dim rngFindout As Range
Dim VlookupRange As Range
Dim InputRange As Range
Dim OutputRange As Range
Dim X As Range
Dim Y As Range

' set input column, which contains the line item ids from Pacing Tool, and also sets bottom row
With Worksheets("Sheet2")
    Set rngFindin = .Cells.Find("nameinput", LookIn:=xlValues, lookat:=xlWhole)
    If rngFindin Is Nothing Then
        MsgBox "Could not find 'Line Item Id' column in your SDF. Please review file.", vbOKOnly, "Column not found"
    Else
        InputtopRow = rngFindin.Row + 1
        Inputcolumn = rngFindin.Column
        InputbottomRow = .Cells(.Rows.Count, Inputcolumn).End(xlUp).Row
    End If

    ' define input range which contain line item ids
    Set InputRange = .Range(.Cells(InputtopRow, Inputcolumn), .Cells(InputbottomRow, Inputcolumn))
End With

'set output column, which contains the line item ids in the SDF, and also sets bottom row
With Worksheets("Sheet3")
    Set rngFindout = .Cells.Find("nameoutput", LookIn:=xlValues, lookat:=xlWhole)
    If rngFindout Is Nothing Then
        MsgBox "Could not find 'Line Item Id' column in your SDF. Please review file.", vbOKOnly, "Column not found"
    Else
        OutputtopRow = rngFindout.Row + 1
        OutputColumn = rngFindout.Column
        OutputbottomRow = .Cells(.Rows.Count, OutputColumn).End(xlUp).Row
    End If
    ' define output range which contain line item ids
    Set OutputRange = .Range(.Cells(OutputtopRow, OutputColumn), .Cells(OutputbottomRow, OutputColumn))
End With

Dim MatchRow As Variant
' loop through outputrange and update relevant column in SDF with new bid values
For Each Y In OutputRange
    If Not IsError(Application.Match(Y.value, InputRange, 0)) Then ' check if Y is found anywhere in inputrange using the Match
        MatchRow = Application.Match(Y.value, InputRange, 0) + rngFindin.Row

        Y.Offset(, 1).Value = Worksheets("Sheet2").Cells(MatchRow, Inputcolumn + 1)
        Y.Offset(, 1).Interior.ColorIndex = 28
    End If
Next Y

End Sub


问:
Console two line output
I have this code which output some value from array, plus - in new line under value a[i]

```<code>Console.Write(a[i] + "\n-");
</code>```

So it looks like this

```<code>a
-
</code>```

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

```<code>a
-b
-c
-d
-
</code>```

I know why this is the case but how can I return one line up after every new line \n? So I can get this

```<code>abcd
----
</code>```

答:
Their are two ways.

The first way is mentioned above.The general idea is to print two lines seperately and that gives you the absolutely same result as what you want in a very simple way.

The second way is to set the cusor position using SetCursorPosition(int Left ,int Top) right under the current position and Write('_') and then move the cusor back again.

Title: Console two line output

Body:
I have this code which output some value from array, plus - in new line under value a[i]

Console.Write(a[i] + "\n-");

So it looks like this

a
-

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

a
-b
-c
-d
-

I know why this is the case but how can I return one line up after every new line \n? So I can get this

abcd
----


问:
How to display a final range of show pages in Grails?
I have domain class objects being added to my database dynamically.

There is the generated index.gsp page which has the table of objects and I want to only display the final 50 objects, NOT all of them.

As of right now this is how the table looks:

```<code><tbody>
<g:each in="${eventInstanceList}" status="i" var="eventInstance">
    <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">

        <td><g:link action="show" id="${eventInstance.id}">${fieldValue(bean: eventInstance, field: "bandsintown_id")}</g:link></td>

        <td>${fieldValue(bean: eventInstance, field: "artist")}</td>

        <td>${fieldValue(bean: eventInstance, field: "ticketStatus")}</td>

        <td>${fieldValue(bean: eventInstance, field: "ticket_url")}</td>

        <td>${fieldValue(bean: eventInstance, field: "venue")}</td>

    </tr>
</g:each>
</code>```

So to reiterate, the code above displays all of my objects in a table - I want to only display the last 50, can anyone help me out here?

UPDATE:

Got it to work with this code in my controller:

```<code>def index()
{
    int eventCount = Event.count()
    int startingPoint = eventCount - 50

    def events = Event.createCriteria().list
    {
        order('id')
        firstResult(startingPoint)
        maxResults(50)
    }

    respond events
}
</code>```

答:
You can modify the index action in your controller, something like:

```<code>def index() {
    def events = Events.createCriteria().list{
        order( 'id', 'desc' )
        maxResults( 50 )
    }
    respond events
}
</code>```

You probably have eventInstanceCount being returned by index and used in your gsp pagination which you can remove.

Body:
I have domain class objects being added to my database dynamically.

There is the generated index.gsp page which has the table of objects and I want to only display the final 50 objects, NOT all of them.

As of right now this is how the table looks:

<g:each in="${eventInstanceList}" status="i" var="eventInstance">

        <g:link action="show" id="${eventInstance.id}">${fieldValue(bean: eventInstance, field: "bandsintown_id")}</g:link>

        ${fieldValue(bean: eventInstance, field: "artist")}

        ${fieldValue(bean: eventInstance, field: "ticketStatus")}

        ${fieldValue(bean: eventInstance, field: "ticket_url")}

        ${fieldValue(bean: eventInstance, field: "venue")}

</g:each>

So to reiterate, the code above displays all of my objects in a table - I want to only display the last 50, can anyone help me out here?

UPDATE:

Got it to work with this code in my controller:

def index()
{
    int eventCount = Event.count()
    int startingPoint = eventCount - 50

    def events = Event.createCriteria().list
    {
        order('id')
        firstResult(startingPoint)
        maxResults(50)
    }

    respond events
}

Body:
You can modify the index action in your controller, something like:

def index() {
    def events = Events.createCriteria().list{
        order( 'id', 'desc' )
        maxResults( 50 )
    }
    respond events
}

You probably have eventInstanceCount being returned by index and used in your gsp pagination which you can remove.


问:
How to make QWebEngineView go fullscreen?
I have the following code, and I want to make my QWebEngineView (Qt 5.8) to go full screen.

My WebView class is contained in a QTabWidget, so it just fills up the tab, not entire screen.

How can I make it go fullscreen?

```<code>class WebView:public QObject{
    void acceptFullScreen(QWebEngineFullScreenRequest request){
        request.accept();
    }

public:
    char* home_page;
    QWebEngineView* view=new QWebEngineView();
    WebView(char* page=(char*)"file:///home/tarptaeya/Desktop/Crusta_Prototype_python/about.html"){
        this->home_page=page;
        createWebView();
        this->view->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled,true);
        this->view->settings()->setAttribute(QWebEngineSettings::PluginsEnabled,true);
        this->view->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows,true);
        connect(this->view->page(),&QWebEnginePage::fullScreenRequested,this,&WebView::acceptFullScreen);
    }
    void createWebView(){
        this->view->load(QUrl(this->home_page));
    }
}
</code>```

答:
I have found a way to do this ,so I am answering my own question :
I can change the acceptFullScreen function as :

```<code>void acceptFullScreen(QWebEngineFullScreenRequest request){
        if(request.toggleOn()){
            request.accept();
            QWidget* w=(QWidget*)this->view->parent();
            this->layout=w->layout();
            this->layout->removeWidget(this->view);
            this->view->setParent(0);
            this->view->showFullScreen();
        }
        else{
            request.accept();
            this->layout->addWidget(this->view);
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following code, and I want to make my QWebEngineView (Qt 5.8) to go full screen.

My WebView class is contained in a QTabWidget, so it just fills up the tab, not entire screen.

How can I make it go fullscreen?

class WebView:public QObject{
    void acceptFullScreen(QWebEngineFullScreenRequest request){
        request.accept();
    }

public:
    char* home_page;
    QWebEngineView* view=new QWebEngineView();
    WebView(char* page=(char*)"file:///home/tarptaeya/Desktop/Crusta_Prototype_python/about.html"){
        this->home_page=page;
        createWebView();
        this->view->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled,true);
        this->view->settings()->setAttribute(QWebEngineSettings::PluginsEnabled,true);
        this->view->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows,true);
        connect(this->view->page(),&QWebEnginePage::fullScreenRequested,this,&WebView::acceptFullScreen);
    }
    void createWebView(){
        this->view->load(QUrl(this->home_page));
    }
}

Body:
I have found a way to do this ,so I am answering my own question :
I can change the acceptFullScreen function as :

void acceptFullScreen(QWebEngineFullScreenRequest request){
        if(request.toggleOn()){
            request.accept();
            QWidget* w=(QWidget*)this->view->parent();
            this->layout=w->layout();
            this->layout->removeWidget(this->view);
            this->view->setParent(0);
            this->view->showFullScreen();
        }
        else{
            request.accept();
            this->layout->addWidget(this->view);
        }


问:
Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
I am trying to build an application wherein I take input from a dialog box and later inflate it in a listview. But Getting the below-mentioned error. Is ther an issue ith my use of edit texts ? Any help is really appriciated.

Error:
                                                                                -

```<code>-------- beginning of crash
03-29 16:55:09.080 17033-17033/com.example.sumeet.assignment4sess8 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sumeet.assignment4sess8, PID: 17033
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                                                                                at com.example.sumeet.assignment4sess8.MainActivity$2.onClick(MainActivity.java:77)
                                                                                at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
</code>```

MainActivity.java

```<code>    package com.example.sumeet.assignment4sess8;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<String> al_contactName, al_contactNumber, al_contactDOB;
    private EditText ev_diag_contactName, ev_diag_contactNumber, ev_diag_DOB;
    String diag_contactName, diag_contactNumber, diag_contactDOB;
    protected MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.lv_contacts);

        al_contactName = new ArrayList<>();
        al_contactNumber = new ArrayList<>();
        al_contactDOB = new ArrayList<>();
        adapter = new MyAdapter(getApplicationContext(), al_contactName,al_contactNumber,al_contactDOB);
        listView.setAdapter(adapter);
    }

    //attaching the menu to the main activity
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.admenu: {
                addItem();
                Toast.makeText(getApplicationContext(), "Item Added", Toast.LENGTH_LONG).show();
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    private void addItem() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = this.getLayoutInflater();
        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        alertDialog.setView(inflater.inflate(R.layout.dialoge_content, null))
                // Add action buttons
                .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(getApplicationContext(),"Hi",Toast.LENGTH_LONG).show();
                        // assign identifiers to the edittext in dialoge
                        ev_diag_contactName = (EditText) findViewById(R.id.diag_contact_name);
                        ev_diag_contactNumber = (EditText) findViewById(R.id.diag_phone_number);
                        ev_diag_DOB = (EditText) findViewById(R.id.diag_date_of_birth);

                        //get the string values
                        diag_contactName = ev_diag_contactName.getText().toString();
                        diag_contactNumber = ev_diag_contactNumber.getText().toString();
                        diag_contactDOB = ev_diag_DOB.getText().toString();

                        //add the string values to the arraylist variabe
                        al_contactName.add(diag_contactName);
                        al_contactNumber.add(diag_contactNumber);
                        al_contactDOB.add(diag_contactDOB);

                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        alertDialog.show();
    }
}
</code>```

MyAdapter.java

```<code>package com.example.sumeet.assignment4sess8;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Sumeet on 29-03-2017.
 */

public class MyAdapter extends BaseAdapter {
    Context context;
    LayoutInflater inflater;

    private ArrayList<String> al_contactName, al_contactNumber, al_contactDOB;

    public MyAdapter(Context context, ArrayList al_contactName, ArrayList al_contactNumber, ArrayList al_contactDOB) {
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        this.al_contactName = al_contactName;
        this.al_contactNumber = al_contactNumber;
        this.al_contactDOB = al_contactDOB;

    }

    public int getCount() {
        return al_contactName.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    public class ViewHolder {
        TextView contactName, contactNumber, contactDOB;

        void bindView(View convertView) {
            //getting values from name_contacts_dob
            contactName = (TextView) convertView.findViewById(R.id.contact_name);
            contactNumber = (TextView) convertView.findViewById(R.id.contact_number);
            contactDOB = (TextView) convertView.findViewById(R.id.contact_DOB);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            // convertView = getLayoutInflater().inflate(R.layout.name_and_contacts, parent, false);
            // LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.name_contacts_dob, parent);
            holder.bindView(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.contactName.setText(al_contactName.get(position));
        holder.contactNumber.setText(al_contactNumber.get(position));
        holder.contactDOB.setText(al_contactDOB.get(position));
        return convertView;
    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/lv_contacts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>
</RelativeLayout>
</code>```

options_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/admenu"
        android:title="Add" />
</menu>
</code>```

dialoge_content.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_dark"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:background="@android:color/holo_red_dark"
        android:text="Enter the Details"
        android:textColor="@android:color/background_dark"
        android:textSize="18dp" />

    <EditText
        android:id="@+id/diag_contact_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:hint="Name" />

    <EditText
        android:id="@+id/diag_phone_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:fontFamily="sans-serif"
        android:hint="Phone Number" />

    <EditText
        android:id="@+id/diag_date_of_birth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:fontFamily="sans-serif"
        android:hint="Date of Birth" />

</LinearLayout>
</code>```

name_contacts_dob.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/contact_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

        <TextView
            android:id="@+id/contact_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

        <TextView
            android:id="@+id/contact_DOB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

    </LinearLayout>

</LinearLayout>
</code>```

答:
```<code>ev_diag_contactName = (EditText) findViewById(R.id.diag_contact_name);
ev_diag_contactNumber = (EditText) findViewById(R.id.diag_phone_number);
ev_diag_DOB = (EditText) findViewById(R.id.diag_date_of_birth);
</code>```

This is wrong. You have inflated a particular layout for this dialog and all of these EditTexts reside there. So, inflate the view and save that to a View object and find EditText within that view.

So, modify your code like below.

```<code>private View view;

private void addItem() {
  AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
  LayoutInflater inflater = this.getLayoutInflater();
  // inflate the View
  view = inflater.inflate(R.layout.dialoge_content, null);

  alertDialog.setView(view)
  .setPositiveButton("Save", new DialogInterface.OnClickListener() {

         @Override
         public void onClick(DialogInterface dialogInterface, int i) {
                 Toast.makeText(getApplicationContext(),"Hi",Toast.LENGTH_LONG).show();
                 // assign identifiers to the edittext in dialoge
/*
   findViewById is now view.findViewById
*/
                 ev_diag_contactName = (EditText) view.findViewById(R.id.diag_contact_name);
                 ev_diag_contactNumber = (EditText) view.findViewById(R.id.diag_phone_number);
                 ev_diag_DOB = (EditText) view.findViewById(R.id.diag_date_of_birth);

                 //Rest of the code

         }
  }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
        }
  });
  alertDialog.show();
}
</code>```

Body:
I am trying to build an application wherein I take input from a dialog box and later inflate it in a listview. But Getting the below-mentioned error. Is ther an issue ith my use of edit texts ? Any help is really appriciated.

Error:
                                                                                -

-------- beginning of crash
03-29 16:55:09.080 17033-17033/com.example.sumeet.assignment4sess8 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sumeet.assignment4sess8, PID: 17033
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                                                                                at com.example.sumeet.assignment4sess8.MainActivity$2.onClick(MainActivity.java:77)
                                                                                at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

MainActivity.java

    package com.example.sumeet.assignment4sess8;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<String> al_contactName, al_contactNumber, al_contactDOB;
    private EditText ev_diag_contactName, ev_diag_contactNumber, ev_diag_DOB;
    String diag_contactName, diag_contactNumber, diag_contactDOB;
    protected MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.lv_contacts);

        al_contactName = new ArrayList<>();
        al_contactNumber = new ArrayList<>();
        al_contactDOB = new ArrayList<>();
        adapter = new MyAdapter(getApplicationContext(), al_contactName,al_contactNumber,al_contactDOB);
        listView.setAdapter(adapter);
    }

    //attaching the menu to the main activity
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.admenu: {
                addItem();
                Toast.makeText(getApplicationContext(), "Item Added", Toast.LENGTH_LONG).show();
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    private void addItem() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = this.getLayoutInflater();
        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        alertDialog.setView(inflater.inflate(R.layout.dialoge_content, null))
                // Add action buttons
                .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(getApplicationContext(),"Hi",Toast.LENGTH_LONG).show();
                        // assign identifiers to the edittext in dialoge
                        ev_diag_contactName = (EditText) findViewById(R.id.diag_contact_name);
                        ev_diag_contactNumber = (EditText) findViewById(R.id.diag_phone_number);
                        ev_diag_DOB = (EditText) findViewById(R.id.diag_date_of_birth);

                        //get the string values
                        diag_contactName = ev_diag_contactName.getText().toString();
                        diag_contactNumber = ev_diag_contactNumber.getText().toString();
                        diag_contactDOB = ev_diag_DOB.getText().toString();

                        //add the string values to the arraylist variabe
                        al_contactName.add(diag_contactName);
                        al_contactNumber.add(diag_contactNumber);
                        al_contactDOB.add(diag_contactDOB);

                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        alertDialog.show();
    }
}

MyAdapter.java

package com.example.sumeet.assignment4sess8;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Sumeet on 29-03-2017.
 */

public class MyAdapter extends BaseAdapter {
    Context context;
    LayoutInflater inflater;

    private ArrayList<String> al_contactName, al_contactNumber, al_contactDOB;

    public MyAdapter(Context context, ArrayList al_contactName, ArrayList al_contactNumber, ArrayList al_contactDOB) {
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        this.al_contactName = al_contactName;
        this.al_contactNumber = al_contactNumber;
        this.al_contactDOB = al_contactDOB;

    }

    public int getCount() {
        return al_contactName.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    public class ViewHolder {
        TextView contactName, contactNumber, contactDOB;

        void bindView(View convertView) {
            //getting values from name_contacts_dob
            contactName = (TextView) convertView.findViewById(R.id.contact_name);
            contactNumber = (TextView) convertView.findViewById(R.id.contact_number);
            contactDOB = (TextView) convertView.findViewById(R.id.contact_DOB);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            // convertView = getLayoutInflater().inflate(R.layout.name_and_contacts, parent, false);
            // LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.name_contacts_dob, parent);
            holder.bindView(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.contactName.setText(al_contactName.get(position));
        holder.contactNumber.setText(al_contactNumber.get(position));
        holder.contactDOB.setText(al_contactDOB.get(position));
        return convertView;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/lv_contacts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>
</RelativeLayout>

options_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/admenu"
        android:title="Add" />
</menu>

dialoge_content.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_dark"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:background="@android:color/holo_red_dark"
        android:text="Enter the Details"
        android:textColor="@android:color/background_dark"
        android:textSize="18dp" />

    <EditText
        android:id="@+id/diag_contact_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:hint="Name" />

    <EditText
        android:id="@+id/diag_phone_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:fontFamily="sans-serif"
        android:hint="Phone Number" />

    <EditText
        android:id="@+id/diag_date_of_birth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:fontFamily="sans-serif"
        android:hint="Date of Birth" />

</LinearLayout>

name_contacts_dob.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/contact_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

        <TextView
            android:id="@+id/contact_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

        <TextView
            android:id="@+id/contact_DOB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

    </LinearLayout>

</LinearLayout>

Body:
ev_diag_contactName = (EditText) findViewById(R.id.diag_contact_name);
ev_diag_contactNumber = (EditText) findViewById(R.id.diag_phone_number);
ev_diag_DOB = (EditText) findViewById(R.id.diag_date_of_birth);

This is wrong. You have inflated a particular layout for this dialog and all of these EditTexts reside there. So, inflate the view and save that to a View object and find EditText within that view.

So, modify your code like below.

private View view;

private void addItem() {
  AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
  LayoutInflater inflater = this.getLayoutInflater();
  // inflate the View
  view = inflater.inflate(R.layout.dialoge_content, null);

  alertDialog.setView(view)
  .setPositiveButton("Save", new DialogInterface.OnClickListener() {

         @Override
         public void onClick(DialogInterface dialogInterface, int i) {
                 Toast.makeText(getApplicationContext(),"Hi",Toast.LENGTH_LONG).show();
                 // assign identifiers to the edittext in dialoge
/*
   findViewById is now view.findViewById
*/
                 ev_diag_contactName = (EditText) view.findViewById(R.id.diag_contact_name);
                 ev_diag_contactNumber = (EditText) view.findViewById(R.id.diag_phone_number);
                 ev_diag_DOB = (EditText) view.findViewById(R.id.diag_date_of_birth);

                 //Rest of the code

         }
  }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
        }
  });
  alertDialog.show();
}


问:
In excel, How to calculate cricket overs completed and overs left to bowl from a cricket table?
This image will give an idea what I exactly looking for. The completed cells calculated and return the overs completed value and the empty cells calculated the remaining overs value. Please help me.</p>

答:
I have tried your idea of subtracting the overs completed from 20 but I didn't get right answer.

Dear Rajesh S, I am not ok to add more columns and would like to put it bit simple.

Finally, I have found a solution by myself for this, here it is
=INT(COUNTBLANK(B2:G21)/6)+MOD(COUNTBLANK(B2:G21),6)/10
and this one works fine for me.

How ever Thank you very much both of you for your time and answers for my question.


问:
Using catalog image as full background image in Magento
I am dealing with a short deadline here, so I will ask this question without having investigated this in depth yet. Although I blieve it's a good question that may interest alot of people dealing with Magento.

I have been ask to do some modifications on a Magento eshop. Among other things I need to use the category image of each category as a full resizable background image, using this (or a similar) plugin - http://johnpatrickgiven.com/jquery/background-resize/

Any help would be greatly appreciated.

答:
To your theme's layout add the following as local.xml

```<code><layout>
    <catalog_category_default>
        <reference name="before_body_end">
            <block type="catalog/category_view" name="back.image" template="page/html/back.image.phtml" />
        </reference>
    </catalog_category_default>
    <catalog_category_layered>
        <reference name="before_body_end">
            <block type="catalog/category_view" name="back.image" template="page/html/back.image.phtml" />
        </reference>
    </catalog_category_layered>
<layout>
</code>```

Next, in the theme's template create a file page/html/back.image.phtml

```<code><?php if ($this->getCurrentCategory()->getImage()): ?>
<div id="back_frame">
    <img class="back_image" src="<?php echo $this->getCurrentCategory()->getImageUrl() ?>" alt="<?php echo $this->getCurrentCategory()->getName() ?>" />
</div>
<?php endif ?>
</code>```

Lastly add something like this to your theme's CSS.

```<code>.page {
    position: relative;
}
#back_frame {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -1;
}
#back_image {
    width: 100%;
}
</code>```

I haven't actually tested any of this but it seems simple enough to work. Certainly it's much too simple to need javascript!

Body:
To your theme's layout add the following as local.xml

<layout>
    <catalog_category_default>
        <reference name="before_body_end">
            <block type="catalog/category_view" name="back.image" template="page/html/back.image.phtml" />
        </reference>
    </catalog_category_default>
    <catalog_category_layered>
        <reference name="before_body_end">
            <block type="catalog/category_view" name="back.image" template="page/html/back.image.phtml" />
        </reference>
    </catalog_category_layered>
<layout>

Next, in the theme's template create a file page/html/back.image.phtml

<?php if ($this->getCurrentCategory()->getImage()): ?>
<div id="back_frame">
    <img class="back_image" src="<?php echo $this->getCurrentCategory()->getImageUrl() ?>" alt="<?php echo $this->getCurrentCategory()->getName() ?>" />
</div>
<?php endif ?>

Lastly add something like this to your theme's CSS.

.page {
    position: relative;
}
#back_frame {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -1;
}
#back_image {
    width: 100%;
}

I haven't actually tested any of this but it seems simple enough to work. Certainly it's much too simple to need javascript!