text:
Q: Angular Modal Dialog not displaying I am using a modal dialog in my Angular 4 application that utilizes a BehaviorSubject observable and this works fine in a number of other areas but not for one particular use case.
See below for samples of some of the Typescript.
dialog.service.ts:
import { Injectable, TemplateRef } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Dialog, DialogSizeEnum } from './dialog.model';

@Injectable()
export class DialogService {

    private d: Dialog = { template: null, size: DialogSizeEnum.XLarge };
    private dialogSubject = new BehaviorSubject<Dialog>({ template: null, size: DialogSizeEnum.XLarge });

    constructor() { }

    showDialog(template: TemplateRef<any>, size = DialogSizeEnum.XLarge, requiresAction = false) {
        Object.assign(this.d, { template: template, size: size, requiresAction: requiresAction });
        if (this.d !== null) {
            this.dialogSubject.next(this.d);
        }
    }

    getDialog(): BehaviorSubject<Dialog> {
        return this.dialogSubject;
    }

    clear() {
        this.dialogSubject.next(null);
    }
}

dialog.component.ts:
import { Component, OnInit, OnDestroy, ViewEncapsulation, ViewChild } from '@angular/core';
import { Dialog, DialogSizeEnum } from './dialog.model';
import { DialogService } from './dialog.service';
import { PlatformLocation } from '@angular/common';
import { Router, NavigationStart, RouterEvent, NavigationEnd } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { state, trigger, transition, animate, style, AnimationEvent } from '@angular/animations';

@Component({
    selector: 'app-dialog',
    templateUrl: './dialog.component.html',
    styles: [],
    encapsulation: ViewEncapsulation.None,
    animations: [
        trigger('dialogState', [
            state('void', style(
                {
                    opacity: 0,
                    'margin-top': '-300px'
                }
            )),
            transition('* => *', [
                animate('0.5s ease')
            ])
        ]),
        trigger('dialogBgState', [
            state('void', style(
                {
                    opacity: 0,
                }
            )),
            transition('* => *', [
                animate('0.5s ease')
            ])
        ])
    ]
})
export class DialogComponent implements OnInit, OnDestroy {

    @ViewChild('engModal') engModal: any;
    routerSubscription: Subscription;
    subscription: Subscription;
    dialog: Dialog;
    showDialog: boolean;
    dialogSize = DialogSizeEnum;

    constructor(
    private _location: PlatformLocation,
    private _dialog: DialogService,
    private _router: Router) { }

    open() {
        this.showDialog = true;
        const body = document.body;
        body.classList.add('cell-modal-open');
    }

    close(validClose: boolean) {
        if (validClose === true) {
            this.dialog = undefined;
        }
    }

    dialogAnimDone(event: AnimationEvent) {
        if (event.toState === 'void') {
            const body = document.body;
            body.classList.remove('cell-modal-open');
            this.showDialog = false;
        }
    }

    getDialogSize(dialogSize: DialogSizeEnum): string {
        switch (dialogSize) {
            case DialogSizeEnum.Standard:
                return '';
            case DialogSizeEnum.Large:
                return 'modal-lg';
            case DialogSizeEnum.XLarge:
                return 'modal-xl';
            case DialogSizeEnum.Small:
                return 'modal-sm';
            default:
                return '';
        }
    }

    private handleDialog(d: Dialog) {
        if (!d) {
            this.close(true);
        } else if (d.template) {
            if (this.showDialog) {
                this.close(true);
            }
            this.dialog = d;
            this.open();
        }
    }

    private handleDialogError(err: any) {
        console.log('Dialog Component error: ' + err);
    }

    private initialiseRoutingEventListeners(): void {
        this._location.onPopState(() => {
            if (this.showDialog) {
                this.close(true);
            }
        });
        this.routerSubscription = this._router.events.subscribe((event: RouterEvent) => {
            if (event instanceof NavigationStart) {
                if (this.showDialog) {
                    this.close(true);
                }
            }
            if (event instanceof NavigationEnd) {
                if (this.showDialog) {
                    this.close(true);
                }
            }
        });
    }

    ngOnInit() {
        this.subscription = this
            ._dialog
            .getDialog()
            .subscribe({
                next: (d) => { this.handleDialog(d) },
                error: (err) => this.handleDialogError(err)
            });
        this.initialiseRoutingEventListeners();
    }

    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
        if (this.routerSubscription) {
            this.routerSubscription.unsubscribe();
        }
    }

}
requests.module.ts (module for business area where modal works correctly):
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import {
    UserComponent, DetailComponent, DetailModalComponent, CreateComponent, CreateAmendmentComponent,
    ReviewAmendmentListComponent, ViewAmendmentListComponent, ListComponent,
    ReviewedAmendmentListComponent, AssociatedComponent
} from './';

import { RequestsRoutingModule } from './requests-routing.module';
import { RequestService, JiraService, JiraCreateIssueComponent, RequestFilterComponent } from './shared';
import { RaciMembersComponent } from './shared/components/raci-members/raci-members.component';
import { CommentsModule } from './comments/comments.module';
import { TitleCasePipe } from '../shared';

@NgModule({
    imports: [
        RequestsRoutingModule,
        SharedModule,
        NgbModule,
        CommentsModule
    ],
    declarations: [
        UserComponent,
        DetailComponent,
        CreateComponent,
        CreateAmendmentComponent,
        ReviewAmendmentListComponent,
        ViewAmendmentListComponent,
        ListComponent,
        ReviewedAmendmentListComponent,
        AssociatedComponent,
        JiraCreateIssueComponent,
        RaciMembersComponent,
        RequestFilterComponent,
        DetailModalComponent
    ],
    providers: [
        RequestService,
        JiraService,
        TitleCasePipe
    ],
    exports: [
        RequestFilterComponent,
        DetailModalComponent
    ]
})
export class RequestsModule { }

detail-modal.component.ts (for actual details view):
import { Component, OnInit, TemplateRef, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { DialogService } from '../../../shared/components/dialog/dialog.service';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl, AbstractControl, ValidatorFn } from '@angular/forms';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import * as moment from 'moment';
import { Observable } from 'rxjs/Observable';
import { appsettings } from '../../../../settings/appsettings';
import {
    RequestService, RequestEdit,
    RequestAmendmentView, ViewAmendmentListComponent,
    RequestEditAdminSubmit, RequestEditDevSubmit,
    RequestEditCustomerMemberSubmit,
    RagstatusEnum
} from '../../shared';
import {
    RequestStatus, RequestType, AlertService, ActiveDirectory,
    ActiveDirectoryService, UserSearchComponent, ConfirmComponent, TitleCasePipe,
    ValueCompareValidator, ValueCompare
} from '../../../shared';
import { RequestQueue } from '../../../shared/models';
import { RequestQueueService } from 'app/request-queue/request-queue.service';
import { RequestUrgencyType, RequestUrgencyTypeEnum } from '../../../shared/models/request-urgency.model';
import { NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { DateCompareValidator } from 'app/shared/validation/value-compare/date-compare.function';
import { ActiveDirectoryUserValidator } from 'app/shared/validation/active-directory/active-directory.function';
import { RequestStatusEnum } from 'app/shared/models';
import { DateCompareValueValidator } from 'app/shared/validation/value-compare/date-compare-value.function';
import { RequiredOnDropDownValidator } from 'app/shared/validation/required-on-drop-down.function';
import Dialogmodel = require('../../../shared/components/dialog/dialog.model');
import DialogSizeEnum = Dialogmodel.DialogSizeEnum;

declare var $: any;

@Component({
    selector: 'app-detail-modal',
    templateUrl: './detail-modal.component.html',
    styleUrls: ['../detail.component.scss']
})

export class DetailModalComponent implements OnInit {

    @ViewChild('detailModal') detailModal: TemplateRef<any>;

    @ViewChild('tagEntryBox') tagInput: ElementRef;

    form: FormGroup;
    id: number;
    request: RequestEdit;
    isBusy = true;
    waitCursorMessage = 'Loading modal...';
    hideAmendments = true;            // is the amendment accordion hidden?
    showAddAmendment = false;         // is the create amendment visible?
    amendmentAccordionOpen = false;   // is the amendment accordian currently open?
    disableControls = true;
    showAmendButton = false;
    membersUpdated = false;
    shouldDisableResponsibleMembers = false;
    amendmentsUpdated = true;
    amendmentsFormGroup: FormGroup;
    createAmendmentFormGroup: FormGroup;
    showFooter = true;
    descriptionMax: number;
    showDateNeeded = false;
    tempDate = new Date(moment('2001-01-01', 'YYYY-MM-DD').format('MM/DD/YYYY')).toDateString();
    ragStatus = RagstatusEnum;
    currentRate = 2;
    hovered = 0;
    showCompletedDate = false;
    allQueues: RequestQueue[];
    initialQueue: RequestQueue;
    queueId: number;
    modalEl = null;

    constructor(
    private _dialog: DialogService,
    private _formBuilder: FormBuilder,
    private _requestService: RequestService,
    private _route: ActivatedRoute,
    private _alertService: AlertService,
    private _activeDirectoryService: ActiveDirectoryService,
    private _location: Location,
    private _sanitizer: DomSanitizer,
    private _titleCase: TitleCasePipe,
    private _queueService: RequestQueueService,
    private _rootNode: ElementRef) { }

    ngOnInit(): void { }

    populateForm(): void {
        this.getAllQueues();
        this.getRequest();    }

    getAllQueues(): void {
        this.isBusy = true;
        this._queueService.getAllQueues().subscribe({
            next: (result) => {
                this.allQueues = result;
            },
            error: (err) => {
                this.isBusy = false;
                this._alertService.sendAlert('warning', 'Unable to load queues!');
            },
            complete: () => {
                this.isBusy = false;
            }
        });
    }

    getRequest(): void {
        this._route.params
            .switchMap(x => this._requestService.getDetailRequest(this.id))
            .subscribe(request => this.receiveRequest(request), error => this.loadError());
    }

    loadError() {
        this.isBusy = false;
        this._alertService.sendAlert('warning', 'Failed to load request!');
    }

    showSave() {
        return !this.shouldDisableControlForAdmin()
            || !this.shouldDisableControlForDev()
            || !this.shouldDisableControlForRequester()
            || this.membersUpdated
    }

    initForm() {
    …
    … (other code not relevant to this question)
    …
    }

    setformValues() {
        this.form.patchValue({
           …
    … (other code not relevant to this question)
    …
        });
    }

    private mapToNgbDate(val: any): NgbDateStruct {
        if (!val) {
            return null;
        }
        const d: Date = new Date(val);
        return {
            day: d.getDate(),
            month: d.getMonth() + 1,
            year: d.getFullYear()
        };
    }

    private mapToDate(d: NgbDateStruct): Date {
        if (!d) {
            return null;
        }
        return new Date(d.year, d.month - 1, d.day);
    }

    onSubmit(): void {
        this.isBusy = true;
        this.waitCursorMessage = 'Saving...';
        if (this.checkCanChangeStatus()) {
            this.prepareSaveRequest();
        } else {
            this.isBusy = false;
            this._alertService.sendAlert('info', 'You cannot change status when there is an outstanding amendment!');
        }
    }

    submissionComplete(request) {
        this.request = request;
        this._alertService.sendAlert('success', 'Request updated!');
        this.form.markAsPristine();
        this.isBusy = false;
        this.membersUpdated = false;
        this.allowedToAddResponsibleMembers();
        this.setShowAmendButton();
    }

    submissionError() {
        this._alertService.sendAlert('warning', 'Failed to update request!');
        this.isBusy = false;
    }

    prepareSaveRequest(): void {
    …
    … (other code not relevant to this question)
    …
            this.cleanSaveRequest();
        }

    …
    … (other code not relevant to this question)
    …
    }

    showDialog(requestId: number) {
        this.id = requestId;
        this.populateForm();
        this._dialog.showDialog(this.detailModal, DialogSizeEnum.XLarge);
    }

    close() {
        this._dialog.clear();
    }

}

