问:
Inline radio with label up/down
I'm trying to get the inline radio in bootstrap with the label up or down the radio.

If you take the official example, you have:

```<code><div class="form-check form-check-inline">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1"> 1
  </label>
</div>
<div class="form-check form-check-inline">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox2" value="option2"> 2
  </label>
</div>
<div class="form-check form-check-inline">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox3" value="option3"> 3
  </label>
</div>
</code>```

What can I do to align the label up or down?

Edit: A failed attempt (not aligned and the checkbox doesn't display a clickable pointer)

答:
If I understand your question correctly, you might want to try the following:

Bottom alignment:

```<code>    <div class="form-check form-check-inline">
        <label class="form-check-label">
            <input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox1" value="option1"><br /> 1
        </label>
    </div>
    <div class="form-check form-check-inline">
        <label class="form-check-label">
            <input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox2" value="option2"><br /> 2
        </label>
    </div>
    <div class="form-check form-check-inline disabled">
        <label class="form-check-label">
            <input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox3" value="option3"><br /> 3
        </label>
    </div>
</code>```

Top alignment:

```<code>    <div class="form-check form-check-inline">
        <label class="form-check-label">
            1 <br /><input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox1" value="option1">
        </label>
    </div>
    <div class="form-check form-check-inline">
        <label class="form-check-label">
            2 <br /><input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox2" value="option2">
        </label>
    </div>
    <div class="form-check form-check-inline disabled">
        <label class="form-check-label">
            3 <br /><input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox3" value="option3">
        </label>
    </div>
</code>```

Title: Inline radio with label up/down

Body:
I'm trying to get the inline radio in bootstrap with the label up or down the radio.

If you take the official example, you have:

    <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1"> 1

    <input class="form-check-input" type="checkbox" id="inlineCheckbox2" value="option2"> 2

    <input class="form-check-input" type="checkbox" id="inlineCheckbox3" value="option3"> 3

What can I do to align the label up or down?

Edit: A failed attempt (not aligned and the checkbox doesn't display a clickable pointer)

Body:
If I understand your question correctly, you might want to try the following:

Bottom alignment:

    <div class="form-check form-check-inline">
        <label class="form-check-label">
            <input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox1" value="option1"><br /> 1
        </label>
    </div>
    <div class="form-check form-check-inline">
        <label class="form-check-label">
            <input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox2" value="option2"><br /> 2
        </label>
    </div>
    <div class="form-check form-check-inline disabled">
        <label class="form-check-label">
            <input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox3" value="option3"><br /> 3
        </label>
    </div>

Top alignment:

    <div class="form-check form-check-inline">
        <label class="form-check-label">
            1 <br /><input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox1" value="option1">
        </label>
    </div>
    <div class="form-check form-check-inline">
        <label class="form-check-label">
            2 <br /><input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox2" value="option2">
        </label>
    </div>
    <div class="form-check form-check-inline disabled">
        <label class="form-check-label">
            3 <br /><input class="form-check-input" style="cursor: pointer;" type="checkbox" id="inlineCheckbox3" value="option3">
        </label>
    </div>


来源: stackexchange

问:
CoreData Fetch Request casting [Any] to [AnyObject] produces memory leak
I am facing a memory leak which am unable to understand
PFB

Call trace:

+0x196  callq               "DYLD-STUB$$NSManagedObjectContext.fetch (NSFetchRequest) throws -> [A]"

+0x8c   callq               "_arrayForceCast ([A]) -> [B]"

+0xde   callq               "Collection.map ((A.Iterator.Element) throws -> A1) throws -> [A1]"

+0x19e  callq               "ContiguousArray.reserveCapacity(Int) -> ()"

+0xaa   callq               "_ContiguousArrayBuffer.init(uninitializedCount : Int, minimumCapacity : Int) -> _ContiguousArrayBuffer"

+0x42   callq               "ManagedBufferPointer.init(_uncheckedBufferClass : AnyObject.Type, minimumCapacity : Int) -> ManagedBufferPointer"

+0x0f   callq               "swift_slowAlloc"

+0x04   callq               "DYLD-STUB$$malloc"

+0x13   callq               "malloc_zone_malloc"

+0x8f  movzbl              71543(%rip), %eax

Edit:

I Further investigated the code and i found out that the real leak is when i try to force cast type [Any] to [AnyObject] in coredata fetch request

```<code>func fetchEntity<T: NSManagedObject>(entityClass:T.Type,setPredicate:NSPredicate?) -> [AnyObject]
{
    let entityName = NSStringFromClass(entityClass)
    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: entityName)
    fetchRequest.predicate = setPredicate
    fetchRequest.returnsObjectsAsFaults = false

    var result:[AnyObject] = []
    do
    {
        result = try cdh.managedObjectContext.fetch(fetchRequest) --> right here is the leak, when i cast the return object of [Any] to [AnyObject]

    }catch let error as NSError
    {
        debugPrint("error in fetchrequest is",error)
        result = []
    }

    return result
}
</code>```

EDIT:
@Jon,Kuba

```<code>Model.getEntities(entityType: EX_TEACHER.self, completion: {[unowned self] entityobjects in
            self.teacherList = entityobjects
    })
</code>```

// in model class

```<code> class func getEntities<T: NSManagedObject>(entityType: T.Type,completion: ([AnyObject]) -> Void)
{
    let  teacherList = coreDataOperation.fetchEntity(entityClass: entityType, setPredicate: nil)

    completion(teacherList)

}
</code>```

// cdh.managedObjectContext code

```<code>lazy var cdh:CoreDataStore = {
    let cdh = CoreDataStore()
    return cdh
}()

class CoreDataStore: NSObject{
lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}() }
</code>```

答:
Try this code</p>

```<code>        do
        {

        var result: AnyObject = try cdh.managedObjectContext.fetch(fetchRequest)
       let resultMirror = Mirror(reflecting: result)
       print(resultMirror.subjectType)    //gives you the return type  from coredata

        }catch let error as NSError
        {
            debugPrint("error in fetchrequest is",error)
            result = []
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am facing a memory leak which am unable to understand
PFB

Call trace:

+0x196  callq               "DYLD-STUB$$NSManagedObjectContext.fetch (NSFetchRequest) throws -> [A]"

+0x8c   callq               "_arrayForceCast ([A]) -> [B]"

+0xde   callq               "Collection.map ((A.Iterator.Element) throws -> A1) throws -> [A1]"

+0x19e  callq               "ContiguousArray.reserveCapacity(Int) -> ()"

+0xaa   callq               "_ContiguousArrayBuffer.init(uninitializedCount : Int, minimumCapacity : Int) -> _ContiguousArrayBuffer"

+0x42   callq               "ManagedBufferPointer.init(_uncheckedBufferClass : AnyObject.Type, minimumCapacity : Int) -> ManagedBufferPointer"

+0x0f   callq               "swift_slowAlloc"

+0x04   callq               "DYLD-STUB$$malloc"

+0x13   callq               "malloc_zone_malloc"

+0x8f  movzbl              71543(%rip), %eax

Edit:

I Further investigated the code and i found out that the real leak is when i try to force cast type [Any] to [AnyObject] in coredata fetch request

func fetchEntity<T: NSManagedObject>(entityClass:T.Type,setPredicate:NSPredicate?) -> [AnyObject]
{
    let entityName = NSStringFromClass(entityClass)
    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: entityName)
    fetchRequest.predicate = setPredicate
    fetchRequest.returnsObjectsAsFaults = false

    var result:[AnyObject] = []
    do
    {
        result = try cdh.managedObjectContext.fetch(fetchRequest) --> right here is the leak, when i cast the return object of [Any] to [AnyObject]

    }catch let error as NSError
    {
        debugPrint("error in fetchrequest is",error)
        result = []
    }

    return result
}

EDIT:
@Jon,Kuba

Model.getEntities(entityType: EX_TEACHER.self, completion: {[unowned self] entityobjects in
            self.teacherList = entityobjects
    })

// in model class

 class func getEntities<T: NSManagedObject>(entityType: T.Type,completion: ([AnyObject]) -> Void)
{
    let  teacherList = coreDataOperation.fetchEntity(entityClass: entityType, setPredicate: nil)

    completion(teacherList)

}

// cdh.managedObjectContext code

lazy var cdh:CoreDataStore = {
    let cdh = CoreDataStore()
    return cdh
}()

class CoreDataStore: NSObject{
lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}() }

Body:
Try this code

        do
        {

        var result: AnyObject = try cdh.managedObjectContext.fetch(fetchRequest)
       let resultMirror = Mirror(reflecting: result)
       print(resultMirror.subjectType)    //gives you the return type  from coredata

        }catch let error as NSError
        {
            debugPrint("error in fetchrequest is",error)
            result = []
        }


问:
Create multiple temp tables in stored procedure using Prepared queries not working
Setup

MySQL 5.7 or 5.6

In the Below Stored procedure what I'm trying to do is create a few Temp Tables.    Some of which are simple and static, and 2 of which are dynamic (TempQuery1, TempQuery2).

All temp tables are Built -> Prepared -> executed first.  Then the main query that utilizes the temp tables (GetQuery) is executed.

Problem

When executed exactly like it is on a fresh connection, I get

```<code> Error Code: 1146. Table 'Job1111.TempPipeER' doesn't exist
</code>```

Which lead me to think I had a typeo or something.. In testing I found that if I follow the next couple steps t works fine.

Comment out Prepare and Execute for both Query2 and GetQuery

Save the stored procedure and run it 2 times. (getting expected error from Deallocate)

Uncomment out Query 2.

Save the stored procedure and run it 2 more times. (getting expected error from Deallocate)

Finally uncomment all Prepares and Executes

Save and run stored procedure... NOW it works.

Question

Why am I having to go through these step to let it build the temp tables one at a time.

Does a following execute wait for previous to finish before starting?

Is there a way to force the procedure to wait for an execute/ table build to finish?

Is there a way to signal/echo/console.log() type of method that could be used to accurately show the completion of a temp table build and the start of an execute to prove that is even my real problem?

Observation/Guess

The way it is acting is like the Execute BuildGetQuery is executing before TempTable Job1111.TempPipeER is finished building.  And sine GetQuery utilizes the TempPipeER able in a Join.  The GetQuery fails.

But if I slowly build each table one at a time, then it works fine for the duration of that MySQL work bench session.

Stored Procedure Create Statement

```DROP PROCEDURE IF EXISTS `Job1111`.`GetPipeStats`;
DELIMITER $$
CREATE DEFINER=`PSAAdmin`@`%` PROCEDURE `Job1111`.`GetPipeStats`( IN GroupedBy varchar(24))
BEGIN

### Declare Variables ###
DECLARE MechHoursPercent DECIMAL(3,2);
DECLARE TestingHoursPercent DECIMAL(3,2);
DECLARE CompleteForTestPercent DECIMAL(3,2);
DECLARE HydroHoursPercent DECIMAL(3,2);
DECLARE ClientTurnoverPercent DECIMAL(3,2);

### Set Variables ###
SELECT Value1 INTO MechHoursPercent
FROM `Job1111`.SETTINGS WHERE Label = "MechHoursPercent";
SELECT Value1 INTO TestingHoursPercent
FROM `Job1111`.SETTINGS WHERE Label = "TestingHoursPercent";
SELECT Value1 INTO CompleteForTestPercent
FROM `Job1111`.SETTINGS WHERE Label = "CompleteForTestPercent";
SELECT Value1 INTO HydroHoursPercent
FROM `Job1111`.SETTINGS WHERE Label = "HydroHoursPercent";
SELECT Value1 INTO ClientTurnoverPercent
FROM `Job1111`.SETTINGS WHERE Label = "ClientTurnoverPercent";

### Build Temp Table Queries ###
#DROP TABLE IF EXISTS `Job1111`.`TempPipeER`, `Job1111`.`TempPipeERT`;

SET @TempQuery1 = CONCAT('
CREATE TEMPORARY TABLE `Job1111`.`TempPipeER`(
INDEX `TempPipeER1` (`ID` ASC)
)
SELECT ID, BidID,
sum(EarnedErectionHours) AS EarnedErectionHours,
sum(EarnedBoltUpHours) AS EarnedBoltUpHours,
sum(EarnedWeldHours) AS EarnedWeldHours,
sum(EarnedCutHours) AS EarnedCutHours,
sum(EarnedTrimHours) AS EarnedTrimHours,
sum(EarnedSupportHours) AS EarnedSupportHours,
sum(EarnedDemoHours) AS EarnedDemoHours,
sum(EarnedMiscHours) AS EarnedMiscHours,
sum(InstalledFootage) AS InstalledFootage,
sum(InstalledBoltUps) AS InstalledBoltUps,
sum(InstalledWelds) AS InstalledWelds,
sum(InstalledCuts) AS InstalledCuts,
sum(InstalledTrim) AS InstalledTrim,
sum(InstalledSupports) AS InstalledSupports,
sum(InstalledMisc) AS InstalledMisc,
sum(InstalledDemo) AS  InstalledDemo

                FROM(SELECT min(td.ID) AS ID,td.BidID,

IF(
COALESCE(se.ErectionLengthSpool1,0)
+ COALESCE(se.ErectionLengthSpool2,0)
+ COALESCE(se.ErectionLengthSpool3,0)
+ COALESCE(se.ErectionLengthSpool4,0)
+ COALESCE(se.ErectionLengthSpool5,0)
+ COALESCE(se.ErectionLengthSpool6,0)
+ COALESCE(sme.MiscQuantity,0)
+ sum(COALESCE(cse.InstalledQuantity,0)) > td.TakeOffQuantity, /*Is Installed Greater then TakeOff*/
/*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(cse.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
/*FALSE*/
COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity)
* (COALESCE(se.ErectionLengthSpool1,0)
+ COALESCE(se.ErectionLengthSpool2,0)
+ COALESCE(se.ErectionLengthSpool3,0)
+ COALESCE(se.ErectionLengthSpool4,0)
+ COALESCE(se.ErectionLengthSpool5,0)
+ COALESCE(se.ErectionLengthSpool6,0)
+ COALESCE(sme.MiscQuantity,0)),0)
) AS EarnedErectionHours,

IF(COALESCE(sb.BoltUpQuantity,0) + COALESCE(smb.MiscQuantity,0) + sum(COALESCE(csb.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csb.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * (COALESCE(sb.BoltUpQuantity,0)+COALESCE(smb.MiscQuantity,0)), 0)
    ) AS EarnedBoltUpHours,

IF(COALESCE(sw.WeldPercentCompleted * .01,0) + COALESCE(smw.MiscQuantity,0) + sum(COALESCE(csw.InstalledQuantity * .01,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csw.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * (COALESCE(sw.WeldPercentCompleted * .01,0)+COALESCE(smw.MiscQuantity,0)),0)
    ) AS EarnedWeldHours,

IF(COALESCE(scut.WeldPercentCompleted * .01,0) + COALESCE(smc.MiscQuantity,0) + sum(COALESCE(csc.InstalledQuantity * .01,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csc.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * (COALESCE(scut.WeldPercentCompleted * .01,0)+COALESCE(smc.MiscQuantity,0)),0)
    ) AS EarnedCutHours,

IF(COALESCE(st.TrimQuantity,0) + COALESCE(smt.MiscQuantity,0) + sum(COALESCE(cst.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(cst.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * (COALESCE(st.TrimQuantity,0)+COALESCE(smt.MiscQuantity,0)),0)
    ) AS EarnedTrimHours,

IF(COALESCE(ssu.SupportInstalled,0) + COALESCE(smssu.MiscQuantity,0) + sum(COALESCE(cssu.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(cssu.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity)*(COALESCE(ssu.SupportInstalled,0)+COALESCE(smssu.MiscQuantity,0)),0)
    ) AS EarnedSupportHours,

IF(COALESCE(sde.DemoQuantity,0) + COALESCE(smd.MiscQuantity,0) + sum(COALESCE(csd.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csd.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours/td.TakeOffQuantity) * (COALESCE(sde.DemoQuantity,0)+COALESCE(smd.MiscQuantity,0)),0)
    ) AS EarnedDemoHours,

IF(COALESCE(sm.MiscQuantity,0) + sum(COALESCE(csm.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csm.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * COALESCE(sm.MiscQuantity,0),0)
    ) AS EarnedMiscHours,

sum(COALESCE(se.ErectionLengthSpool1,0) + COALESCE(se.ErectionLengthSpool2,0) + COALESCE(se.ErectionLengthSpool3,0) + COALESCE(se.ErectionLengthSpool4,0) + COALESCE(se.ErectionLengthSpool5,0) + COALESCE(se.ErectionLengthSpool6,0) + COALESCE(sme.MiscQuantity,0)) AS InstalledFootage,
sum(COALESCE(sb.BoltUpQuantity,0) + COALESCE(smb.MiscQuantity,0)) AS InstalledBoltUps,
sum(COALESCE(sw.WeldPercentCompleted * .01,0) + COALESCE(smw.MiscQuantity,0)) AS InstalledWelds,
sum(COALESCE(scut.WeldPercentCompleted * .01,0) + COALESCE(smc.MiscQuantity,0)) AS InstalledCuts,
sum(COALESCE(st.TrimQuantity,0) + COALESCE(smt.MiscQuantity,0)) AS InstalledTrim,
sum(COALESCE(ssu.SupportInstalled,0) + COALESCE(smssu.MiscQuantity,0)) AS InstalledSupports,
sum(COALESCE(sm.MiscQuantity,0)) AS InstalledMisc,
sum(COALESCE(sde.DemoQuantity,0) + COALESCE(smd.MiscQuantity,0)) AS InstalledDemo

FROM `Job1111`.SubmissionStatus ss
    JOIN PSA.REF_ActivityTypes at
        ON at.ID = ss.ActivityType

    LEFT JOIN `Job1111`.SubsErection se
        ON se.ID = ss.ActivityRowId AND ss.ActivityType = 11 AND se.ErectionRework = 0

    LEFT JOIN `Job1111`.SubsBoltUp sb
        ON sb.ID = ss.ActivityRowId AND ss.ActivityType = 21 AND sb.BoltUpRework = 0

    LEFT JOIN `Job1111`.SubsWeld sw
        ON sw.ID = ss.ActivityRowId AND ss.ActivityType = 22 AND  sw.WeldRework = 0

    LEFT JOIN `Job1111`.SubsWeld scut
        ON scut.ID = ss.ActivityRowId AND ss.ActivityType = 23 AND scut.WeldRework = 0

    LEFT JOIN `Job1111`.SubsTrim st
        ON st.ID = ss.ActivityRowId AND ss.ActivityType IN (30,31,33,34,35,39) AND st.TrimRework = 0

    LEFT JOIN (SELECT ssu.ID, COALESCE((ssu.SupportPercentCompleted * .01 * ssu.SupportQuantity),0) AS SupportInstalled
                FROM `Job1111`.SubsSupports ssu
                WHERE ssu.SupportRework = 0) ssu
        ON ssu.ID = ss.ActivityRowId AND ss.ActivityType = 32

    LEFT JOIN `Job1111`.SubsDemo sde
        ON sde.ID = ss.ActivityRowId AND ss.ActivityType IN (50,51,52,53,59)

    LEFT JOIN `Job1111`.`TempTrackerDetailsPipe`td
        ON td.BidID = ss.fk_BidIDAssigned

/* #### Begining of Misc activities assigned joins #### */
    LEFT JOIN `Job1111`.SubsMisc sm
        ON sm.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT != "D" AND td.PipingActivityType = "MISC"  AND sm.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc sme
        ON sme.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "PE" AND sme.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smb
        ON smb.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "BU" AND smb.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smw
        ON smw.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "W" AND smw.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smc
        ON smc.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT != "D" AND td.PipingActivityType = "CUT" AND smc.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smt
        ON smt.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT = "T" AND td.PipingActivityType IN ("V","Plug","HpLp","Other","Blind") AND smt.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smssu
        ON smssu.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "S" AND smssu.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smd
        ON smd.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT = "D" AND smd.MiscRework = 0

/* #### Begining of Cumulative Past sums Calculation #### */
    LEFT JOIN `Job1111`.`TempPipeCSE` cse
        ON ss.ActivityType IN (11,91) AND ss.fk_BidIDAssigned = cse.fk_BidIDAssigned AND cse.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSB` csb
        ON ss.ActivityType IN (21,91) AND ss.fk_BidIDAssigned = csb.fk_BidIDAssigned AND csb.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSW` csw
        ON ss.ActivityType IN (22,91) AND ss.fk_BidIDAssigned = csw.fk_BidIDAssigned AND csw.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSC` csc
        ON ss.ActivityType IN (23,91) AND ss.fk_BidIDAssigned = csc.fk_BidIDAssigned AND csc.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCST` cst
        ON ss.ActivityType IN (30,31,33,34,35,39,91) AND ss.fk_BidIDAssigned = cst.fk_BidIDAssigned AND cst.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSSU` cssu
        ON ss.ActivityType IN (32,91) AND ss.fk_BidIDAssigned = cssu.fk_BidIDAssigned AND cssu.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSD` csd
        ON ss.ActivityType IN (50,51,52,53,59,91) AND ss.fk_BidIDAssigned = csd.fk_BidIDAssigned AND csd.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSM` csm
        ON ss.ActivityType = 91 AND ss.fk_BidIDAssigned = csm.fk_BidIDAssigned AND csm.PSAActivityID < ss.PSAActivityID

WHERE fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (10,11,20,21,22,23,30,31,32,33,34,35,39,50,51,52,53,59,90,91,93)
GROUP BY ss.PSAActivityID)er0
GROUP BY BidID
');

SET @TempQuery2 = CONCAT('
CREATE TEMPORARY TABLE `Job1111`.`TempPipeERT`(
INDEX `TempPipeERT1` (`ID` ASC)
)
SELECT min(td.ID) AS ID, td.BidID,

IF(
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,CompleteForTestPercent, ' * sum(COALESCE(steR.InstalledReadyForTesting, 0)))
    > COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,CompleteForTestPercent, ',
    /*TRUE*/
    COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,CompleteForTestPercent, ',
    /*FALSE*/
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,CompleteForTestPercent, ' * sum(COALESCE(steR.InstalledReadyForTesting, 0)))
) AS EarnedReadyForTestingHours,

IF(
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,HydroHoursPercent, ' * sum(COALESCE(steH.InstalledHydro, 0)))
    > COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,HydroHoursPercent, ',
    /*TRUE*/
    COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,HydroHoursPercent, ',
    /*FALSE*/
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,HydroHoursPercent, ' * sum(COALESCE(steH.InstalledHydro, 0)))
) AS EarnedHydroHours,

IF(
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,ClientTurnoverPercent, ' * sum(COALESCE(steC.InstalledClientTurnover, 0)))
    > COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,ClientTurnoverPercent, ',
    /*TRUE*/
    COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,ClientTurnoverPercent, ',
    /*FALSE*/
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,ClientTurnoverPercent, ' * sum(COALESCE(steC.InstalledClientTurnover, 0)))
) AS EarnedClientTurnoverHours

FROM `Job1111`.trackerDetails td

LEFT JOIN (SELECT ste.ActivityType, ste.TestingTestPackageNumber, 1 AS InstalledReadyForTesting
            FROM `Job1111`.SubsTesting ste
            JOIN `Job1111`.SubmissionStatus ss
                ON ss.ActivityRowId = ste.ID AND ss.ActivityType = 41 AND ss.fk_ActivityStatus IN (5,12) AND ste.TestingRework = 0) steR
    ON steR.TestingTestPackageNumber = td.TestPackageNumber AND steR.ActivityType = 41 AND td.ECT != "D"

LEFT JOIN (SELECT ste.ActivityType, ste.TestingTestPackageNumber, 1 AS InstalledHydro
            FROM `Job1111`.SubsTesting ste
            JOIN `Job1111`.SubmissionStatus ss
                ON ss.ActivityRowId = ste.ID AND ss.ActivityType = 42 AND ss.fk_ActivityStatus IN (5,12) AND ste.TestingRework = 0) steH
    ON steH.TestingTestPackageNumber = td.TestPackageNumber AND steH.ActivityType = 42 AND td.ECT != "D"

LEFT JOIN (SELECT ste.ActivityType, ste.TestingTestPackageNumber, 1 AS InstalledClientTurnover
            FROM `Job1111`.SubsTesting ste
            JOIN `Job1111`.SubmissionStatus ss
                ON ss.ActivityRowId = ste.ID AND ss.ActivityType = 43 AND ss.fk_ActivityStatus IN (5,12) AND ste.TestingRework = 0) steC
    ON steC.TestingTestPackageNumber = td.TestPackageNumber AND steC.ActivityType = 43 AND td.ECT != "D"

GROUP BY td.BidID
');

### Build Main Query ###
SET @GetQuery = CONCAT('
QUERY REMOVED DUE TO BODY SIZE LIMIT
');

### Execute NON Prep Queries ###
DROP TABLE IF EXISTS `Job1111`.`TempTrackerDetailsPipe`;
CREATE TEMPORARY TABLE `Job1111`.`TempTrackerDetailsPipe`(
INDEX `TempPipeTD1` (`BidID` ASC),
INDEX `TempPipeTD2` (`PipingActivityType` ASC, `ECT` ASC),
INDEX `TempPipeTD3` (`ECT` ASC)
)
SELECT min(ID) AS ID, BidID, sum(TakeOffQuantity) AS TakeOffQuantity, sum(EstimatedHours) AS EstimatedHours, ECT, PipingActivityType
FROM`Job1111`.`trackerDetails`
GROUP BY BidID;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSE`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSE`(
INDEX `TempPipeCSE1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(ErectionLengthSpool1,0) + COALESCE(ErectionLengthSpool2,0) + COALESCE(ErectionLengthSpool3,0) + COALESCE(ErectionLengthSpool4,0) + COALESCE(ErectionLengthSpool5,0) + COALESCE(ErectionLengthSpool6,0) + COALESCE(sme.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsErection
    ON ss.ActivityType = 11 AND ss.ActivityRowId = ID AND ErectionRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc sme
    ON sme.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "PE" AND sme.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (11,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSB`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSB`(
INDEX `TempPipeCSB1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(BoltUpQuantity,0) + COALESCE(smb.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsBoltUp
    ON ss.ActivityType = 21 AND ss.ActivityRowId = ID AND BoltUpRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smb
    ON smb.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "BU" AND smb.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (21,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSW`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSW`(
INDEX `TempPipeCSW1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(WeldPercentCompleted,0) + COALESCE(smw.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsWeld
    ON ss.ActivityType = 22 AND ss.ActivityRowId = ID AND WeldRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe`td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smw
    ON smw.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "W"AND smw.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (22,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSC`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSC`(
INDEX `TempPipeCSC1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(WeldPercentCompleted,0) + COALESCE(smc.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsWeld
    ON ss.ActivityType = 23 AND ss.ActivityRowId = ID AND WeldRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe`td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smc
    ON smc.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT != "D" AND td.PipingActivityType = "CUT" AND smc.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (23,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCST`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCST`(
INDEX `TempPipeCST1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(TrimQuantity,0) + COALESCE(smt.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsTrim
    ON ss.ActivityType IN (30,31,33,34,35,39) AND ss.ActivityRowId = ID AND TrimRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smt
    ON smt.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT = "T" AND td.PipingActivityType IN ("V","Plug","HpLp","Other","Blind")AND smt.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (30,31,33,34,35,39,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSSU`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSSU`(
INDEX `TempPipeCSSU1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(SupportQuantity,0) + COALESCE(smssu.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsSupports
    ON ss.ActivityType = 32 AND ss.ActivityRowId = ID AND SupportRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smssu
    ON smssu.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "S" AND smssu.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSD`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSD`(
INDEX `TempPipeCSD` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(DemoQuantity,0) + COALESCE(smd.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsDemo
    ON ss.ActivityType IN (50,51,52,53,59) AND ss.ActivityRowId = ID
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smd
    ON smd.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT = "D" AND smd.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (50,51,52,53,59,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSM`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSM`(
INDEX `TempPipeCSM` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, MiscQuantity AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
JOIN `Job1111`.SubsMisc sm
    ON ss.ActivityType = 91 AND ss.ActivityRowId = sm.ID AND td.PipingActivityType = "MISC"  AND td.ECT != "D" AND sm.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12);

### Prepare Queries to execute ###
PREPARE BuildTempQuery1 FROM @TempQuery1;
PREPARE BuildTempQuery2 FROM @TempQuery2;
PREPARE BuildGetQuery FROM @GetQuery;

### Execute Prep Queries ###
EXECUTE BuildTempQuery1;
EXECUTE BuildTempQuery2;
EXECUTE BuildGetQuery;

### Deallocate Execute Querys and Tables###
DEALLOCATE PREPARE BuildTempQuery1;
DEALLOCATE PREPARE BuildTempQuery2;
DEALLOCATE PREPARE BuildGetQuery;

END$$
DELIMITER ;
```

答:
The stored procedure is perfectly sound.  Except for one item.   Due to the fact that some prepared statements use Temp tables made by other prepared statements.  Care needs to be taken to Prepare AND EXECUTE the statements in the right order.

Change This

```<code>### Prepare Queries to execute ###
PREPARE BuildTempQuery1 FROM @TempQuery1;
PREPARE BuildTempQuery2 FROM @TempQuery2;
PREPARE BuildGetQuery FROM @GetQuery;

### Execute Prep Queries ###
EXECUTE BuildTempQuery1;
EXECUTE BuildTempQuery2;
EXECUTE BuildGetQuery;

### Deallocate Execute Querys and Tables###
DEALLOCATE PREPARE BuildTempQuery1;
DEALLOCATE PREPARE BuildTempQuery2;
DEALLOCATE PREPARE BuildGetQuery;
</code>```

To This

```<code>### Prepare Pass 1 Queries to execute ###
PREPARE BuildTempQuery1 FROM @TempQuery1;
PREPARE BuildTempQuery2 FROM @TempQuery2;

### Execute Pass 1 Queries ###
EXECUTE BuildTempQuery1 ;
EXECUTE BuildTempQuery2 ;

### Prepare Pass 2 Queries to execute ###
PREPARE BuildGetQuery FROM @GetQuery;

### Execute Pass 2 Queries ###
EXECUTE BuildGetQuery;

### Deallocate Execute Querys and Tables###
DEALLOCATE PREPARE BuildTempQueryER;
DEALLOCATE PREPARE BuildTempQueryERT;
DEALLOCATE PREPARE BuildGetQuery;
</code>```

Explanation

The reason this is needed, is since "BuildGetQuery" is looking for the Temp Table created by "BuildTempQuery1".  It must exist BEFORE PREPARE of BuildGetQuery.

The mistake was thinking the "Do these tables exist?" check performed during the execution of "BuildGetQuery" where looking for tables made in  BuildTempQuery1 and BuildTempQuery1 happen at EXECUTE and not at PREPARE.

Turns out this check happens at PREPARE of "BuildGetQuery".  Meaning the Temp queries need to first be executed.

The one peace I'm missing is where in the MySQL documentation this reality is explained/demonstrated.

Body:
Setup

MySQL 5.7 or 5.6

In the Below Stored procedure what I'm trying to do is create a few Temp Tables.    Some of which are simple and static, and 2 of which are dynamic (TempQuery1, TempQuery2).

All temp tables are Built -> Prepared -> executed first.  Then the main query that utilizes the temp tables (GetQuery) is executed.

Problem

When executed exactly like it is on a fresh connection, I get

 Error Code: 1146. Table 'Job1111.TempPipeER' doesn't exist

Which lead me to think I had a typeo or something.. In testing I found that if I follow the next couple steps t works fine.

Comment out Prepare and Execute for both Query2 and GetQuery

Save the stored procedure and run it 2 times. (getting expected error from Deallocate)

Uncomment out Query 2.

Save the stored procedure and run it 2 more times. (getting expected error from Deallocate)

Finally uncomment all Prepares and Executes

Save and run stored procedure... NOW it works.

Question

Why am I having to go through these step to let it build the temp tables one at a time.

Does a following execute wait for previous to finish before starting?

Is there a way to force the procedure to wait for an execute/ table build to finish?

Is there a way to signal/echo/console.log() type of method that could be used to accurately show the completion of a temp table build and the start of an execute to prove that is even my real problem?

Observation/Guess

The way it is acting is like the Execute BuildGetQuery is executing before TempTable Job1111.TempPipeER is finished building.  And sine GetQuery utilizes the TempPipeER able in a Join.  The GetQuery fails.

But if I slowly build each table one at a time, then it works fine for the duration of that MySQL work bench session.

Stored Procedure Create Statement

DROP PROCEDURE IF EXISTS `Job1111`.`GetPipeStats`;
DELIMITER $$
CREATE DEFINER=`PSAAdmin`@`%` PROCEDURE `Job1111`.`GetPipeStats`( IN GroupedBy varchar(24))
BEGIN

### Declare Variables ###
DECLARE MechHoursPercent DECIMAL(3,2);
DECLARE TestingHoursPercent DECIMAL(3,2);
DECLARE CompleteForTestPercent DECIMAL(3,2);
DECLARE HydroHoursPercent DECIMAL(3,2);
DECLARE ClientTurnoverPercent DECIMAL(3,2);

### Set Variables ###
SELECT Value1 INTO MechHoursPercent
FROM `Job1111`.SETTINGS WHERE Label = "MechHoursPercent";
SELECT Value1 INTO TestingHoursPercent
FROM `Job1111`.SETTINGS WHERE Label = "TestingHoursPercent";
SELECT Value1 INTO CompleteForTestPercent
FROM `Job1111`.SETTINGS WHERE Label = "CompleteForTestPercent";
SELECT Value1 INTO HydroHoursPercent
FROM `Job1111`.SETTINGS WHERE Label = "HydroHoursPercent";
SELECT Value1 INTO ClientTurnoverPercent
FROM `Job1111`.SETTINGS WHERE Label = "ClientTurnoverPercent";

### Build Temp Table Queries ###
#DROP TABLE IF EXISTS `Job1111`.`TempPipeER`, `Job1111`.`TempPipeERT`;

SET @TempQuery1 = CONCAT('
CREATE TEMPORARY TABLE `Job1111`.`TempPipeER`(
INDEX `TempPipeER1` (`ID` ASC)
)
SELECT ID, BidID,
sum(EarnedErectionHours) AS EarnedErectionHours,
sum(EarnedBoltUpHours) AS EarnedBoltUpHours,
sum(EarnedWeldHours) AS EarnedWeldHours,
sum(EarnedCutHours) AS EarnedCutHours,
sum(EarnedTrimHours) AS EarnedTrimHours,
sum(EarnedSupportHours) AS EarnedSupportHours,
sum(EarnedDemoHours) AS EarnedDemoHours,
sum(EarnedMiscHours) AS EarnedMiscHours,
sum(InstalledFootage) AS InstalledFootage,
sum(InstalledBoltUps) AS InstalledBoltUps,
sum(InstalledWelds) AS InstalledWelds,
sum(InstalledCuts) AS InstalledCuts,
sum(InstalledTrim) AS InstalledTrim,
sum(InstalledSupports) AS InstalledSupports,
sum(InstalledMisc) AS InstalledMisc,
sum(InstalledDemo) AS  InstalledDemo

                FROM(SELECT min(td.ID) AS ID,td.BidID,

IF(
COALESCE(se.ErectionLengthSpool1,0)
+ COALESCE(se.ErectionLengthSpool2,0)
+ COALESCE(se.ErectionLengthSpool3,0)
+ COALESCE(se.ErectionLengthSpool4,0)
+ COALESCE(se.ErectionLengthSpool5,0)
+ COALESCE(se.ErectionLengthSpool6,0)
+ COALESCE(sme.MiscQuantity,0)
+ sum(COALESCE(cse.InstalledQuantity,0)) > td.TakeOffQuantity, /*Is Installed Greater then TakeOff*/
/*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(cse.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
/*FALSE*/
COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity)
* (COALESCE(se.ErectionLengthSpool1,0)
+ COALESCE(se.ErectionLengthSpool2,0)
+ COALESCE(se.ErectionLengthSpool3,0)
+ COALESCE(se.ErectionLengthSpool4,0)
+ COALESCE(se.ErectionLengthSpool5,0)
+ COALESCE(se.ErectionLengthSpool6,0)
+ COALESCE(sme.MiscQuantity,0)),0)
) AS EarnedErectionHours,

IF(COALESCE(sb.BoltUpQuantity,0) + COALESCE(smb.MiscQuantity,0) + sum(COALESCE(csb.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csb.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * (COALESCE(sb.BoltUpQuantity,0)+COALESCE(smb.MiscQuantity,0)), 0)
    ) AS EarnedBoltUpHours,

IF(COALESCE(sw.WeldPercentCompleted * .01,0) + COALESCE(smw.MiscQuantity,0) + sum(COALESCE(csw.InstalledQuantity * .01,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csw.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * (COALESCE(sw.WeldPercentCompleted * .01,0)+COALESCE(smw.MiscQuantity,0)),0)
    ) AS EarnedWeldHours,

IF(COALESCE(scut.WeldPercentCompleted * .01,0) + COALESCE(smc.MiscQuantity,0) + sum(COALESCE(csc.InstalledQuantity * .01,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csc.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * (COALESCE(scut.WeldPercentCompleted * .01,0)+COALESCE(smc.MiscQuantity,0)),0)
    ) AS EarnedCutHours,

IF(COALESCE(st.TrimQuantity,0) + COALESCE(smt.MiscQuantity,0) + sum(COALESCE(cst.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(cst.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * (COALESCE(st.TrimQuantity,0)+COALESCE(smt.MiscQuantity,0)),0)
    ) AS EarnedTrimHours,

IF(COALESCE(ssu.SupportInstalled,0) + COALESCE(smssu.MiscQuantity,0) + sum(COALESCE(cssu.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(cssu.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity)*(COALESCE(ssu.SupportInstalled,0)+COALESCE(smssu.MiscQuantity,0)),0)
    ) AS EarnedSupportHours,

IF(COALESCE(sde.DemoQuantity,0) + COALESCE(smd.MiscQuantity,0) + sum(COALESCE(csd.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csd.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours/td.TakeOffQuantity) * (COALESCE(sde.DemoQuantity,0)+COALESCE(smd.MiscQuantity,0)),0)
    ) AS EarnedDemoHours,

IF(COALESCE(sm.MiscQuantity,0) + sum(COALESCE(csm.InstalledQuantity,0))
    > td.TakeOffQuantity,/*Is Installed Greater then TakeOff*/
    /*TRUE*/ GREATEST(td.TakeOffQuantity - sum(COALESCE(csm.InstalledQuantity,0)),0) * (td.EstimatedHours * ' ,MechHoursPercent, ' / td.TakeOffQuantity),
    /*FALSE*/ COALESCE((td.EstimatedHours*' ,MechHoursPercent, '/td.TakeOffQuantity) * COALESCE(sm.MiscQuantity,0),0)
    ) AS EarnedMiscHours,

sum(COALESCE(se.ErectionLengthSpool1,0) + COALESCE(se.ErectionLengthSpool2,0) + COALESCE(se.ErectionLengthSpool3,0) + COALESCE(se.ErectionLengthSpool4,0) + COALESCE(se.ErectionLengthSpool5,0) + COALESCE(se.ErectionLengthSpool6,0) + COALESCE(sme.MiscQuantity,0)) AS InstalledFootage,
sum(COALESCE(sb.BoltUpQuantity,0) + COALESCE(smb.MiscQuantity,0)) AS InstalledBoltUps,
sum(COALESCE(sw.WeldPercentCompleted * .01,0) + COALESCE(smw.MiscQuantity,0)) AS InstalledWelds,
sum(COALESCE(scut.WeldPercentCompleted * .01,0) + COALESCE(smc.MiscQuantity,0)) AS InstalledCuts,
sum(COALESCE(st.TrimQuantity,0) + COALESCE(smt.MiscQuantity,0)) AS InstalledTrim,
sum(COALESCE(ssu.SupportInstalled,0) + COALESCE(smssu.MiscQuantity,0)) AS InstalledSupports,
sum(COALESCE(sm.MiscQuantity,0)) AS InstalledMisc,
sum(COALESCE(sde.DemoQuantity,0) + COALESCE(smd.MiscQuantity,0)) AS InstalledDemo

FROM `Job1111`.SubmissionStatus ss
    JOIN PSA.REF_ActivityTypes at
        ON at.ID = ss.ActivityType

    LEFT JOIN `Job1111`.SubsErection se
        ON se.ID = ss.ActivityRowId AND ss.ActivityType = 11 AND se.ErectionRework = 0

    LEFT JOIN `Job1111`.SubsBoltUp sb
        ON sb.ID = ss.ActivityRowId AND ss.ActivityType = 21 AND sb.BoltUpRework = 0

    LEFT JOIN `Job1111`.SubsWeld sw
        ON sw.ID = ss.ActivityRowId AND ss.ActivityType = 22 AND  sw.WeldRework = 0

    LEFT JOIN `Job1111`.SubsWeld scut
        ON scut.ID = ss.ActivityRowId AND ss.ActivityType = 23 AND scut.WeldRework = 0

    LEFT JOIN `Job1111`.SubsTrim st
        ON st.ID = ss.ActivityRowId AND ss.ActivityType IN (30,31,33,34,35,39) AND st.TrimRework = 0

    LEFT JOIN (SELECT ssu.ID, COALESCE((ssu.SupportPercentCompleted * .01 * ssu.SupportQuantity),0) AS SupportInstalled
                FROM `Job1111`.SubsSupports ssu
                WHERE ssu.SupportRework = 0) ssu
        ON ssu.ID = ss.ActivityRowId AND ss.ActivityType = 32

    LEFT JOIN `Job1111`.SubsDemo sde
        ON sde.ID = ss.ActivityRowId AND ss.ActivityType IN (50,51,52,53,59)

    LEFT JOIN `Job1111`.`TempTrackerDetailsPipe`td
        ON td.BidID = ss.fk_BidIDAssigned

/* #### Begining of Misc activities assigned joins #### */
    LEFT JOIN `Job1111`.SubsMisc sm
        ON sm.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT != "D" AND td.PipingActivityType = "MISC"  AND sm.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc sme
        ON sme.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "PE" AND sme.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smb
        ON smb.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "BU" AND smb.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smw
        ON smw.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "W" AND smw.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smc
        ON smc.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT != "D" AND td.PipingActivityType = "CUT" AND smc.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smt
        ON smt.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT = "T" AND td.PipingActivityType IN ("V","Plug","HpLp","Other","Blind") AND smt.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smssu
        ON smssu.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "S" AND smssu.MiscRework = 0

    LEFT JOIN `Job1111`.SubsMisc smd
        ON smd.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT = "D" AND smd.MiscRework = 0

/* #### Begining of Cumulative Past sums Calculation #### */
    LEFT JOIN `Job1111`.`TempPipeCSE` cse
        ON ss.ActivityType IN (11,91) AND ss.fk_BidIDAssigned = cse.fk_BidIDAssigned AND cse.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSB` csb
        ON ss.ActivityType IN (21,91) AND ss.fk_BidIDAssigned = csb.fk_BidIDAssigned AND csb.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSW` csw
        ON ss.ActivityType IN (22,91) AND ss.fk_BidIDAssigned = csw.fk_BidIDAssigned AND csw.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSC` csc
        ON ss.ActivityType IN (23,91) AND ss.fk_BidIDAssigned = csc.fk_BidIDAssigned AND csc.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCST` cst
        ON ss.ActivityType IN (30,31,33,34,35,39,91) AND ss.fk_BidIDAssigned = cst.fk_BidIDAssigned AND cst.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSSU` cssu
        ON ss.ActivityType IN (32,91) AND ss.fk_BidIDAssigned = cssu.fk_BidIDAssigned AND cssu.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSD` csd
        ON ss.ActivityType IN (50,51,52,53,59,91) AND ss.fk_BidIDAssigned = csd.fk_BidIDAssigned AND csd.PSAActivityID < ss.PSAActivityID

    LEFT JOIN `Job1111`.`TempPipeCSM` csm
        ON ss.ActivityType = 91 AND ss.fk_BidIDAssigned = csm.fk_BidIDAssigned AND csm.PSAActivityID < ss.PSAActivityID

WHERE fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (10,11,20,21,22,23,30,31,32,33,34,35,39,50,51,52,53,59,90,91,93)
GROUP BY ss.PSAActivityID)er0
GROUP BY BidID
');

SET @TempQuery2 = CONCAT('
CREATE TEMPORARY TABLE `Job1111`.`TempPipeERT`(
INDEX `TempPipeERT1` (`ID` ASC)
)
SELECT min(td.ID) AS ID, td.BidID,

IF(
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,CompleteForTestPercent, ' * sum(COALESCE(steR.InstalledReadyForTesting, 0)))
    > COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,CompleteForTestPercent, ',
    /*TRUE*/
    COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,CompleteForTestPercent, ',
    /*FALSE*/
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,CompleteForTestPercent, ' * sum(COALESCE(steR.InstalledReadyForTesting, 0)))
) AS EarnedReadyForTestingHours,

IF(
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,HydroHoursPercent, ' * sum(COALESCE(steH.InstalledHydro, 0)))
    > COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,HydroHoursPercent, ',
    /*TRUE*/
    COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,HydroHoursPercent, ',
    /*FALSE*/
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,HydroHoursPercent, ' * sum(COALESCE(steH.InstalledHydro, 0)))
) AS EarnedHydroHours,

IF(
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,ClientTurnoverPercent, ' * sum(COALESCE(steC.InstalledClientTurnover, 0)))
    > COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,ClientTurnoverPercent, ',
    /*TRUE*/
    COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,ClientTurnoverPercent, ',
    /*FALSE*/
    (COALESCE(td.EstimatedHours,0)*' ,TestingHoursPercent, '*' ,ClientTurnoverPercent, ' * sum(COALESCE(steC.InstalledClientTurnover, 0)))
) AS EarnedClientTurnoverHours

FROM `Job1111`.trackerDetails td

LEFT JOIN (SELECT ste.ActivityType, ste.TestingTestPackageNumber, 1 AS InstalledReadyForTesting
            FROM `Job1111`.SubsTesting ste
            JOIN `Job1111`.SubmissionStatus ss
                ON ss.ActivityRowId = ste.ID AND ss.ActivityType = 41 AND ss.fk_ActivityStatus IN (5,12) AND ste.TestingRework = 0) steR
    ON steR.TestingTestPackageNumber = td.TestPackageNumber AND steR.ActivityType = 41 AND td.ECT != "D"

LEFT JOIN (SELECT ste.ActivityType, ste.TestingTestPackageNumber, 1 AS InstalledHydro
            FROM `Job1111`.SubsTesting ste
            JOIN `Job1111`.SubmissionStatus ss
                ON ss.ActivityRowId = ste.ID AND ss.ActivityType = 42 AND ss.fk_ActivityStatus IN (5,12) AND ste.TestingRework = 0) steH
    ON steH.TestingTestPackageNumber = td.TestPackageNumber AND steH.ActivityType = 42 AND td.ECT != "D"

LEFT JOIN (SELECT ste.ActivityType, ste.TestingTestPackageNumber, 1 AS InstalledClientTurnover
            FROM `Job1111`.SubsTesting ste
            JOIN `Job1111`.SubmissionStatus ss
                ON ss.ActivityRowId = ste.ID AND ss.ActivityType = 43 AND ss.fk_ActivityStatus IN (5,12) AND ste.TestingRework = 0) steC
    ON steC.TestingTestPackageNumber = td.TestPackageNumber AND steC.ActivityType = 43 AND td.ECT != "D"

GROUP BY td.BidID
');

### Build Main Query ###
SET @GetQuery = CONCAT('
QUERY REMOVED DUE TO BODY SIZE LIMIT
');

### Execute NON Prep Queries ###
DROP TABLE IF EXISTS `Job1111`.`TempTrackerDetailsPipe`;
CREATE TEMPORARY TABLE `Job1111`.`TempTrackerDetailsPipe`(
INDEX `TempPipeTD1` (`BidID` ASC),
INDEX `TempPipeTD2` (`PipingActivityType` ASC, `ECT` ASC),
INDEX `TempPipeTD3` (`ECT` ASC)
)
SELECT min(ID) AS ID, BidID, sum(TakeOffQuantity) AS TakeOffQuantity, sum(EstimatedHours) AS EstimatedHours, ECT, PipingActivityType
FROM`Job1111`.`trackerDetails`
GROUP BY BidID;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSE`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSE`(
INDEX `TempPipeCSE1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(ErectionLengthSpool1,0) + COALESCE(ErectionLengthSpool2,0) + COALESCE(ErectionLengthSpool3,0) + COALESCE(ErectionLengthSpool4,0) + COALESCE(ErectionLengthSpool5,0) + COALESCE(ErectionLengthSpool6,0) + COALESCE(sme.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsErection
    ON ss.ActivityType = 11 AND ss.ActivityRowId = ID AND ErectionRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc sme
    ON sme.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "PE" AND sme.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (11,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSB`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSB`(
INDEX `TempPipeCSB1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(BoltUpQuantity,0) + COALESCE(smb.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsBoltUp
    ON ss.ActivityType = 21 AND ss.ActivityRowId = ID AND BoltUpRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smb
    ON smb.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "BU" AND smb.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (21,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSW`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSW`(
INDEX `TempPipeCSW1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(WeldPercentCompleted,0) + COALESCE(smw.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsWeld
    ON ss.ActivityType = 22 AND ss.ActivityRowId = ID AND WeldRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe`td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smw
    ON smw.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "W"AND smw.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (22,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSC`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSC`(
INDEX `TempPipeCSC1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(WeldPercentCompleted,0) + COALESCE(smc.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsWeld
    ON ss.ActivityType = 23 AND ss.ActivityRowId = ID AND WeldRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe`td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smc
    ON smc.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT != "D" AND td.PipingActivityType = "CUT" AND smc.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (23,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCST`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCST`(
INDEX `TempPipeCST1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(TrimQuantity,0) + COALESCE(smt.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsTrim
    ON ss.ActivityType IN (30,31,33,34,35,39) AND ss.ActivityRowId = ID AND TrimRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smt
    ON smt.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT = "T" AND td.PipingActivityType IN ("V","Plug","HpLp","Other","Blind")AND smt.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (30,31,33,34,35,39,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSSU`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSSU`(
INDEX `TempPipeCSSU1` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(SupportQuantity,0) + COALESCE(smssu.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsSupports
    ON ss.ActivityType = 32 AND ss.ActivityRowId = ID AND SupportRework = 0
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smssu
    ON smssu.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.PipingActivityType = "S" AND smssu.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSD`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSD`(
INDEX `TempPipeCSD` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, (COALESCE(DemoQuantity,0) + COALESCE(smd.MiscQuantity,0)) AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.SubsDemo
    ON ss.ActivityType IN (50,51,52,53,59) AND ss.ActivityRowId = ID
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
LEFT JOIN `Job1111`.SubsMisc smd
    ON smd.ID = ss.ActivityRowId AND ss.ActivityType = 91 AND td.ECT = "D" AND smd.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12)
AND ss.ActivityType IN (50,51,52,53,59,91)
HAVING InstalledQuantity > 0;

DROP TABLE IF EXISTS `Job1111`.`TempPipeCSM`;
CREATE TEMPORARY TABLE `Job1111`.`TempPipeCSM`(
INDEX `TempPipeCSM` (`fk_BidIDAssigned` ASC, `PSAActivityID` ASC)
)
SELECT ss.PSAActivityID, ss.fk_BidIDAssigned, MiscQuantity AS InstalledQuantity
FROM `Job1111`.SubmissionStatus ss
LEFT JOIN `Job1111`.`TempTrackerDetailsPipe` td
    ON td.BidID = ss.fk_BidIDAssigned
JOIN `Job1111`.SubsMisc sm
    ON ss.ActivityType = 91 AND ss.ActivityRowId = sm.ID AND td.PipingActivityType = "MISC"  AND td.ECT != "D" AND sm.MiscRework = 0
WHERE ss.fk_ActivityStatus IN (5,12);

### Prepare Queries to execute ###
PREPARE BuildTempQuery1 FROM @TempQuery1;
PREPARE BuildTempQuery2 FROM @TempQuery2;
PREPARE BuildGetQuery FROM @GetQuery;

### Execute Prep Queries ###
EXECUTE BuildTempQuery1;
EXECUTE BuildTempQuery2;
EXECUTE BuildGetQuery;

### Deallocate Execute Querys and Tables###
DEALLOCATE PREPARE BuildTempQuery1;
DEALLOCATE PREPARE BuildTempQuery2;
DEALLOCATE PREPARE BuildGetQuery;

END$$
DELIMITER ;

Body:
The stored procedure is perfectly sound.  Except for one item.   Due to the fact that some prepared statements use Temp tables made by other prepared statements.  Care needs to be taken to Prepare AND EXECUTE the statements in the right order.

Change This

### Prepare Queries to execute ###
PREPARE BuildTempQuery1 FROM @TempQuery1;
PREPARE BuildTempQuery2 FROM @TempQuery2;
PREPARE BuildGetQuery FROM @GetQuery;

### Execute Prep Queries ###
EXECUTE BuildTempQuery1;
EXECUTE BuildTempQuery2;
EXECUTE BuildGetQuery;

### Deallocate Execute Querys and Tables###
DEALLOCATE PREPARE BuildTempQuery1;
DEALLOCATE PREPARE BuildTempQuery2;
DEALLOCATE PREPARE BuildGetQuery;

To This

### Prepare Pass 1 Queries to execute ###
PREPARE BuildTempQuery1 FROM @TempQuery1;
PREPARE BuildTempQuery2 FROM @TempQuery2;

### Execute Pass 1 Queries ###
EXECUTE BuildTempQuery1 ;
EXECUTE BuildTempQuery2 ;

### Prepare Pass 2 Queries to execute ###
PREPARE BuildGetQuery FROM @GetQuery;

### Execute Pass 2 Queries ###
EXECUTE BuildGetQuery;

### Deallocate Execute Querys and Tables###
DEALLOCATE PREPARE BuildTempQueryER;
DEALLOCATE PREPARE BuildTempQueryERT;
DEALLOCATE PREPARE BuildGetQuery;

Explanation

The reason this is needed, is since "BuildGetQuery" is looking for the Temp Table created by "BuildTempQuery1".  It must exist BEFORE PREPARE of BuildGetQuery.

The mistake was thinking the "Do these tables exist?" check performed during the execution of "BuildGetQuery" where looking for tables made in  BuildTempQuery1 and BuildTempQuery1 happen at EXECUTE and not at PREPARE.

Turns out this check happens at PREPARE of "BuildGetQuery".  Meaning the Temp queries need to first be executed.

The one peace I'm missing is where in the MySQL documentation this reality is explained/demonstrated.

ContentLicense: CC BY-SA 4.0


问:
Actively rendering a JComponent
I am deploying a classic active-rendering graphical application in Java. In this setting, I am given a Graphics2D g component on which I can paint (e.g. boxes, text, shapes) using g.draw... operations.

Now, I want to re-use a Swing components, such as JLabel. Therefore, I would like to do something like g.draw(new JLabel("Hello World!"));.
However, this primitive is not available for Graphics2D objects.

Do you know a workaround I could rely on, please?

答:
From VGR:
You can use SwingUtilities.paintComponent. However, if you just want to put the contents of a JLabel in your Graphics, you might be better off using SwingUtilities.layoutCompoundLabel.

Title: Actively rendering a JComponent


问:
Cannot create a compilation in Roslyn from source code
For test purposes, I need to get a System.Reflection.Assembly from a string source which contains a source code. I am using Roslyn:

```<code>SyntaxTree tree = CSharpSyntaxTree.ParseText(source);
CSharpCompilation compilation = CSharpCompilation.Create("TestCompilation", new[] { tree });

Assembly assembly = null;
using (var stream = new MemoryStream())
{
    var emitResult = compilation.Emit(stream);
    if (!emitResult.Success)
    {
        var message = emitResult.Diagnostics.Select(d => d.ToString())
            .Aggregate((d1, d2) => $"{d1}{Environment.NewLine}{d2}");

        throw new InvalidOperationException($"Errors!{Environment.NewLine}{message}");
    }

    stream.Seek(0, SeekOrigin.Begin);
    assembly = Assembly.Load(stream.ToArray());
}
</code>```

As you can see my attempt here is to emit a CSHarpCompilation object so that I can get the Assembly later. I am trying to do this with:

```<code>var source = @"
  namespace Root.MyNamespace1 {
    public class MyClass {
    }
  }
";
</code>```

Emit errors

But I fail at var emitResult = compilation.Emit(stream) and enter the conditional which shows the error. I get 1 warning and 3 errors:

Warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.

(3,34): Error CS0518: Predefined type 'System.Object' is not defined or imported

(3,34): Error CS1729: 'object' does not contain a constructor that takes 0 arguments

Error CS5001: Program does not contain a static 'Main' method suitable for an entry point

So it seems I need to add reference to mscorelib and it also seems like I need to tell Roslyn that I want to emit a class library, not an executable assembly. How to do that?

答:
You're missing a metadata reference to mscorlib and you can change the compilation options via CSharpCompilationOptions.

Create your compilation as follows:

```<code>var Mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create("TestCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib }, options: options);
</code>```

Body:
For test purposes, I need to get a System.Reflection.Assembly from a string source which contains a source code. I am using Roslyn:

SyntaxTree tree = CSharpSyntaxTree.ParseText(source);
CSharpCompilation compilation = CSharpCompilation.Create("TestCompilation", new[] { tree });

Assembly assembly = null;
using (var stream = new MemoryStream())
{
    var emitResult = compilation.Emit(stream);
    if (!emitResult.Success)
    {
        var message = emitResult.Diagnostics.Select(d => d.ToString())
            .Aggregate((d1, d2) => $"{d1}{Environment.NewLine}{d2}");

        throw new InvalidOperationException($"Errors!{Environment.NewLine}{message}");
    }

    stream.Seek(0, SeekOrigin.Begin);
    assembly = Assembly.Load(stream.ToArray());
}

As you can see my attempt here is to emit a CSHarpCompilation object so that I can get the Assembly later. I am trying to do this with:

var source = @"
  namespace Root.MyNamespace1 {
    public class MyClass {
    }
  }
";

Emit errors

But I fail at var emitResult = compilation.Emit(stream) and enter the conditional which shows the error. I get 1 warning and 3 errors:

Warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.

(3,34): Error CS0518: Predefined type 'System.Object' is not defined or imported

(3,34): Error CS1729: 'object' does not contain a constructor that takes 0 arguments

Error CS5001: Program does not contain a static 'Main' method suitable for an entry point

So it seems I need to add reference to mscorelib and it also seems like I need to tell Roslyn that I want to emit a class library, not an executable assembly. How to do that?

Body:
You're missing a metadata reference to mscorlib and you can change the compilation options via CSharpCompilationOptions.

Create your compilation as follows:

var Mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create("TestCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib }, options: options);


答:
You should use:

```<code>a.set_index(['Date'], inplace=True)
</code>```

As listed here:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html

Or, if you want a new dataframe:

```<code>b = a.set_index(['Date'])
</code>```

Title: Python dataframe indexing - can not reindex?

Body:
Indexing a panda dataframe using set_index or reindex did not work as intended. Am I missing something? Thanks for the help. See the example below. Use a.set_index(['Date']) getting same result

print(a)
a.reindex(['Date'])
print(a.index)
   Adj_Close      Close       Date       High        Low       Open Symbol  \
3  53.015032  54.799999 2016-01-04  54.799999  53.389999  54.320000   MSFT
2  53.256889  55.049999 2016-01-05  55.389999  54.540001  54.930000   MSFT
1  52.289462  54.049999 2016-01-06  54.400002  53.639999  54.320000   MSFT
0  50.470697  52.169998 2016-01-07  53.490002  52.070000  52.700001   MSFT

     Volume  price_gap    target
3  53778000        NaN  0.479999
2  34079700   0.130001  0.119999
1  39518900  -0.729999 -0.270001
0  56564900  -1.349998 -0.530003

Body:
You should use:

a.set_index(['Date'], inplace=True)

As listed here:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html

Or, if you want a new dataframe:

b = a.set_index(['Date'])


问:
Tensorflow Layers Api Linear Activation Function
This question is similar to this question: How to use a linear activation function in TensorFlow? however not the same.

On the final dense layer I want to output 28 nodes with a linear activation, not a sigmoid.  I am using the new layers api as shown here: https://www.tensorflow.org/tutorials/layers

My final layer stack looks like this however:

```<code>flat = tf.reshape(pool3, [-1, 128 * 128 * 128]) #width (after poolings), height (after poolings), filters
dense1 = tf.layers.dense(inputs=flat, units=4096, activation=tf.nn.relu)
dense2 = tf.layers.dense(inputs=dense1, units=4096, activation=tf.nn.relu)
dropout = tf.layers.dropout(
            inputs=dense2, rate=0.4, training=mode == learn.ModeKeys.TRAIN)
output = tf.layers.dense(inputs=dropout, units=28)
</code>```

How does on ensure that the output of the 28 nodes is in fact linear?  In CNTK, you specify an activation function as None (see here: cntk linear activation function in layers? )

Pointers is greatly appreciated.  Thanks!

答:
The documentation of dense says about the activation parameter:

activation: Activation function (callable). Set it to None to maintain a linear activation.

None is the default value, so not specifying the activation sets it to linear.

Body:
This question is similar to this question: How to use a linear activation function in TensorFlow? however not the same.

On the final dense layer I want to output 28 nodes with a linear activation, not a sigmoid.  I am using the new layers api as shown here: https://www.tensorflow.org/tutorials/layers

My final layer stack looks like this however:

flat = tf.reshape(pool3, [-1, 128 * 128 * 128]) #width (after poolings), height (after poolings), filters
dense1 = tf.layers.dense(inputs=flat, units=4096, activation=tf.nn.relu)
dense2 = tf.layers.dense(inputs=dense1, units=4096, activation=tf.nn.relu)
dropout = tf.layers.dropout(
            inputs=dense2, rate=0.4, training=mode == learn.ModeKeys.TRAIN)
output = tf.layers.dense(inputs=dropout, units=28)

How does on ensure that the output of the 28 nodes is in fact linear?  In CNTK, you specify an activation function as None (see here: cntk linear activation function in layers? )

Pointers is greatly appreciated.  Thanks!


问:
How to return ids on Inserts with mybatis in mysql with annotations

See this related question for Postgres. For some reason, the solution doesn't work for me - the return value of the insert statement is always "1".

See this other question for an XML based solution. I would like to do the same without XML - insert a record and find the new auto-generated id of the record I just insreted.

I didn't find a matching annotation to <selectkey> (see this open issue)
How do I proceed?

Examining mybatis code reveals that INSERT is implemented via UPDATE, and always returns the number of inserted rows! So ... unless I'm completely missing something here, there's no way to do this using the current (3.0.3) implementation.

答:
The <insert>, <update>and <delete> statements return the number of affected rows, as is common with database APIs.

If a new ID is generated for the inserted row, it is reflected in the object you passed as a parameter. So for example, if you call mapper.insert(someObject) inside your annotated insert method, after inserting, you can call someObject.getId (or similar) to retrieve it.

Using the options of <insert>, you can tweak how (by providing an SQL statement) and when (before or after the actual insertion) the id is generated or retrieved, and where in the object it is put.

It may be instructive to use the MyBatis generator to generate classes from a database schema and have a look at how inserts and updates are handled. Specifically, the generator produces "example" classes that are used as temporary containers to pass around data.

ContentLicense: CC BY-SA 2.5


问:
Disable popup message in Magento 2.0
I am designing my own theme in Magento for the first time (without any base theme).

By default Magento loads a popup message that says "Checkout out as a new customer Creating an account has many benefits:...".

The question: How can I disable this message?

I know I can hide it using CSS, but I would like to remove it from the HTML code.

Thanks!

答:
To remove this notification popup message.

Login to your Magento Admin Panel
Go to System >> Configuration >> Advanced
Disable the Mage_Admin Notification module

Title: Disable popup message in Magento 2.0


问:
Hybrid DotNet Core/.NET Framework Build with MSBuild
dotnet msbuild

from the sln directory works

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe
</code>```

from the solution directory works

I don't want VS 2017 to have to be installed on a build machine, so I installed "Build Tools for Visual Studio 2017" from https://www.visualstudio.com/downloads/.

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\msbuild.exe
</code>```

bombs out on every single project in the sln with the error:

error MSB4019: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk.

In truth - it doesn't exist on disk. It only exists in the VS subfolder at

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks

I have manually tried installing the .NET 4.6 SDK, the .NET Core 1.0 SDK, and .NET Core 1.0.1 SDK (both x86 and x64 versions).

Is there any way to make MSBuild function correctly or is it just irrepairably broken like much else?

答:
The only way I found now is to create a compile configuration where I target all the .NetCore and .net Standard projects and an other for all .Net projects (or simply use the release config).

Then I use MsBuild twice to build.

MSBuild.exe MySolution.sln /p:Configuration=DotNetCore

MSBuild.exe MySolution.sln /p:Configuration=Release

It works for VS2017 solutions.

Body:
dotnet msbuild

from the sln directory works

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe

from the solution directory works

I don't want VS 2017 to have to be installed on a build machine, so I installed "Build Tools for Visual Studio 2017" from https://www.visualstudio.com/downloads/.

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\msbuild.exe

bombs out on every single project in the sln with the error:

error MSB4019: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk.

In truth - it doesn't exist on disk. It only exists in the VS subfolder at

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks

I have manually tried installing the .NET 4.6 SDK, the .NET Core 1.0 SDK, and .NET Core 1.0.1 SDK (both x86 and x64 versions).

Is there any way to make MSBuild function correctly or is it just irrepairably broken like much else?


问:
I want to merge two excel workbooks by specific column data?
The problem I have is I need to merge two excel workbooks by common column data (Column A in both workbooks are the same data - names) but workbook 2 has more individual named data than workbook 1, in column A, so I just want the data from workbook 2 that matches the data from workbook 1 - and to skip over (leave out) the excess data in workbook 2? - if possible I'd also like to only extract certain columns from workbook 2 to merge with workbook 1 also. Is this possible? The files are too big to manually remove unnecessary rows by filter. Thanks</p>

答:
thanks both. Only getting back to this as have been away. Jahknows, in response to your questions, the only column that actually matches is the first column (column A). And yes, I want to append the data from workbook 2 to workbook 1 - based on the names in column A matching in both workbooks - workbook 2 will have more names in column A than workbook 1. this is excess data that is not needed in the appended workbook. </p>

<p>Thanks TDP - I've had a quick play around with the power query and this could be the answer when I've fully figured out how to append what I want and have leave out the excess data I referred to. </p>

Body:
thanks both. Only getting back to this as have been away. Jahknows, in response to your questions, the only column that actually matches is the first column (column A). And yes, I want to append the data from workbook 2 to workbook 1 - based on the names in column A matching in both workbooks - workbook 2 will have more names in column A than workbook 1. this is excess data that is not needed in the appended workbook.

Thanks TDP - I've had a quick play around with the power query and this could be the answer when I've fully figured out how to append what I want and have leave out the excess data I referred to.


问:
Unable to show SQLite data in android app
I'm creating a fitness app in which workout data is entered by a user and saved to 2 tables in an SQLite database (TABLE_CARDIO & TABLE_WEIGHTS). Below is the structure of these 2 tables:

```<code> public static final String DATABASE_NAME = "FitnessTracker.db";
public static final String TABLE_WEIGHTS = "saved_workout_weights";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "EXERCISE";
public static final String COL_4 = "WEIGHT";
public static final String COL_5 = "REPS";
public static final String COL_6 = "SETS";

public static final String TABLE_CARDIO = "saved_workout_cardio";
public static final String COL_1a = "ID";
public static final String COL_2a = "DATE";
public static final String COL_3a = "TIME";
</code>```

I've used 'SQLite Manager' firefox add on, in which I was able to see that data has successfully been saved to both tables. Now I need to retrieve the data and show it in my app when a button is clicked. So I have this below method with a query to get all saved data from both tables:

```<code> public Cursor getWorkoutData() {
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_CARDIO + " CROSS JOIN " + TABLE_WEIGHTS + " ON " + TABLE_CARDIO + ".DATE = " + TABLE_WEIGHTS + ".DATE";
    Cursor result = db.rawQuery(query,null);
    return result;
}
</code>```

I then have the following method in a different java class which either returns the data found from the query as string values OR returns 'Error: No workouts found' if the query doesn't find any results from my database:

```<code>public void viewWorkout() {
    btnShowWorkout.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Cursor result = myDb.getWorkoutData();
                    if (result.getCount() == 0) {
                        //show error
                        messageShow("Error","No workouts found");
                        return;
                    }

                    StringBuffer bfr = new StringBuffer();
                    while (result.moveToNext()) {
                        bfr.append("Id :"+ result.getString(0)+"\n");
                        bfr.append("Date :"+ result.getString(1)+"\n");
                        bfr.append("Time :"+ result.getString(2)+"\n\n");
                        bfr.append("Id :"+ result.getString(0)+"\n");
                        bfr.append("Date :"+ result.getString(1)+"\n");
                        bfr.append("Exercise :"+ result.getString(2)+"\n");
                        bfr.append("Weight :"+ result.getString(3)+"\n");
                        bfr.append("Reps :"+ result.getString(4)+"\n");
                        bfr.append("Sets :"+ result.getString(5)+"\n\n");
                    }

                    //show data
                    messageShow("Past Workouts",bfr.toString());
                }
            }
    );
}
</code>```

My issue is that my app returns the 'Error: No workouts found' even though I have checked my database tables and both are populated. Is there an issue with my query that's not allowing me to get all the data? Any help greatly appreciated!

答:
Try using .moveToFirst.  If it returns false, and you are sure you have data in the database, and the tables have been created, something is wrong with your query.    </p>

```<code>if (!result.moveToFirst) {
                    //show error
                    messageShow("Error","No workouts found");
                    return;
                }
</code>```

Body:
I'm creating a fitness app in which workout data is entered by a user and saved to 2 tables in an SQLite database (TABLE_CARDIO & TABLE_WEIGHTS). Below is the structure of these 2 tables:

 public static final String DATABASE_NAME = "FitnessTracker.db";
public static final String TABLE_WEIGHTS = "saved_workout_weights";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "EXERCISE";
public static final String COL_4 = "WEIGHT";
public static final String COL_5 = "REPS";
public static final String COL_6 = "SETS";

public static final String TABLE_CARDIO = "saved_workout_cardio";
public static final String COL_1a = "ID";
public static final String COL_2a = "DATE";
public static final String COL_3a = "TIME";

I've used 'SQLite Manager' firefox add on, in which I was able to see that data has successfully been saved to both tables. Now I need to retrieve the data and show it in my app when a button is clicked. So I have this below method with a query to get all saved data from both tables:

 public Cursor getWorkoutData() {
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_CARDIO + " CROSS JOIN " + TABLE_WEIGHTS + " ON " + TABLE_CARDIO + ".DATE = " + TABLE_WEIGHTS + ".DATE";
    Cursor result = db.rawQuery(query,null);
    return result;
}

I then have the following method in a different java class which either returns the data found from the query as string values OR returns 'Error: No workouts found' if the query doesn't find any results from my database:

public void viewWorkout() {
    btnShowWorkout.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Cursor result = myDb.getWorkoutData();
                    if (result.getCount() == 0) {
                        //show error
                        messageShow("Error","No workouts found");
                        return;
                    }

                    StringBuffer bfr = new StringBuffer();
                    while (result.moveToNext()) {
                        bfr.append("Id :"+ result.getString(0)+"\n");
                        bfr.append("Date :"+ result.getString(1)+"\n");
                        bfr.append("Time :"+ result.getString(2)+"\n\n");
                        bfr.append("Id :"+ result.getString(0)+"\n");
                        bfr.append("Date :"+ result.getString(1)+"\n");
                        bfr.append("Exercise :"+ result.getString(2)+"\n");
                        bfr.append("Weight :"+ result.getString(3)+"\n");
                        bfr.append("Reps :"+ result.getString(4)+"\n");
                        bfr.append("Sets :"+ result.getString(5)+"\n\n");
                    }

                    //show data
                    messageShow("Past Workouts",bfr.toString());
                }
            }
    );
}

My issue is that my app returns the 'Error: No workouts found' even though I have checked my database tables and both are populated. Is there an issue with my query that's not allowing me to get all the data? Any help greatly appreciated!

Body:
Try using .moveToFirst.  If it returns false, and you are sure you have data in the database, and the tables have been created, something is wrong with your query.

if (!result.moveToFirst) {
                    //show error
                    messageShow("Error","No workouts found");
                    return;
                }


问:
Yii2 DynamicForm: Demo 3: Nested Dynamic Form with types of rooms
Is it possible to have differents types of rooms in the "demo 3: Nested Dynamic Form" and get the rooms separated by their type? For example, if I wanna create the same as the demo 3 shows and adding a type for each room. I want to have rooms type A, rooms type B and rooms type C. Is it possible? (types are preloaded in the database, the user doesn't have to insert a new type nor select one type. If I want to insert a "room type A", I just add it where it belongs)

I've changed the html but the room's array in the controller didn't has all the rooms (because the first ones are overwritten). So, what do I have to do to make it work fine?

In the picture you can see the approach, I want to make it work because by just editing the html didn't work.

答:
Ok, here is my solution:

Create 2 more clases extended of "Model". So I have 3 clases: Room (ActiveRecord), RoomB (Model), RoomC (Model). So I can representate the 3 types of room.
The attributes of the two "Model" clases, are the "id" and the "description" of the "ActiveRecord" class (remember, we are talking about Room).
In the "_form.php", I've put two "render('_form-rooms')" more, inside divs with class "col-md-4" to get the separation.

```<code><td>
<div class="row">
<div class="col-md-4">
                    <?= $this->render('_form-rooms', [
                        'form' => $form,
                        'indexHouse' => $indexHouse,
                        'modelsRoom' => $modelsRoom[$indexHouse],
                    ]) ?>

<button type="button" class="remove-house btn btn-danger btn-xs"><span class="fa fa-minus"></span></button>
</div>
<div class="col-md-4">
                    <?= $this->render('_form-rooms', [
                        'form' => $form,
                        'indexHouse' => $indexHouse,
                        'modelsRoom' => $modelsRoomB[$indexHouse],
                    ]) ?>

<button type="button" class="remove-house btn btn-danger btn-xs"><span class="fa fa-minus"></span></button>
</div>
<div class="col-md-4">
                    <?= $this->render('_form-rooms', [
                        'form' => $form,
                        'indexHouse' => $indexHouse,
                        'modelsRoom' => $modelsRoomC[$indexHouse],
                    ]) ?>

<button type="button" class="remove-house btn btn-danger btn-xs"><span class="fa fa-minus"></span></button>
</div>
</div>
                </td>
</code>```

In the "actionCreate", I've made 2 extra arrays representing the 2 "Model" clases, so I have those 3 arrays: $modelsRoom = [[new Room]]; $modelsRoomB = [[new RoomB]]; $modelsRoomC = [[new RoomC]];
I've changed all the logic of the code inside "actionCreate" ad hoc with the two extra arrays, so, for example, in the "isset($_POST['Room'][0][0])", I've asking for "isset($_POST['RoomB'][0][0])" and "isset($_POST['RoomC'][0][0])" as well:

```<code>// validate person and houses models
           $valid = $modelPerson->validate();
           $valid = Model::validateMultiple($modelsHouse) && $valid;
           $valid2 = $valid3 = $valid;

           if (isset($_POST['Room'][0][0])) {
               foreach ($_POST['Room'] as $indexHouse => $rooms) {
                   foreach ($rooms as $indexRoom => $room) {
                       $data['Room'] = $room;
                       $modelRoom = new Room;
                       $modelRoom->load($data);
                       $modelsRoom[$indexHouse][$indexRoom] = $modelRoom;
                       $valid = $modelRoom->validate();
                   }
               }
           }

           if (isset($_POST['RoomB'][0][0])) {
               foreach ($_POST['RoomB'] as $indexHouse => $rooms) {
                   foreach ($rooms as $indexRoom => $room) {
                       $data['Room'] = $room;
                       $modelRoom = new Room;
                       $modelRoom->load($data);
                       $modelsRoomB[$indexHouse][$indexRoom] = $modelRoom;
                       $valid2 = $modelRoom->validate();
                   }
               }
           }

           if (isset($_POST['RoomC'][0][0])) {
               foreach ($_POST['RoomC'] as $indexHouse => $rooms) {
                   foreach ($rooms as $indexRoom => $room) {
                       $data['Room'] = $room;
                       $modelRoom = new Room;
                       $modelRoom->load($data);
                       $modelsRoomC[$indexHouse][$indexRoom] = $modelRoom;
                       $valid3 = $modelRoom->validate();
                   }
               }
           }
</code>```

so I ask if the 2 extra "valid" variables are true to continue

```<code>if ($valid && $valid2 && $valid3) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $modelPerson->save(false)) {
                        foreach ($modelsHouse as $indexHouse => $modelHouse) {

                            if ($flag === false) {
                                break;
                            }

                            ... (continue with the same code)
</code>```

and, in the render of the form, I've pass as a parameter the extra arrays created:

```<code>return $this->render('create', [
            'modelPerson' => $modelPerson,
            'modelsHouse' => (empty($modelsHouse)) ? [new House] : $modelsHouse,
            'modelsRoom' => (empty($modelsRoom)) ? [[new Room]] : $modelsRoom,
            'modelsRoomB' => (empty($modelsRoomB)) ? [[new RoomB]] : $modelsRoomB,
            'modelsRoomC' => (empty($modelsRoomC)) ? [[new RoomC]] : $modelsRoomC,
        ]);
</code>```

In the "_form.php" view, you can see the code above, I've used the two extra arrays in the render of the two extra "_form-rooms".

In the "_form-rooms", I've removed the code representing the model's id, because in the "actionUpdate", I've remove all the "Houses", so, all their "rooms" will be deleted too. After this, I've just do the same as in the "actionCreate" (after the post).

I hope you can understand my solution. It maybe not the best solution, but it works for me. There are more details that I've omited to not to extend too much this reply, but you can always contact me ;)

If you need more details, email me.

Body:
Ok, here is my solution:

Create 2 more clases extended of "Model". So I have 3 clases: Room (ActiveRecord), RoomB (Model), RoomC (Model). So I can representate the 3 types of room.
The attributes of the two "Model" clases, are the "id" and the "description" of the "ActiveRecord" class (remember, we are talking about Room).
In the "_form.php", I've put two "render('_form-rooms')" more, inside divs with class "col-md-4" to get the separation.

<td>
<div class="row">
<div class="col-md-4">
                    <?= $this->render('_form-rooms', [
                        'form' => $form,
                        'indexHouse' => $indexHouse,
                        'modelsRoom' => $modelsRoom[$indexHouse],
                    ]) ?>

<button type="button" class="remove-house btn btn-danger btn-xs"><span class="fa fa-minus"></span></button>
</div>
<div class="col-md-4">
                    <?= $this->render('_form-rooms', [
                        'form' => $form,
                        'indexHouse' => $indexHouse,
                        'modelsRoom' => $modelsRoomB[$indexHouse],
                    ]) ?>

<button type="button" class="remove-house btn btn-danger btn-xs"><span class="fa fa-minus"></span></button>
</div>
<div class="col-md-4">
                    <?= $this->render('_form-rooms', [
                        'form' => $form,
                        'indexHouse' => $indexHouse,
                        'modelsRoom' => $modelsRoomC[$indexHouse],
                    ]) ?>

<button type="button" class="remove-house btn btn-danger btn-xs"><span class="fa fa-minus"></span></button>
</div>
</div>
                </td>

In the "actionCreate", I've made 2 extra arrays representing the 2 "Model" clases, so I have those 3 arrays: $modelsRoom = [[new Room]]; $modelsRoomB = [[new RoomB]]; $modelsRoomC = [[new RoomC]];
I've changed all the logic of the code inside "actionCreate" ad hoc with the two extra arrays, so, for example, in the "isset($_POST['Room'][0][0])", I've asking for "isset($_POST['RoomB'][0][0])" and "isset($_POST['RoomC'][0][0])" as well:

// validate person and houses models
           $valid = $modelPerson->validate();
           $valid = Model::validateMultiple($modelsHouse) && $valid;
           $valid2 = $valid3 = $valid;

           if (isset($_POST['Room'][0][0])) {
               foreach ($_POST['Room'] as $indexHouse => $rooms) {
                   foreach ($rooms as $indexRoom => $room) {
                       $data['Room'] = $room;
                       $modelRoom = new Room;
                       $modelRoom->load($data);
                       $modelsRoom[$indexHouse][$indexRoom] = $modelRoom;
                       $valid = $modelRoom->validate();
                   }
               }
           }

           if (isset($_POST['RoomB'][0][0])) {
               foreach ($_POST['RoomB'] as $indexHouse => $rooms) {
                   foreach ($rooms as $indexRoom => $room) {
                       $data['Room'] = $room;
                       $modelRoom = new Room;
                       $modelRoom->load($data);
                       $modelsRoomB[$indexHouse][$indexRoom] = $modelRoom;
                       $valid2 = $modelRoom->validate();
                   }
               }
           }

           if (isset($_POST['RoomC'][0][0])) {
               foreach ($_POST['RoomC'] as $indexHouse => $rooms) {
                   foreach ($rooms as $indexRoom => $room) {
                       $data['Room'] = $room;
                       $modelRoom = new Room;
                       $modelRoom->load($data);
                       $modelsRoomC[$indexHouse][$indexRoom] = $modelRoom;
                       $valid3 = $modelRoom->validate();
                   }
               }
           }

so I ask if the 2 extra "valid" variables are true to continue

if ($valid && $valid2 && $valid3) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $modelPerson->save(false)) {
                        foreach ($modelsHouse as $indexHouse => $modelHouse) {

                            if ($flag === false) {
                                break;
                            }

                            ... (continue with the same code)

and, in the render of the form, I've pass as a parameter the extra arrays created:

return $this->render('create', [
            'modelPerson' => $modelPerson,
            'modelsHouse' => (empty($modelsHouse)) ? [new House] : $modelsHouse,
            'modelsRoom' => (empty($modelsRoom)) ? [[new Room]] : $modelsRoom,
            'modelsRoomB' => (empty($modelsRoomB)) ? [[new RoomB]] : $modelsRoomB,
            'modelsRoomC' => (empty($modelsRoomC)) ? [[new RoomC]] : $modelsRoomC,
        ]);

In the "_form.php" view, you can see the code above, I've used the two extra arrays in the render of the two extra "_form-rooms".

In the "_form-rooms", I've removed the code representing the model's id, because in the "actionUpdate", I've remove all the "Houses", so, all their "rooms" will be deleted too. After this, I've just do the same as in the "actionCreate" (after the post).

I hope you can understand my solution. It maybe not the best solution, but it works for me. There are more details that I've omited to not to extend too much this reply, but you can always contact me ;)

If you need more details, email me.