associated.component.ts (example of modal successfully being used):
import { Component, OnInit, ViewChild } from '@angular/core';
import { AdminListRequestViewModel, RequestService, RequestFilter, RagstatusEnum } from '../shared';
import { AlertService, RequestStatusEnum } from '../../shared';
import { DetailModalComponent } from '../detail/detail-modal/detail-modal.component'

@Component({
    templateUrl: './associated.component.html',
    styleUrls: ['./associated.component.scss']
})
export class AssociatedComponent implements OnInit {
    @ViewChild('associatedDetailModalComponent') associatedDetailModalComponent: DetailModalComponent;

    requests: AdminListRequestViewModel[];
    isBusy = true;
    selectedStatuses = [
      RequestStatusEnum.New,
      RequestStatusEnum.AwaitingApproval,
      RequestStatusEnum.BeingTested,
      RequestStatusEnum.InDesign,
      RequestStatusEnum.InDevelopment,
      RequestStatusEnum.Approved
    ];
    selectedFilter: RequestFilter;
    ragStatus = RagstatusEnum;

    constructor(
    private _requestService: RequestService,
    private _alertService: AlertService) { }

    ngOnInit(): void {
        this.getRequests();
    }

    getRequests(): void {
        this._requestService.getAssociatedRequests().subscribe(requests => this.receiveRequests(requests), error => this.onError());
    }

    onError() {
        this._alertService.sendAlert('warning', 'Unable to load requests!');
        this.isBusy = false;
    }

    receiveRequests(returnedRequests): void {
        this.requests = returnedRequests;
        this.isBusy = false;
    }

    filterChanged(newFilterValue: RequestFilter) {
        this.selectedFilter = newFilterValue;
    }

    viewAssociatedRequest(requestId: number) {
        this.associatedDetailModalComponent.showDialog(requestId);
    }

}
manage-request-queues.component.ts (where modal does not display):
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { RequestQueueService } from 'app/request-queue/request-queue.service';
import {
    RequestQueue, RequestQueueRequest, RequestQueuePosition, RequestQueueChanges,
    RequestQueueWithRequests, RequestQueueMove
} from 'app/request-queue/models';
import { RequestService } from 'app/requests/shared';
import { AlertService } from 'app/shared';
import { DragulaService } from 'ng2-dragula';
import { YesNoCancelComponent, RequestStatusEnum } from 'app/shared';
import { DetailModalComponent } from '../../requests/detail/detail-modal/detail-modal.component';

@Component({
    selector: 'app-manage-request-queues',
    templateUrl: './manage-request-queues.component.html',
    styleUrls: ['./manage-request-queues.component.scss']
})
export class ManageRequestQueuesComponent implements OnInit, OnDestroy {
    @ViewChild('manageRequestDetailModalComponent') manageRequestDetailModalComponent: DetailModalComponent;

    selectedQueueId = '-1';
    allQueues: RequestQueueWithRequests[];
    dragulaDropSubscription: any;
    dragulaDragSubscription: any;
    dragulaDragEndSubscription: any;
    moves = new Array<RequestQueueMove>();
    saving = false;
    isBusy = true;
    waitCursorMessage = 'Loading...';

    get canDeactivate(): boolean {
        return this.moves.length === 0;
    }

    constructor(
        private _queueService: RequestQueueService,
        private _alertService: AlertService,
        private _dragulaService: DragulaService) {
    }

    saveQueues() {
        this.saving = true;
        this.isBusy = true;
        this.waitCursorMessage = 'Saving...';
        const saveRequestCollection = this.buildSaveRequestCollection();
        if (saveRequestCollection.length > 0) {
            this._queueService.saveRequestQueueChanges(saveRequestCollection).subscribe({
                next: (result) => {
                    this._alertService.sendAlert('success', 'Request queues have been updated.');
                },
                error: (err) => {
                    console.log(err);
                    const result = JSON.parse(err.error);
                    this._alertService.sendAlert('danger', result.messageList[0]);
                    this.saving = false;
                    this.isBusy = false;
                },
                complete: () => {
                    this.saving = false;
                    this.isBusy = false;
                    this.moves = new Array<RequestQueueMove>();
                }
            });
        }
    }

    resetQueues() {
        this.selectedQueueId = '-1';
        this.allQueues = new Array<RequestQueueWithRequests>();
        this.moves = new Array<RequestQueueMove>();
        this.getAllQueuesWithRequests();
    }

    showQueue(requestQueueID: number) {
        return +this.selectedQueueId === requestQueueID;
    }

    private buildSaveRequestCollection() {
        const saveRequestCollection = new Array<RequestQueuePosition>();

        this.allQueues.forEach(queue => queue.requests.forEach(request => {
            const queueIndex = queue.requests.indexOf(request);
            // set queue id to pick up user changes
            request.requestQueueID = queue.requestQueueID;
            if (this.checkHasUpdated(request, queue.requests.indexOf(request))) {
                // must update position as this is likely to have changed
                request.requestQueuePosition = queueIndex + 1;
                saveRequestCollection.push({
                    requestID: request.requestID,
                    requestQueueID: request.requestQueueID,
                    queuePosition: request.requestQueuePosition,
                    requestStatusID: request.requestStatus.requestStatusId
                });
            }
        }));

        return saveRequestCollection;
    }

    ngOnInit() {
        this.getAllQueuesWithRequests();
    }

    ngOnDestroy() {
        this.selectedQueueId = '-1';
        this.allQueues = new Array<RequestQueueWithRequests>();
        this.moves = new Array<RequestQueueMove>();
        if (this.dragulaDropSubscription) {
            this.dragulaDropSubscription.unsubscribe();
        }
        if (this.dragulaDragSubscription) {
            this.dragulaDragSubscription.unsubscribe();
        }
        if (this.dragulaDragEndSubscription) {
            this.dragulaDragEndSubscription.unsubscribe();
        }
    }

    viewManageRequest(requestId: number) {
        this.manageRequestDetailModalComponent.showDialog(requestId);
    }

}

request-queue.module.ts (used by unsuccessful component):
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RequestQueueRoutingModule } from './request-queue-routing.module';
import { RequestQueueService } from './request-queue.service';
import { ManageRequestQueuesComponent } from './manage-request-queues/manage-request-queues.component';
import { ModifyRequestQueueComponent } from './modify-request-queue/modify-request-queue.component';
import { AddRequestQueueComponent } from './add-request-queue/add-request-queue.component';
import { SharedModule } from 'app/shared/shared.module';
import { DragulaModule } from 'ng2-dragula';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { RequestsModule } from '../requests/requests.module'

@NgModule({
    imports: [
        CommonModule,
        SharedModule,
        FormsModule,
        DragulaModule,
        NgbModule,
        ReactiveFormsModule,
        RequestQueueRoutingModule,
        RequestsModule
    ],
    declarations: [ManageRequestQueuesComponent, ModifyRequestQueueComponent, AddRequestQueueComponent],
    providers: [RequestQueueService]
})
export class RequestQueueModule { }

I believe the problem is that the dialogSubject (BehaviorSubject) in dialog.service.ts does not have any observers for the manage-request-queues where the modal is not working. This is also evident in detail-modal.component.ts where the injected _dialog DialogService dialogSubject also has no observers (where is has for all other successful implementations of this dialog).
The other main difference with the unsuccessful manage-request-queues is that it is in another area of the app so has it's own module (see above). I have imported the RequestsModule but this makes no difference. I have also tried adding the DialogService to the Providers in app.module but to no avail.
I suspect this might be a simple fix related to the unsuccessful component not having the embedded BehaviorSubject subscribed to but I'm not sure how this is successfully happening for the other use cases.
I realise there's a lot of code above but the main items of interest are related to the dialog.service (I've removed most of the irrelevant code).
I am new to Angular so apologies if the answer is obvious.

A: After much trial & error the cause of the issue was the DialogService not being in scope for the manage-request-queues.component due to it's location within the solution.
The fix was to move the import and provider declaration from the shared.module to the main app.module.


text:
Q: mvc4 upload file I can not invoking MY action I made an action and using Html.BeginForm to upload image file
my controller name is ImagesTaple
and it is like that:
    using System;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using bootstrab1.Models;

namespace bootstrab1.Controllers
{
    public class ImagesTableController : Controller
    {
        private SpaDbEntities db = new SpaDbEntities();

        //
        // GET: /Images/

        public ActionResult Index()
        {
            return View(db.C_Images.ToList());
        }

        [HttpPost]
        public ActionResult UploadImg(HttpPostedFileBase image)
        {
            if (image.ContentLength > 0)
            {
                var FileFame = Path.GetFileName(image.FileName);
                var path = Path.Combine(Server.MapPath("~/Images/"), FileFame);
                image.SaveAs(path);
            }
            return RedirectToAction("Create");
        }
        //
        // GET: /Images/Details/

        public ActionResult Details(int id = 0)
        {
            C_Images c_images = db.C_Images.Find(id);
            if (c_images == null)
            {
                return HttpNotFound();
            }
            return View(c_images);
        }

        //
        // GET: /Images/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Images/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(C_Images c_images)
        {
            if (ModelState.IsValid)
            {
                db.C_Images.Add(c_images);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(c_images);
        }

        //
        // GET: /Images/Edit/5

        public ActionResult Edit(int id = 0)
        {
            C_Images c_images = db.C_Images.Find(id);
            if (c_images == null)
            {
                return HttpNotFound();
            }
            return View(c_images);
        }

        //
        // POST: /Images/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(C_Images c_images)
        {
            if (ModelState.IsValid)
            {
                db.Entry(c_images).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(c_images);
        }

        //
        // GET: /Images/Delete/5

        public ActionResult Delete(int id = 0)
        {
            C_Images c_images = db.C_Images.Find(id);
            if (c_images == null)
            {
                return HttpNotFound();
            }
            return View(c_images);
        }

        //
        // POST: /Images/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            C_Images c_images = db.C_Images.Find(id);
            db.C_Images.Remove(c_images);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

my BeginForm  is like that
@using (Html.BeginForm("UploadImg","ImagesTaple", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    file :
    <input type="file" name="File" id="file" />

     <input type="submit" name="submet" value="upload" />

}

and my action is
 [HttpPost]
        public ActionResult UploadImg(HttpPostedFileBase image)
        {
            if (image.ContentLength > 0)
            {
                var FileFame = Path.GetFileName(image.FileName);
                var path = Path.Combine(Server.MapPath("~/Images/"), FileFame);
                image.SaveAs(path);
            }
            return RedirectToAction("Create");
        }

now when i press my submet button
i get this error mesage
Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /ImagesTaple/UploadImg

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0

what is wrong in my code plz
thanx for your help

A: I just a misspelling, change ImagesTaple to ImagesTable

redpajama_set_name: RedPajamaStackExchange


text:
Q: 2 heads 5 flips weighted coin - what is the probability? A coin is weighted to 1/12 heads and 11/12 tails.
What is the probability you get exactly 2 heads in 5 coin flips?
I think it's:
(Probability of 2 heads) * (Probability of 3 tails) * (number of ways this can occur)
= (1/12 * 1/12) * (11/12 * 11/12 * 11/12) * (5!/(3!*2!))
= 0.05348990484

A: As has been stated in the comments, your calculation is correct.


text: Q: how to read mac address of cellphone thats unavailable in android studio I have written some codes in android studio  and I Can Read the Mac address but the problem is when the mac address of  Cellphone is Unavailble  an blutooth address is Unavailble too .... so What Can I read Mac address in this situation ?


text:
Q: is it not possible to define two queries in a function of zend frame work controller i am new to zend frame work need two mysql queries ca be define in a function of zend controller but it showing
error message as Message: SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty
public function addisplayAction()
  {

    $registry = Zend_Registry::getInstance();
$DB = $registry['DB'];

   $sql = "SELECT cateno,catename,image FROM hl_category ORDER BY`hl_category`.`cateno` ASC LIMIT 0 , 42";
      $result = $DB->fetchAssoc($sql);
    $sql1 = mysql_query("select * from ad where cid=8");
   $result1 = $DB->fetchAssoc($sql1);
  $this->view->assign('title','Member List');
      $this->view->assign('description','Below, our members:');
       $this->view->assign('datas',$result);
  $this->view->assign('datas1',$result1);

A: OMG!!!! You are using Zend framework and put in your code mysql_query() ???? :D
You need to use the Zend_Db...
http://framework.zend.com/manual/1.11/en/zend.db.html


text:
Q: Efficient algorithm to compute resultants of sparse polynomials? Consider two polynomials $f,g\in\mathbb{F}_2$ of degree $O(2^n)$, with the property that they are extremely sparse (say, only $O(n)$ of the coefficients are non-zero). Is there a way to calculate their resultant that does not involve an exponential computation in $n$? The Sylvester matrix would be very structured (more than it is already), but I don't know if there are methods to exploit this structure to compute its determinant.
In a more general context, I'm using the resultant to check if $f$ and $g$ share a root. Is there another method to check this, considering the sparsity property?

A: See the oevre of I. Emiris:
Emiris, Ioannis Z.; Pan, Victor Y., Improved algorithms for computing determinants and resultants, J. Complexity 21, No. 1, 43-71 (2005). ZBL1101.68981.
Jeronimo, Gabriela; Sabia, Juan, Sparse resultants and straight-line programs,  ZBL06825747.


text:
Q: Git: What's the best practice to "git clone" into an existing folder? I have a working copy of the project, without any source control meta data. Now, I'd like to do the equivalent of git-clone into this folder, and keep my local changes.
git-clone doesn't allow me to clone into an existing folder. What is the best practice here?

A: This can be done by cloning to a new directory, then moving the .git directory into your existing directory.
If your existing directory is named "code".
git clone https://myrepo.com/git.git temp
mv temp/.git code/.git
rm -rf temp

This can also be done without doing a checkout during the clone command; more information can be found here.

A: git init
git remote add origin git@github.com:<user>/<repo>.git
git remote -v
git pull origin master

A: Using a temp directory is fine, but this will work if you want to avoid that step. From the root of your working directory:
$ rm -fr .git
$ git init
$ git remote add origin your-git-url
$ git fetch
$ git reset --mixed origin/master

A: Lots of answers already to do it the way that the OP asked. But it worth noting that doing it the opposite way around is far simpler:
git clone repo-url tmp/
cp -R working/ tmp/

You now have the desired target state - fresh clone + local-changes.

A: I'd git clone to a new directory and copy the content of the existing directory to the new clone.

A: To clone a git repo into an empty existing directory do the following:
cd myfolder
git clone https://myrepo.com/git.git .

Notice the . at the end of your git clone command. That will download the repo into the current working directory.

A: Don't clone, fetch instead. In the repo:
git init
git remote add origin $url_of_clone_source
git fetch origin
git checkout -b master --track origin/master # origin/master is clone's default

Then you can reset the tree to get the commit you want:
git reset origin/master # or whatever commit you think is proper...

and you are like you cloned.
The interesting question here (and the one without answer): How to find out which commit your naked tree was based on, hence to which position to reset to.

A: This is the Best of all methods i came across
Clone just the repository's .git folder (excluding files as they are already in existing-dir) into an empty temporary directory

*

*git clone --no-checkout repo-path-to-clone existing-dir/existing-dir.tmp //might want --no-hardlinks for cloning local repo

Move the .git folder to the directory with the files.
This makes existing-dir a git repo.

*mv existing-dir/existing-dir.tmp/.git existing-dir/
Delete the temporary directory

*rmdir existing-dir/existing-dir.tmp

*cd existing-dir
Git thinks all files are deleted, this reverts the state of the repo to HEAD.
WARNING: any local changes to the files will be lost.

*git reset --mixed HEAD

A: The following i did, to checkout master branch in an existing directory:
git init
git remote add origin [my-repo]
git fetch
git checkout origin/master -ft

A: git clone your_repo tmp && mv tmp/.git . && rm -rf tmp && git reset --mixed

A: There are two approaches to this. Where possible I would start with a clean folder for your new git working directory and then copy your version of things in later. This might look something like*:
mv $dir $dir.orig
git clone $url $dir
rsync -av --delete --exclude '.git' $dir.orig/ $dir/
rm -rf $dir.orig

At this point you should have a pretty clean working copy with your previous working folder as the current working directory so any changes include file deletions will show up on the radar if you run git status.
On the other hand if you really must do it the other way around, you can get the same result with something like this:
cd $dir
git clone --no-checkout $url tempdir
mv tempdir/.git .
rmdir tempdir
git reset --mixed HEAD

Either way, the first thing I would do is run something like git stash to get a copy of all your local changes set aside, then you can re-apply them and work through which ones you want to get committed.
* Both examples assume you start out on the shell in the parent directory of your project.

A: For reference, from the Gitlab Commandline instruction:
Push an existing folder
cd existing_folder
git init
git remote add origin <url>
git add .
git commit -m "Initial commit"
git push -u origin master

Or Push an existing Git repository
cd existing_repo
git remote rename origin old-origin
git remote add origin <url>
git push -u origin --all
git push -u origin --tags

A: Usually I will clone the initial repository first, and then move everything in the existing folder to the initial repository. It works every time.
The advantage of this method is that you won't missing anything of the initial repository including README or .gitignore.
You can also use the command below to finish the steps:
$ git clone https://github.com/your_repo.git && mv existing_folder/* your_repo

A: You can do it by typing the following command lines recursively:
mkdir temp_dir   //  Create new temporary dicetory named temp_dir
git clone https://www...........git temp_dir // Clone your git repo inside it
mv temp_dir/* existing_dir // Move the recently cloned repo content from the temp_dir to your existing_dir
rm -rf temp_dir // Remove the created temporary directory

A: Just use the . at the end of the git clone command (being in that directory), like this:
cd your_dir_to_clone_in/
git clone git@github.com/somerepo/ .

A: if you are cloning the same repository, then run the following snippet through the existing repository
git pull origin master

A: If you are using at least git 1.7.7 (which taught clone the --config option), to turn the current directory into a working copy:
git clone example.com/my.git ./.git --mirror --config core.bare=false

This works by:

*

*Cloning the repository into a new .git folder

*--mirror makes the new clone into a purely metadata folder as .git needs to be

*--config core.bare=false countermands the implicit bare=true of the --mirror option, thereby allowing the repository to have an associated working directory and act like a normal clone

This obviously won't work if a .git metadata directory already exists in the directory you wish to turn into a working copy.


text:
Q: function composition type inference in haskell In haskell, the type of (.) function is:
(.) :: (b -> c) -> (a -> b) -> a -> c

And the type of (.) (.) is:
(.) (.) :: (a -> b -> c) -> a -> (a1 -> b) -> a1 -> c

I am not able to deduce the result, how is this done?

A: (.) :: (b -> c) -> (a -> b) -> a -> c

Let's go through it. First thing this function takes is (b -> c) (so a function from b to c), cool. By adding a pair of (redundant) parentheses:
(.) :: (b -> c) -> ((a -> b) -> a -> c)
       ^-- I am b'  ^-- I am c'   -- (b' and c' not to have name clash)

That first part, we gave to the function (i.e. has been taken care of):
(.) (.) :: (a -> b') -> a -> c'
-- after substituting stuff (b' and c')
(.) (.) :: (a -> (b -> c)) -> a -> ((a1 -> b) -> a1 -> c)
                                    ^-- of course a1 /= a
-- you could eliminate redundant parentheses
(.) (.) :: (a -> b -> c) -> a -> (a1 -> b) -> a1 -> c
-- wee

I hope this settles it. Main point is: type inference is easy to 'get' and once you get it is only a matter of substitution to reach what ghci automagically infers.
ot: we could call this quizzical operator boobs.


text:
Q: Using WSGI with a specific python binary Can wsgi be configured to use a specific python executable?
When using the WSGIPythonHome directive, you supply a prefix. What does mod_wsgi look for in that directory? I assume it looks in the supplied directory for the executable ../bin/python . If the executable is called, say, python26, will it be found? I assume not.
(Details: The system python on the server I'm using is 2.4 and I'm trying to upgrade. I don't have sudo on the machine, and I'm trying to work with my admin on this... I'm not sure why we can't just install the new version of python in /opt or /usr/local with the standard directory structure, so we can use WSGIPythonHome in the normal way, which is what I would do. I'm just trying to work with him and be agreeable.)

Alternatively, does mod_wsgi just use the python binary it was compiled against? So if we recompile mod_wsgi with the new version of python, will it always use that one?

A: Yes, you must recompile mod_wsgi from source code against version/installation of Python you wish to use. See:
http://code.google.com/p/modwsgi/wiki/InstallationIssues#Multiple_Python_Versions
and:
http://code.google.com/p/modwsgi/wiki/InstallationIssues#Unable_To_Find_Python_Shared_Library


text:
Q: PHP - exporting data to excel I have some data that I need to export to excel.  Right now it exports to some other type of file, that I am able to open and read with notepad, but not excel.
Here is the code:
<?php
    header("Content-Disposition: attachment; filename=\"ISBN\"");
    header("Content-Type: application/vnd.xls");
        // filename for download
function output($data){

    //print_r($data);
    $str = preg_replace("/\t/", "\\t", $data);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';

    $filename = "nonprofitdata" . date_default_timezone_set('Ymd') . ".xls";

        $flag = false;
        foreach($data as $row) {
            if(!$flag) {
                // display field/column names as first row
                echo implode("\t", array_keys($row)) . "\r\n";
                $flag = true;
            }
        array_walk($row, 'cleanData');
        echo implode("\t", array_values($row)) . "\r\n";
        }
        exit;
}
?>

How can I update this so that it will export to a file type that Excel can read?


text:
Q: What is the correct way to implement a 'party model' with the various roles that parties play? One of the programs we're working on is growing and we're at a stage where we can revisit the existing database and spend time 'trying to get it right'. One of the things we're looking at is the data model and how we model 'parties' among other things. We have made do until now with determining customer details from transaction records, but now we want to store more detail and would like to combine the common data we have for staff, suppliers and members, etc.
Each party is either an individual or a group, but can also have one or more roles such as employer, client, member, etc. I realise that various parties in our model don't exist without a relationship to another party (staff need an employer, a customer needs a company to buy from, members need a club, etc) and since I don't want people to add silly relationships like 'employer-client' or 'member-subcontractor', I now have a table called relationship which predefines which roles can go with each other. I haven't seen this before and I wonder, are we on the right track? (Here is a simplified EER diagram to show how we think this might be represented)

I have looked at various documentation on the principles of the party model, but I haven't been able to find any (open source) examples of how it actually looks in pratice. Can anyone recommend a source (preferably in MySQL) or share your experience on how to implement it, perhaps with the table structure or application code?

A: This SO answer has an implementation of parties.
Another answer, applying this pattern to articles and blog posts and stories has explanations of some of the subtle points in the comments.


text:
Q: How do I retrieve photos from a Facebook group using the GraphAPI? I would like to retrieve photos from a facebook group using the GraphAPI. Based on FB Docs I don't see any connections to photos. I would like to get the photos and the users who uploaded them.

A: Ive been digging a bit in the same issue.
We have a group album which is has this url
https://www.facebook.com/media/set/?set=oa.10150651435446985
So the ID seems to be oa.10150651435446985
Another empty album gets album gets the set-id oa.10150652583791985
A note in the same group id 10150652589396985
Notice the similarity in ID's.
The direct link: http://facebook.com/10150651435446985 works to go to the album.
The album is created by user 1128233556 and the groupid is 184760601984.
Other, individual (not in an album) group photos are in "set" o.184760601984 where the digit represents the group id.
So what does "o" and "oa" stand for? a=album, o=?
Pictures have the following URL: https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/s720x720/420015_3293876662264_1128233556_33234982_110700674_n.jpg
420015_3293876662264_1128233556_33234982_110700674
??????_PHOTOID_______USER_______????_____?????????

Who can make something out of al that?

A: I have the same problem / here is my partial answer, which remains kind of hack :
one can retrieve photos posted on a group via the FQL group.stream or the GraphAPI group.feed (playing around with the facebook graphApi explorer or the fql query/multiquery test console).
This way you can retrieve all needed information, included a valid id to retrieve the photo, and one to retrieve the object from the graph.
BUT, this is only valid for individual photos.
since my previous answer was deleted, i won't repost it here, but remind that my similar problem is detailed in this thread FQL or GraphAPI unable to retrieve PHOTO ALBUM or VIDEO posted on a GROUP , which, if ever solved, might even as well help people for this very problem here.
Thomas

A: Graph API:
http://graph.facebook.com/GROUP_ID/?fields=name,description,albums
return
{
  "name": "Group name",
  "description": "Group description",
  "id": "GROUP_ID",
  "albums": {
    "data": [
      {
        "id": "GROUP_ALBUM_ID",
        "name": "GROUP_ALBUM_NAME",
        "link": "GROUP_ALBUM_LINK",
        "created": 1352388257,
        "modified": 1352388257,
        "cover_pid": 444427468954616,
        "count": 22
      }
    ],
    "paging": {
      "next": "https://graph.facebook.com/GROUP_ID/albums?limit=25&offset=25"
    }
  }
}

and next query
http://graph.facebook.com/GROUP_ALBUM_ID/photos?fields=picture,source,name&type=uploaded

A: I don't think Albums in groups R treated like albums on Profile pages. The pics have aid ="0" Even if they are part of albums.
I used The Image below:
https://www.facebook.com/photo.php?fbid=10151350034089218 is the link to the image. And you can guess where I got the object_ID.
In this example 10151350034089218 is the object_ID for an image in an album for my group "T_Group" The link to the group is https://www.facebook.com/groups/217697621700825/.
You can then run the FQL query
SELECT aid
  FROM photo
 WHERE object_id = 10151350034089218

you'll get
aid
====
0

Even though it is part of an album "Hugh Laurie".
I tried the same FQL query with images in albums on my profile and they always returned an aid with some Number other than 0.
I plan on posting to Facebook bugs, I hope I get a fix. Unless its running as intended.
I tried:
SELECT pid
  FROM photo_tag
 WHERE subject =217697621700825

...and I got PIDs to photos posted to the group page not images in albums.

A: I wish I had found a more direct method, but this appears to have promise:
get  /me/groups  or /me?fields=groups  to get the groups ids.
From that,  get {group_id}/feed?type=photo  This returns just the photos from the feed, but all you really get (toward this goal) is the photo's id  (returned as object_id).
Then for each photo you can  get /{object_id} which returns all the links to the various sizes of the image.
I did this research in Facebook Graph Explorer, so keep that in mind as you try to implement it.
Rob


text:
Q: Snowflake - Run Multiple SQL Queries at Once Let's PRETEND, I am using SQL Server, if I execute the following queries, they will go one after the next:
select top 10 * from table_1;
go
select top 10 * from table_2;
go
select top 10 * from table_3;
go

Snowflake does not have a go command, and it appears to only execute the last statement only.
Is there a way to make all 3 (or whatever my number is) run instead of just the last one running?
Edit #1:
I am using the Snowflake Web UI

A: There is no go command in snowflake. however, you can execute multiple queries at the same time from the WEB UI of the snowflake. Please find the sql below
select top 10 * from table_1;
select top 10 * from table_2;
select top 10 * from table_3;
Select all the above queries and click on execute. Each query will have the query id and result set to view.

A: Use a tool like DBVisualizer that lets you run a script and see the results of all the queries executed, each in their own tab.

A: You can make use of SnowSQL and submit use the command below, that will submit the queries asynchronously:
snowsql -o log_level=DEBUG -q "select top 10 * from table_1;> select top 10 * from table_2;> select top 10 * from table_3;"


text:
Q: Drag an ImageView to a particular place on a screen in android I am implementing Drag and Drop functionality with ImageView in android, but I received an error every time when I want to touch the view. I don't know how this problem could be solved? Please suggest me for the right solution regarding the same.
Error-Stack:
01-16 18:32:31.349: E/AndroidRuntime(3157): FATAL EXCEPTION: main
01-16 18:32:31.349: E/AndroidRuntime(3157): java.lang.IllegalArgumentException: Given view not a child of com.SpeachTreat.common.DragLayer@44c35318
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.view.ViewGroup.updateViewLayout(ViewGroup.java:1876)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.SpeachTreat.common.DragLayer.onDrop(DragLayer.java:90)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.SpeachTreat.common.DragController.drop(DragController.java:446)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.SpeachTreat.common.DragController.onTouchEvent(DragController.java:424)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.SpeachTreat.common.DragLayer.onTouchEvent(DragLayer.java:63)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.view.View.dispatchTouchEvent(View.java:3766)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:897)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1676)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1112)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.app.Activity.dispatchTouchEvent(Activity.java:2086)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1660)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1785)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.os.Looper.loop(Looper.java:123)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at android.app.ActivityThread.main(ActivityThread.java:4627)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at java.lang.reflect.Method.invokeNative(Native Method)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at java.lang.reflect.Method.invoke(Method.java:521)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
01-16 18:32:31.349: E/AndroidRuntime(3157):     at dalvik.system.NativeStart.main(Native Method)

Xml:
<?xml version="1.0" encoding="utf-8"?>
<com.SpeachTreat.common.DragLayer
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:launcher="http://schemas.android.com/apk/res/com.android.launcher"
android:background="#ffffff"
    android:id="@+id/drag_layer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:layout_centerVertical="true"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" android:background="@drawable/header_back" android:orientation="vertical">

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/logo" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/header_text" />

        </LinearLayout>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:layout_marginTop="10dip">

        <FrameLayout
            android:id="@+id/frameLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" android:background="@drawable/start_playing_with_outline4">

            <ImageView
                android:id="@+id/img_Treat_Character"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/cute_animal_big3" android:layout_gravity="center_vertical|center_horizontal"/>

        </FrameLayout>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:layout_marginTop="10dip">

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:orientation="vertical" android:background="@drawable/select_your_treat_with_outline">

             <LinearLayout
                android:id="@+id/linearLayout4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:layout_marginTop="10dip">

                <ImageView
                    android:id="@+id/img_treat1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="30dip"/>
                <ImageView
                    android:id="@+id/img_treat2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="10dip"/>
                <ImageView
                    android:id="@+id/img_treat3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="10dip"/>
                <ImageView
                    android:id="@+id/img_treat4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="10dip"/>
                <ImageView
                    android:id="@+id/img_treat5"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="10dip"/>

            </LinearLayout>
             <LinearLayout
                android:id="@+id/linearLayout5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:layout_marginTop="10dip">

                <ImageView
                    android:id="@+id/img_treat6"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="30dip"/>
                <ImageView
                    android:id="@+id/img_treat7"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="10dip"/>
                <ImageView
                    android:id="@+id/img_treat8"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="10dip"/>
                <ImageView
                    android:id="@+id/img_treat9"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="10dip"/>
                <ImageView
                    android:id="@+id/img_treat10"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/treat1" android:layout_marginLeft="10dip"/>

            </LinearLayout>

        </LinearLayout>

    </RelativeLayout>
 <RelativeLayout
        android:id="@+id/relativeLayout4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:layout_marginTop="10dip">

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="wrap_content"
         android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" android:layout_marginTop="10dip">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/selectanewcharacter_button" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/end_game_button" android:layout_marginTop="10dip"/>

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/green_button_with_shadow" android:layout_marginTop="20dip" android:layout_marginLeft="10dip"/>

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/red_button_with_shadow" android:layout_marginTop="20dip" android:layout_marginLeft="10dip"/>

    </LinearLayout>
</RelativeLayout>
</LinearLayout>
</com.SpeachTreat.common.DragLayer>

DragLayer:
public class DragLayer extends MyAbsoluteLayout
    implements DragSource, DropTarget
{
    DragController mDragController;

    /**
     * Used to create a new DragLayer from XML.
     *
     * @param context The application's context.
     * @param attrs The attribtues set containing the Workspace's customization values.
     */
    public DragLayer (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setDragController(DragController controller) {
        mDragController = controller;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return mDragController.dispatchKeyEvent(event) || super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return mDragController.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return mDragController.onTouchEvent(ev);
    }

    @Override
    public boolean dispatchUnhandledMove(View focused, int direction) {
        return mDragController.dispatchUnhandledMove(focused, direction);
    }

public void onDropCompleted (View target, boolean success)
{
    toast ("DragLayer2.onDropCompleted: " + target.getId () + " Check that the view moved.");
}

public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
        DragView dragView, Object dragInfo)
{
    View v = (View) dragInfo;
    toast ("DragLayer2.onDrop accepts view: " + v.getId ()
          + "x, y, xO, yO :" + new Integer (x) + ", " + new Integer (y) + ", "
          + new Integer (xOffset) + ", " + new Integer (yOffset));

    int w = v.getWidth ();
    int h = v.getHeight ();
    int left = x - xOffset;
    int top = y - yOffset;
    DragLayer.LayoutParams lp = new DragLayer.LayoutParams (w, h, left, top);
    this.updateViewLayout(v, lp);
}

public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
        DragView dragView, Object dragInfo)
{
}

public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
        DragView dragView, Object dragInfo)
{
}

public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
        DragView dragView, Object dragInfo)
{
}
public boolean acceptDrop(DragSource source, int x, int y, int xOffset, int yOffset,
        DragView dragView, Object dragInfo)
{
    return true;
}
public Rect estimateDropLocation(DragSource source, int x, int y, int xOffset, int yOffset,
            DragView dragView, Object dragInfo, Rect recycle)
{
    return null;
}
public void toast (String msg)
{
    if (!SpeachTreatActivity.Debugging) return;
    Toast.makeText (getContext (), msg, Toast.LENGTH_SHORT).show ();
} // end toast

My Activity:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        img_character = (ImageView)findViewById(R.id.img_Treat_Character);
        img_treat1 = (ImageView)findViewById(R.id.img_treat1);
        img_treat2 = (ImageView)findViewById(R.id.img_treat2);
        img_treat3 = (ImageView)findViewById(R.id.img_treat3);
        img_treat4 = (ImageView)findViewById(R.id.img_treat4);
        img_treat5 = (ImageView)findViewById(R.id.img_treat5);
        img_treat6 = (ImageView)findViewById(R.id.img_treat6);
        img_treat7 = (ImageView)findViewById(R.id.img_treat7);
        img_treat8 = (ImageView)findViewById(R.id.img_treat8);
        img_treat9 = (ImageView)findViewById(R.id.img_treat9);
        img_treat10 = (ImageView)findViewById(R.id.img_treat10);

        img_treat1.setOnLongClickListener(this);
        img_treat2.setOnLongClickListener(this);
        img_treat3.setOnLongClickListener(this);
        img_treat4.setOnLongClickListener(this);
        img_treat5.setOnLongClickListener(this);
        img_treat6.setOnLongClickListener(this);
        img_treat7.setOnLongClickListener(this);
        img_treat8.setOnLongClickListener(this);
        img_treat9.setOnLongClickListener(this);
        img_treat10.setOnLongClickListener(this);
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
    @Override
    public boolean onLongClick(View v) {
        // TODO Auto-generated method stub
         trace ("onLongClick in view: " + v);

            // Make sure the drag was started by a long press as opposed to a long click.
            // (Note: I got this from the Workspace object in the Android Launcher code.
            //  I think it is here to ensure that the device is still in touch mode as we start the drag operation.)
            if (!v.isInTouchMode()) {
                Toast.makeText(this, "isInTouchMode returned false. Try touching the view again.", Toast.LENGTH_SHORT).show();
               return false;
            }
            return startDrag (v);
    }
    public void trace (String msg)
    {
        if (!Debugging) return;
        Log.d ("SpeachTreatActivity", msg);
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    public boolean startDrag (View v)
    {
        // Let the DragController initiate a drag-drop sequence.
        // I use the dragInfo to pass along the object being dragged.
        // I'm not sure how the Launcher designers do this.
        Object dragInfo = v;
        mDragController.startDrag (v, mDragLayer, dragInfo, DragController.DRAG_ACTION_MOVE);
        return true;
    }


text:
Q: Very weird entry in apache error_log. Is this an exploit fishing expedition? I was in the middle of tailing my error log for apache when this massive chunk came through. Never seen anything like it before. The IP maps out to RIPE Network Coordination Centere, with a PO box
link here
Is this anything i should dig into further? I couldn't find much in regards to this when googling, other than RIPE is what appears to be an ISP.
[Tue Mar 15 21:34:44.775251 2016] [core:error] [pid 22280] (36)File name too long: [client 93.113.125.12:44444] AH00036: access to /we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages failed (filesystem path '/var/www/html/we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages_we_are_looking_for_not_found_pages')

A: I just received this request as well from the same IP. I don't see many others talking about it, so I guess it's new.
I assume it is a bot looking for insecure common management pages, and the actual request text is sort of a joke to the webmaster viewing the logs.
The script making these requests is doing exactly what the request URL says. It is sending requests to huge lists of IP addresses, IP address ranges, or even in some cases every IP address on the internet. It records whether or not the address returns with a status code - indicating that there is a web server running at that address.
It is unclear what's going to be done with this information. Maybe if they get a response they will put you on a list to be further probed. This is actually quite common.
These sorts of things are harmless unless you are using default passwords on some admin utility (wordpress, drupal, phpmyadmin, etc). If you start getting bombarded with these requests, you may want to employ the use of a more advanced hardware or software firewall, audit your publicly open ports, and maybe start restricting IP ranges.
http://who.is/whois-ip/ip-address/93.113.125.12
If this persists, you could always report the incident to the source's ISP.


text:
Q: mySQL limit the number of rows in a JOIN statement Suppose having the table containing the following data:
|id|product_id|date_time          |warehouse_id|city_id|
+--+----------+-------------------+------------+-------+
| 1|         1|2013-08-09 10:52:28|           1|      1|
| 2|         1|2013-08-09 10:52:28|           1|      2|
| 3|         1|2013-08-09 10:52:29|           1|      3|
| 4|         2|2013-08-09 10:52:28|           1|      1|
| 5|         2|2013-08-09 10:52:28|           1|      2|
+--+----------+-------------------+------------+-------+

is there any way on a mySQL JOIN query to only get one entry per product_id & warehouse_id (the latest by date_time)
ie:
SELECT * FROM xxxxx
JOIN a ON a.product_id=xxxx.product_id AND a.warehouse_id=xxxx.warehouse_id

I have tryied using a max(date_time) on JOIN but that of course will not give me the correct resultset
select * from xxxxx x
JOIN a ON a.product_id=x.product_id and a.warehouse_id=x.warehouse_id
JOIN (SELECT id, max(date_time) as date_time From a  group by a.product_id, a.warehouse ) a2 on a2.id=a.id

A: Just because you are asking for the maximum date does not mean that the id comes from that row.  MySQL chooses an arbitrary id because the column is not in an aggregation function and is not in the group by clause.  That the id would come from the row with the maximum is a common misconception in MySQL.  Such syntax is generally not permitted in other databases (your query is not standard SQL).
You need to do two things.  First, you need to do the join on product_id and warehouse_id, because those are the fields you are trying to get the maximum date for.  Second, you need to include the date_time in the on clause:
select *
from xxxxx x
JOIN a ON a.product_id=x.product_id and a.warehouse_id=x.warehouse_id
JOIN (SELECT product_id, a.warehouse_id, max(date_time) as date_time
      From a
      group by a.product_id, a.warehouse_id
     ) a2
    on a2.product_id = a.product_id and a2.warehouse_id = a.warehouse_id and
       a2.date_time = a.date_time;

EDIT:
If you want to do the join on id, you can use this trick:
select *
from xxxxx x
JOIN a ON a.product_id=x.product_id and a.warehouse_id=x.warehouse_id
JOIN (SELECT substring_index(group_concat(id order by date_time desc), ',', 1) as id
      From a
      group by a.product_id, a.warehouse_id
     )  a2
     on a2.id=a.id;

Do note, though, that this forced the type of id in the subquery to be a string, even if it is originally numeric.


text:
Q: Copy from Excel to Outlook - white cells behind topleft corner of image I am copying excel content from Excel to the Outlook Email Body, and unlike many other users my problem is not that cell formatting is messed up, but rather that when copying any of the images from excel, they are pasted into outlook with a white cell behind the image's top left corner.
Attached a sample image with how it looks in Excel and then in Outlook.

I have spent hours trying to solve this including:

*

*change the format of the image (PNG/JPG/BMP)

*play around with resolution, image compression, move-and-size-with-cells option, etc.

*tried to manually copy the range into the outlook email body VS copying it via a macro which converts the worksheet-range into a html string and generates the email directly from excel

The last option, where I used VBA to generate the email from excel directly, exhibits the exact some problem as a manual copy & paste from excel. The problem only occurs around the area of images and the cells that are touched by the topleft corner of the image, no matter if those cells are regular cells or merged.
This leads me to believe that this is either an issue with my images/object (I replaced all images with shapes and had the same issue, or its bug in MS Office in when it comes to handling the copy & paste process of content with objects.
Would love to hear some opinions of you guys, I am at the end of my wit.
Thank you!
Also, here the function I use for copying the range to outlook.
Excel VBA
Option Explicit

Private Function RngToEmail(rng As Range, eTo As String, eSubject As String)
    Dim wbThis As Workbook, wbNew As Workbook
    Dim tempFileName As String, imgName As String, newPath As String

    '~~> Do not change "Myimg". This will be used to
    '~~> identify the images
    Dim imgPrefix As String: imgPrefix = "Myimg"

    '~~> This is the temp html file name.
    '~~> Do not change this as when you publish the
    '~~> html file, it will create a folder Temp_files
    '~~> to store the images
    Dim tmpFile As String: tmpFile = "Temp.Htm"

    Set wbThis = Workbooks(rng.Parent.Parent.Name)
    Set wbNew = Workbooks.Add

    '~~> Copy the relevant range to new workbook
    rng.Copy wbNew.Worksheets("Sheet1").Range("A:A")

    newPath = wbThis.Path & "\"
    tempFileName = newPath & tmpFile

    '~~> Publish the image
    With wbNew.PublishObjects.Add(xlSourceRange, _
        tempFileName, "Sheet1", rng.Address, xlHtmlStatic, _
        imgPrefix, "")
        .Publish (True)
        .AutoRepublish = True
    End With

    '~~> Close the new file without saving
    wbNew.Close (False)

    '~~> Read the html file in a string in one go
    Dim MyData As String, strData() As String
    Dim i As Long
    Open tempFileName For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)

    '~~> Loop through the file
    For i = LBound(strData) To UBound(strData)
        '~~> Here we will first get the image names
        If InStr(1, strData(i), "Myimg_", vbTextCompare) And InStr(1, strData(i), ".Png", vbTextCompare) Then
            '~~> Insert actual path to the images
            strData(i) = Replace(strData(i), "Temp_files/", newPath & "Temp_files\")
        End If
    Next i

    '~~> Rejoin to get the new html string
    MyData = Join(strData, vbCrLf)

    '~~> Create the Email
    Dim OutApp As Object, OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    With OutMail
        .to = eTo
        .Subject = eSubject

        '~~> Set the body
        .HTMLBody = MyData

        '~~> Show the email. Change it to `.Send` to send it
        .Display
    End With

    '~~> Delete the temp file name
    Kill tempFileName
End Function

Sub Sample()
    RngToEmail ThisWorkbook.Sheets("FINAL").Range("A:F"), "someemail@someserver.com", "Some Subject"
End Sub

A: Do you insert picture to this cell? When testing on my Outlook 2016 version 1812, I also find the issue. The cell behind the picture would appear blank or wired when pasting to email body. I haven't found related official articles and I'm not familiar with VBA code.

However, we can choose to paste as a picture in Paste Options to avoid this.


text:
Q: How to make r shiny load a separate instance for each user, so as each user has their own global variables? I saw this post already
handling multiple users simulaneously in an R Shiny app
and I am aware that you can define anything inside of the shinyServer() expression to make it private to a single user's session. However, this limits my ability to define variables that depend on a reactive expression outside of a reactive context.
Reproducible example:
Assume I define ui to have a button "do"

server <- function(input, output, session) {

observeEvent(input$do, {
    data<- read.csv("data.csv",check.names=F,row.names=1)
  })

req(data) # doesn't work
matrix <- data    # PRODUCES ERROR, see below error

})

Error I get when doing this is, and this makes sense because I data is not defined yet:
Error in server(...) : object 'data' not found

I don't want to define matrix in a reactive context, because that would pose a tremendous headache to work with in my code later one as I would have to define MANY variables this way, and would have to access them reactively each time. I really want to avoid doing so if possible.
What I have instead been doing, and it has been working, is define everything (reactive or not) in a reactive context so that I dont have a single line of code outside of a reactive function (not variables, I am trying everything to avoid those). This, however, does not allow me to access variables outside said functions. So what do I do? I use global variables even though its terrible coding practice (I know) but it saves me a big headache and seems to be working.
MY ONLY CONCERN is that users can access each other's data since data is defined globally!!!
However, I have heard from someone that I can allow each user to create their own instance and therefore not share their global variables with anyone else.
If someone can tell me how to do this that would be great. I know this isn't good for scalability, but I am only looking for a temporary solution right now and will probably switch all my variables to be reactive eventually.
Thanks so much


text:
Q: Angularjs | ng-message not showing error message when load html from directive by using $compile I am creating dynamic from through ng-repeat from json.
my form.html
    <form    name="userForm" >

    <accordion >
            <accordion-group heading="{{key}}"  is-open="true">

                       <field-directive field="field">
                        </field-directive>

            </accordion-group>
  </accordion>

    </form>

so basically i am loading each type of field (textbox/radio/dropdown/email etc) html trough loop via directive.
I am loading these small HTML by using $compile and linker. Everything is working good even validation also. I am able to enable/disable submit button based on form validation except ng-message . if i not use directive like this
    <form name="userForm" >

    <accordion >
            <accordion-group heading="{{key}}"  is-open="true">

                                <md-input-container >
                                          {{field.field_title}}
                                          <input ng-model="field.field_value" name="{{field.field_id}}" type="text"
                                            ng-required="true" md-maxlength="9" >

Your name is too long.

Your name is required.

                                 </md-input-container>

                                <md-input-container >
                                          {{field.field_title}}
                                          <input ng-model="field.field_value" name="{{field.field_id}}" type="text"
                                            ng-required="true" md-maxlength="9" >

Your name is too long.

Your name is required.

                                 </md-input-container>

            </accordion-group>
  </accordion>

    </form>

everything is working fine including ng-message. I can see error message also.
 What is the issue with ng-message if i use directive . Please help.

A: Probably late answer but you can do
var element1 = angular.element(your_html_fragment);
... logic to append element1 in somewhere

after this
$compile(element1)(scope) in your directive this should do it.
The sequence of angular.element and $compile is important.


text:
Q: Desktop theme for Android tablets I am using a separate theme for mobile devices but I still want to present the desktop theme for Android tablets.
here's my matched expressions for the exception
iPhone|iPod|BlackBerry|Palm|Googlebot-Mobile|mobile|mobi|Windows Mobile|Safari Mobile|Android|Opera Mini

and in iPad it shows the desktop theme as it should but on Android tablets i'm still getting the mobile theme.

A: I saw that the user agent string for Android Tablets contained "Safari" whereas the string for Android cell phones has "Mobile Safari" so I just targeted "Mobile Safari" for my mobile theme and now all tablets get the desktop theme.
Here's my final string to target only mobile devices, not tablets
iPhone|iPod|BlackBerry|Palm|Googlebot-Mobile|mobi|Windows Mobile|Safari Mobile|Mobile Safari|Opera Mini

Notice that I removed "Android" from that string.


text:
Q: Prove or disprove "The set of points at which a sequence of real valued measurable functions converges to a point of [0,1] is measurable. I know the following is true:
The set of points at which a sequence of real valued measurable functions converges (in R) is a measurable set. (This is proved by the definition of "Cauchy"="convergence")
However, I have no clue at all if this is true "The set of points at which a sequence of real valued measurable functions converges to a point of [0,1] is measurable."
If [0,1] were a countable set, then the statement would be correct. But it is uncountable, so I guess the statement is wrong?
Any help would be appreciated!

A: You know the set $C=\{x\in\mathbb R\mid (f_n(x))_n\ \text{converges}\}$ is measurable. Try to intersect $C$ with
$$
\bigcap_{i\geqslant1}\bigcup_{n\geqslant1}\bigcap_{k\geqslant n}\{x\in\mathbb R\mid -1/i\leqslant f_k(x)\leqslant1+1/i\}.
$$


text:
Q: Javascript in GSP files broken in Grails 3 I've undertaken the arduous process of upgrading a project from Grails 2 to Grails 3. I've survived mostly intact so far, but I've hit a pretty mystifying roadblock: the Javascript that worked perfectly on the Grails 2 version appears to be completely ignored in the Grails 3 version.
Example: I have a page with a single field that is required to be filled out before the form can be submitted. Below is the code for the whole page - the javascript is at the end:

    <meta name="layout" content="main">

    <g:render template="worksheet/nav"/>

            <g:form class="form-horizontal" url="[action:'worksheet']" id="form" onsubmit="return validateForm()">
                <fieldset>

                            Client *

                            <g:select name="client" class="input-medium" from="${clients}" noSelection="['':'']" value="${map.client?.name}"/>

                        <g:hiddenField name="_eventId" value="next"/>

                            <g:link event="skip" class="btn btn-large">Skip</g:link>
                            <button type="submit" class="btn btn-large btn-primary">Next</button>

                </fieldset>
            </g:form>

<g:javascript>
$("#form").on('submit', function() {
    $('#errors').html('');
    $('#errors').hide();
});
$("#form").validate({
    onfocusout: false,
    onkeyup: false,
    onclick: false,
    rules: {
        client: "required"
    },
    messages: {
        client: "Please select a client"
    },
    errorElement: "div",
    errorPlacement: function (error, element) {
        $('#errors').append(error);
        $('#errors').show();
    }
});

In Grails 2, this works as expected - the page will verify a selection has been made before submitting the form. But in Grails 3, nada - the form gets submitted and the system moves on to the next page even if the user hasn't picked anything. I checked the source code after compiling and the JS is there, so I'm not sure why it's getting ignored. Any ideas?
Some additional context: I'm also upgrading JQuery from 1.8.0 to 2.2.0, and Bootstrap from 2.0.x to 3.3.6.


text:
Q: IBM Worklight 6.0.0.1 - Push-enabled app does not open when tapping a notification I have implemented push notifications support as provided in the IBM Worklight Getting Started training module:
http://public.dhe.ibm.com/software/mobile-solutions/worklight/docs/v600/09_04_Push_notifications.pdf
My problem is when the application is in the background or closed, and I receive a push notification. I click on the notification but nothing happens - the notification disappears and the application doesn't launch.
I'm using worklight 6.0.0.1 and testing on Android OS v4.1 and v2.3.
Did I miss some configuration?

A: Take a look at the approved answer from this question: IBM Worklight 5.0.6.1 - Not getting Push Notifications when phone/app is closed

*

*Make sure that you did not do the same error as mentioned in it.

*Please also add the relevant push implementation of your app to the question.


text:
Q: How to open select menu using jquery / javascript I want to open select menu using javascript/ jquery. Is this possible. Can createEvent in javascript is useful for this pus. fiddle
$('span').click(function(){
$('select').trigger('click')
})


text:
Q: PowerApps Sort and Filter I don't see a similar question based on a quick search, so I'll ask a newbie question about PowerApps:
I have a SP Online list relating to incoming parts (raw materials) and I'm creating a new form for our Fork-truck drivers to use. The purpose of this form is to alert the drivers if the parts need to be inspected by our quality lab. Two of the fields in the list are Active and ItemNumber. I want to filter the parts to show only those parts (items) which are "active=yes" and then sort the resulting set based on the ItemNumber in ascending order.
Here's the curve: the form contains a text input where the driver begins typing in a part number, then the gallery dynamically displays the ItemNumber with this formula in the Text property: ThisItem.'RM-item-Number'  I did this to condense the result set (as the driver types) so that they don't have to scroll through several hundred parts.

That works, however, there are situations (only a few, but they do exist) where there are multiple entries for an ItemNumber because we have multiple vendors supplying the material. I've found that when there are multiple vendors, the ItemNumbers aren't sorting properly (as shown below).

How do I filter and sort this correctly?
Thanks!
gpence

A: I'm not sure why the items aren't sorting consistently, but a sort can be applied as part of the items property:
SortByColumns('Inbound RM Inspection', "Title")

Of course, this would sort, but wouldn't filter, so you'll need to nest the functions:
SortByColumns(
  Search('Inbound RM Inspection', SearchBox.Text, "Title"),
  "Title")

The above will search for the matching items, and then pass the result to the SortByColumns function. See here for another example.


text:
Q: how to retrieve the ip of openshift private docker registry when started through minishift and accessed from machine where minishift is present I have installed openshift through minishift on mac. I am able to run the command docker login -u developer -p <pass> 172.30.1.1:5000 from the shell where openshift is running. However I need to run the same login command from host mac machine and don't know the ip to use.
The openshift console can be accessed from https://192.168.64.3:8443.
The command minishift openshift registry returns an error.
I can run the oc commands from mac host machine.

A: I think you better login to docker daemon: https://docs.okd.io/latest/minishift/using/docker-daemon.html instead that login to the internal registry directly. Once you've done you can use docker client as it is bound to your minishift environment.


text:
Q: Python Flask alongside with node.js I have a Python Flask application and I'm about to start implementing websockets and I wan't to have all this done in node.js of several reasons;
Node.js use less overhead and I like the idea of separating the more more heavy logic from the more traffic intensive parts.
node.js seem to have better support for websockets and being more mature.
And I might later on move the node.js to a separate server if needed for performance.
My question is what would the best practice, to build up the communication between my Flask application and Node.js? Is this a bad idea to set it up like this?

A: Unless you have a really good reason to use both, and you've verified through some benchmarking that using both is necessary, I wouldn't do it. It adds a lot of complexity (code duplication, different libraries working differently in different languages, etc) for questionable benefit.
WebSocket is an issue in Flask, but you can use Juggernaut to handle it easily.


text:
Q: Element with gradient and border I have html like this

Here goes some content
Here goes some content
Here goes some content
Here goes some content
Here goes some content
Here goes some content
Here goes some content
Here goes some content
Here goes some content

And css like this
.bottom-content{
  width: 100%;
  height: 19px;
  border-top: 1px rgba(red, 0.2);
  box-shadow: 0 -19px 19px 0 blue !important;
  opacity: .6;
}

The problem is that has to be some kind of gradient and border, this way entire element is in opacity
This is how border or bottom gradient should look like

A: This sounds a good job for a blur filter:

.bottom-content {
  padding:10px;
  position:relative;
  z-index:0;
}
.bottom-content::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:lightblue;
  filter:blur(6px);
}

  Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content

Like below for only border:

.bottom-content {
  padding:10px;
  position:relative;
  z-index:0;
}
.bottom-content::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  border:8px solid lightblue;
  filter:blur(5px);
}

  Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content

And it also work for only one border:

.bottom-content {
  padding:10px;
  position:relative;
  z-index:0;
}
.bottom-content::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  border-bottom:8px solid lightblue;
  filter:blur(5px);
}

  Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content Here goes some content


text:
Q: How to find out master product of simple product? How can I find out, if a simple product is part of a configurable product and then get the master product? I need this for the product listing.
Just found out:
$_product->loadParentProductIds();
$parentIds = $_product->getParentProductIds();

A: Let's say that you have your simple product's Product ID.
To get all the parent configurable product IDs of this simple product, use the following code:-
<?php
$_product = Mage::getModel('catalog/product')->load(YOUR_SIMPLE_PRODUCT_ID);
$parentIdArray = $_product->loadParentProductIds()
                 ->getData('parent_product_ids');
if(!empty($parentIdArray)) {
    // currently in the master configurable product
    print_r($parentIdArray); // this prints all the parent product IDs using your simple product.
}
?>

I suppose this should get you going.

A: After version 1.4.2.0 the loadParentProductIds() and getParentProductIds() methods are deprecated. Don't ask me why. Personally I kind of liked those methods. So I've reintroduced them to my local Mage classes. This is how:
Copy
app/code/core/Mage/Catalog/Model/Product.php

to
app/code/local/Mage/Catalog/Model/Product.php

and change the loadParentProductIds() method, found around line 1349 to:
public function loadParentProductIds()
{
        return $this->_getResource()->getParentProductIds($this);
}

This piece of code will query its resource for its parent product ids. For this to work we'll need to rewrite the getParentProductIds() method in the resource class.
So copy:
app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Product.php

to
app/code/local/Mage/Catalog/Model/Resource/Eav/Mysql4/Product.php

Find the deprecated getParentProductIds() method. Should be somewhere around line 535. Overwrite it with the pre 1.4.2.0 code:
public function getParentProductIds($object){
    $childId = $object->getId();
    $groupedProductsTable = $this->getTable('catalog/product_link');
    $groupedLinkTypeId = Mage_Catalog_Model_Product_Link::LINK_TYPE_GROUPED;
    $configurableProductsTable = $this->getTable('catalog/product_super_link');

    $groupedSelect = $this->_getReadAdapter()->select()
        ->from(array('g'=>$groupedProductsTable), 'g.product_id')
        ->where("g.linked_product_id = ?", $childId)
        ->where("link_type_id = ?", $groupedLinkTypeId);

    $groupedIds = $this->_getReadAdapter()->fetchCol($groupedSelect);

    $configurableSelect = $this->_getReadAdapter()->select()
        ->from(array('c'=>$configurableProductsTable), 'c.parent_id')
        ->where("c.product_id = ?", $childId);

    $configurableIds = $this->_getReadAdapter()->fetchCol($configurableSelect);
    return array_merge($groupedIds, $configurableIds);
}

Now you once again can do this:
$_product->loadParentProductIds()->getData('parent_product_ids');

Hope this helps you out!

A: For Magento 1.4.2 and above use the following method instead:
$configurable_product_model = Mage::getModel('catalog/product_type_configurable');
$parentIdArray = $configurable_product_model->getParentIdsByChild($simple_product_id);


text:
Q: LWC Display format for nested template for:each How to display nested array of arrays
[
  [
    { Id: "0035g00000AXuUAAA1" },
    { Name: "Person" },
    { key: "AccountId", value: "0015g00000KuZmEAAV" },
    { key: "First Name", value: "Nadie" },
    { key: "Last Name", value: "Person" },
    { key: "Birth Date", value: undefined },
  ],
  [
    { Id: "0035g00000AXuUAAA1" },
    { Name: "Person" },
    { key: "AccountId", value: "0015g00000KuZmEAAV" },
    { key: "First Name", value: "Nadie" },
    { key: "Last Name", value: "Person" },
    { key: "Birth Date", value: undefined },
  ],
  [
    { Id: "0035g00000AXuUAAA1" },
    { Name: "Person" },
    { key: "AccountId", value: "0015g00000KuZmEAAV" },
    { key: "First Name", value: "Nadie" },
    { key: "Last Name", value: "Person" },
    { key: "Birth Date", value: undefined },
  ],
  [
    { Id: "0035g00000AXuUAAA1" },
    { Name: "Person" },
    { key: "AccountId", value: "0015g00000KuZmEAAV" },
    { key: "First Name", value: "Nadie" },
    { key: "Last Name", value: "Person" },
    { key: "Birth Date", value: undefined },
  ],
  [
    { Id: "0035g00000AXuUAAA1" },
    { Name: "Person" },
    { key: "AccountId", value: "0015g00000KuZmEAAV" },
    { key: "First Name", value: "Nadie" },
    { key: "Last Name", value: "Person" },
    { key: "Birth Date", value: undefined },
  ],
]

A: One important thing in LWC is that you must have a "key", so it is impossible to work with this data as it is now.
A minimal transform method will work, though:
function transform(source) {
  let result = source.map((values, index) => ({
    index,
    values: values.reduce((acc, row) =>
      (row.key? (acc.fields.push(row), acc): Object.assign(acc, row)),
      { fields: [] })
  }))
  return result
}

Which you can then iterate over the various parts:
<template>
    <lightning-layout multiple-rows for:each={data} for:item="section" key={section.index}>
        <lightning-layout-item size="6">Record Id</lightning-layout-item>
        <lightning-layout-item size="6">{section.values.Id}</lightning-layout-item>
        <lightning-layout-item size="6">Record Name</lightning-layout-item>
        <lightning-layout-item size="6">{section.values.Name}</lightning-layout-item>
        <template for:each={section.values.fields} for:item="field">
            <lightning-layout-item key={field.key} size="6">
                {field.key}
            </lightning-layout-item>
            <lightning-layout-item key={field.key} size="6">
                <template if:true={field.value}>{field.value}</template>
                <template if:false={field.value}>-</template>
            </lightning-layout-item>
        </template>
    </lightning-layout>
</template>

I have created this demo for you.


text:
Q: Конвертация string во float в JavaScript/Vue.js Фронт пишется на vue.js
На входе есть строковая переменная (денежная величина), которая приходит с бэка. Пытаюсь ее конвертировать во float, но конвертации не происходит. Ниже небольшой пример кода
// Так как нет возможности предоставить код серверной части, присвою значение переменной
let back_end_value = '0.012';
let local_value = 10;
let tmp = 0;
let variable = 0;

Проверяю типы:
console.log('BACK: ', typeof(back_end_value)); // String
console.log('local_value: ', typeof(local_value)); // Integer

Все правильно. так и должно быть. Теперь конвертирую строковую величину в десятичное значение, и снова проверяю тип
variable = parseFloat(back_end_value).toFixed(8); //Мне нужны 8 знаков после запятой
console.log('BACK: ', typeof(variable)); // String

Снова получаю тип String. Как такое может быть?
В результате при сложении вижу вот такой результат:
tmp = local_value + back_end_value
console.log('Result: ', temp); // 10.0.0012

Подскажите, где у меня ошибка?

A: Ошибка в том, что toFixed возвращает строку, а не "десятичное значение"


text:
Q: ActionScripts3 POST to URL issue I'm trying to use API of SMSPVA.com, when i copy and paste URL to Firefox it return json values, but in Actionscripts3 wrong value appear in output.
I thing my code is not right.
I want to POST data over URL and print response with "trace" in output window.
import flash.net.*;

 function URLRequest_method()
{
    var url:String = "http://smspva.com/priemnik.php?metod=get_balance&service=opt4&apikey=HPQjg2cyfY2KhkyAjJft";

    var request:URLRequest = new URLRequest(url);

    request.method = URLRequestMethod.GET;

    var urlLoader:URLLoader = new URLLoader();

    urlLoader.load(request);

    trace(request.data);

}

Edit:
import flash.net.*;
import flash.events.Event;

 function URLRequest_method():void
{
    var url:String = "http://smspva.com/priemnik.php?metod=get_balance&service=opt4&apikey=HPQjg2cyfY2KhkyAjJf";

    var request:URLRequest = new URLRequest(url);

    request.method = URLRequestMethod.GET;

    var urlLoader:URLLoader = new URLLoader();

    urlLoader.addEventListener(Event.COMPLETE, onLoaderComplete);
    urlLoader.load(request);

}

 function onLoaderComplete(event:Event):void
{
    var urlLoader2:URLLoader = event.target as URLLoader ;
    trace(urlLoader2.data);
    trace(event.target.data.done);
}

URLRequest_method();

Result is true: "{"response":"1","balance":"0.00"}"
but a warning show too: "ReferenceError: Error #1069: Property done not found on String and there is no default value."
What thing is wrong?

A: urlLoader.load(request); is async operation, you should listen for Event.COMPLETE event to get the loaded data:
UPD:
    function URLRequest_method():void
    {
        var url:String = "http://smspva.com/priemnik.php";
        var postParams:URLVariables = new URLVariables("metod=get_balance&service=opt4&apikey=HPQjg2cyfY2KhkyAjJf");

        var request:URLRequest = new URLRequest(url);
        request.method = URLRequestMethod.GET;
        request.data = postParams;

        var urlLoader:URLLoader = new URLLoader();

        urlLoader.addEventListener(Event.COMPLETE, onLoaderComplete);
        urlLoader.load(request);

    }

    function onLoaderComplete( event:Event ):void
    {
        var urlLoader2:URLLoader = event.target as URLLoader;
        trace( urlLoader2.data );

        var json:Object = JSON.parse( urlLoader2.data );
        trace( "json.response = ", json.response );
        trace( "json.balance = ", json.balance );
    }

Output:
{"response":"1","balance":"0.00"}

json.response =  1
json.balance =  0.00

Btw, your endpoint does not support POST method, only GET


text:
Q: Restoring/Attaching Oracle DB files on a new machine I have been given some oracle database files and I need to retrieve data from them. The files include .ctl, .ora, .dbf, and .log. How can I attach/restore the database on a new install of oracle?

A: Try beginning here: Recreate Oracle Databse from .dbf files after re-installation of Oracle Enterprise 11gR2
With these files you should create a new instance, not try to "attach" it to an existing database.