Q:

Complicated multiple select case, variable declarations, range definitions

I developed the code below for a budget template I'm creating from scratch.  The purpose is to populate automatically actual GL data information into my assumptions tab in the workbook. I'm using one particular month as a test.  I have set up the assumptions tab to have about 26 different sections of regional office information in order to determine an appropriate forecast.
Not all GLs are itemized. I've lumped the GLs for a particular expense (other admin) in categories. I have about 5 major categories of spend and the rest of the GLs are considered as "other".  Since the categories are not titled exactly the same as the GL accounts I've had to create a map grid on a separate tab in the workbook to link category names with different GLs.
The end goal is to:

Cycle through each category type on the assumptions tab for each PM region office,
Calculate the total amount for each spend (i.e., Evictions) by PM office plus it's cost center in another workbook,
Calculate the total amount for each spend of Entity code only items from that same other workbook.

The code below only cycle through and calculates the spend for Eviction GLs. I'm looking to improve the code for performance improvement, easier future maintenance(flexibility), and efficiency.  The end goal is to cycle through the different types of spend.  As of right now, my solution to do that is to repeat the variable/range declarations substituting EvictionRg for the next spend, as well as adding another case.
I'm afraid the code will get too long and performance may be at risk.  Any insight and guidance as how I can plan this, modify the code, etc. to help me do this will be greatly appreciated.  I've been at this for three days trying to figure it out by actually drawing a process map and other methods to help me brainstorm and by reading other posts on SO.  I'm afraid I'm at the end of my VBA knowledge.
Sub Try()
'Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

Dim Wb1 As Workbook
Dim Wb2 As Workbook

Set Wb1 = Workbooks("SubModel Forecast_Other Admin v4.xlsm")
Set Wb2 = Workbooks("Feb15 PNL.xlsx")

Dim Wk4 As Worksheet
Set Wk4 = Wb1.Sheets("ASSUMPTIONS")

Dim Wk5 As Worksheet
Set Wk5 = Wb1.Sheets("Validation")

Dim Wk7 As Worksheet
Set Wk7 = Wb1.Sheets("GL Mapping")

Dim Wk1 As Worksheet
Set Wk1 = Wb2.Sheets("det")

Dim fname As String
fname = "Feb15 PNL"

With Wb1  '----submodel
    With Wk5 '---validation tab
        Dim CCCol As Long
        Dim fRowCC As Long
        Dim lRowCC As Long
        CCCol = Wk5.Cells.Find("Cost Center", lookat:=xlWhole).Column
        fRowCC = Wk5.Cells.Find("Cost Center", lookat:=xlWhole).Offset(1, 0).row
        lRowCC = Wk5.Cells.Find("Cost Center", lookat:=xlWhole).End(xlDown).row
        '---Determine cost center code column range and it's corresponding Region Office Name(ClinkRg)
        Dim CCRg As Range
        Set CCRg = Wk5.Range(Wk5.Cells(fRowCC, CCCol), Wk5.Cells(lRowCC, CCCol))
        Dim CLinkRg As Range
        Set CLinkRg = Wk5.Range(Wk5.Cells(fRowCC, CCCol).Offset(0, -1), Wk5.Cells(lRowCC, CCCol).Offset(0, -1))
    End With '----closes W5 Validation tab

    '----Grid that contains GL accounts and their category type
    With Wk7
        Dim MapGLCol As Long
        MapGLCol = Wk7.Cells.Find("GL", lookat:=xlWhole).Column
        Dim MapfRow As Long
        MapfRow = Wk7.Cells.Find("GL", lookat:=xlWhole).Offset(1, 0).row
        Dim MaplRow As Long
        MaplRow = Wk7.Cells(rows.Count, MapGLCol).End(xlUp).row
        Dim MapGLRg As Range
        Set MapGLRg = Wk7.Range(Wk7.Cells(MapfRow, MapGLCol), Wk7.Cells(MapfRow, MapGLCol))
        Dim TypeRg As Range
        Set TypeRg = Wk7.Range(Wk7.Cells(MapfRow, MapGLCol).Offset(0, -1), Wk7.Cells(MaplRow, MapGLCol).Offset(0, -1))
    End With '--closes wk7 - GL Mapping
End With '--closes Wb1 - SubModel file

'---------PNL wkb
With Wb2
    With Wk1

        'If Left(Wk2.Name, 5) = "By PM" Then
            Dim OpsCol As Long
            OpsCol = Wk1.Cells.Find("Property Manager", lookat:=xlWhole).Column
        'Else
         '   OpsCol = Wk1.Cells.Find("Submarket", lookat:=xlWhole).Column
        'End If

        Dim FRow As Long
        Dim LRow As Long
        'Dim ExpCol As Long
        Dim PropCodeCol As Long

        'Dim Expense As String
        'Expense = InputBox("Enter Expense GL")

        'to locate begining and ending row of data on PNL report
        'Identifies the column where the SubMarket names are located for lookup purposes
        'Defines the expense GL column to lookup based on the inputbox above
        FRow = Wk1.Cells.Find("66990000", lookat:=xlPart).Offset(2, 0).row
        LRow = Wk1.Cells.Find("66990000", lookat:=xlPart).End(xlDown).Offset(-1, 0).row
        'ExpCol = Wk1.Cells.Find(Expense, lookat:=xlPart).Column
        PropCodeCol = Wk1.Cells.Find("Property Code", lookat:=xlWhole).Column

        'Defines the Range of the PM
        Dim OpsRg As Range
        Set OpsRg = Wk1.Range(Wk1.Cells(FRow, OpsCol), Wk1.Cells(LRow, OpsCol))

        'Defines the Range of the Property Codes
        Dim PropCodeRg As Range
        Set PropCodeRg = Wk1.Range(Wk1.Cells(FRow, PropCodeCol), Wk1.Cells(LRow, PropCodeCol))

        'Defines the exact range of the expense column being analyzed
        'Dim ExpRg As Range
        'Set ExpRg = Wk1.Range(Wk1.Cells(FRow, ExpCol), Wk1.Cells(LRow, ExpCol))

        'Defining range for GLs under Other Admin
        Dim GLRow As Long
        Dim BegGLCol As Long
        Dim EndGLCol As Long
        GLRow = Wk1.Cells.Find("66550000", lookat:=xlPart).row
        BegGLCol = Wk1.Cells.Find("66550000", lookat:=xlPart).Column
        EndGLCol = Wk1.Cells.Find("66990000", lookat:=xlPart).Column

        Dim GLRg As Range
        Set GLRg = Wk1.Range(Wk1.Cells(GLRow, BegGLCol), Wk1.Cells(GLRow, EndGLCol))

        '----Find All GL accounts in WB1 Wk5 Validation Tab range TypeRg categorized as Evictions($)
        '----Then Look up each GL account in the row with all the GLs in the current workbook PNL and Wk1
        '----------Set that up as TempCell
        '----------Set the range for the entire column of data for each GL and consolidate as one range 'EvictionRg'
        '----------Purpose of this is to set up one range for all GL accounts categorized as Eviction GL accoutns
        Dim c As Range
        For Each c In TypeRg
            If c = "Evictions ($)" Then
                Dim TempCell As Range
                Set TempCell = GLRg.Find(c.Offset(0, 1).Value, lookat:=xlWhole)
                'MsgBox (TempCell)

                Dim EvictionRg As Range
                If EvictionRg Is Nothing Then
                    Set EvictionRg = Wk1.Range(Wk1.Cells(FRow, TempCell.Column), Wk1.Cells(LRow, TempCell.Column))
                Else
                    Set EvictionRg = Union(EvictionRg, Wk1.Range(Wk1.Cells(FRow, TempCell.Column), Wk1.Cells(LRow, TempCell.Column)))
                End If

            End If
        Next c
        '---Sum up all the amounts under all the GL eviction accounts and set them as "z"
        Dim z As Double
        z = Application.WorksheetFunction.Sum(EvictionRg)

    '---Define Ranges for All Entities, Cost Centers, Entities Not Cost Centers

    'Define the range on the Property PNL workbook all items booked under an entity
    Dim AllEntRg As Range
    Dim cell As Range
    For Each cell In OpsRg
      If cell = "" Then
          If AllEntRg Is Nothing Then
              Set AllEntRg = Wk1.Cells(cell.row, PropCodeCol)
          Else
              Set AllEntRg = Union(AllEntRg, Wk1.Cells(cell.row, PropCodeCol))
          End If
      End If
    Next cell

    'Define the range of the property PNL workbook that are Entity codes that are NOT Cost Center Codes
    '---Entity Codes and Cost Center Codes are within the AllEntRg
    '---Create a new range in the Eviction GL Range that intersects
    '---------the rows of the entity only codes and the eviction GL columns
    With AllEntRg
    Dim EntityRg As Range
    Dim cl As Range
    For Each cl In AllEntRg
            If CCRg.Find(cl.Value, lookat:=xlWhole) Is Nothing Then
                Dim cl2 As Range
                For Each cl2 In EvictionRg '------extra
                If cl2.row = cl.row Then '------extra
                    If EntityRg Is Nothing Then
                        Set EntityRg = cl2
                    Else
                        Set EntityRg = Union(EntityRg, cl2)
                    End If
                End If
                Next cl2
            End If
    Next cl
    'MsgBox (EntityRg.Address)
    Dim v As Double
    v = Application.WorksheetFunction.Sum(EntityRg)
    End With

    'With AllEntRg
    'Dim CostCRg As Range
    'Dim r As Range
    'For Each r In AllEntRg
     '       If Not CCRg.Find(r.Value, lookat:=xlWhole) Is Nothing Then
     '           Dim cl3 As Range
     '           For Each cl3 In EvictionRg
     '           If cl3.row = r.row Then
     '               If CostCRg Is Nothing Then
     '                   Set CostCRg = cl3
     '               Else
     '                   Set CostCRg = Union(CostCRg, cl3)
     '               End If
     '           End If
      '          Next cl3
     '       End If
    'Next r
    'End With
    'MsgBox (CostCRg.Address)

    'Define cell ranges for regional PM offices that contain more than one cost center ocde
    With AllEntRg
        If Not AllEntRg.Find("cahied", lookat:=xlWhole) Is Nothing Then
            Dim n As Range
            Set n = AllEntRg.Find("cahied", lookat:=xlWhole)
        End If
        'MsgBox (n.Address)

        If Not AllEntRg.Find("cahrvr", lookat:=xlWhole) Is Nothing Then
            Dim n2 As Range
            Set n2 = AllEntRg.Find("cahrvr", lookat:=xlWhole)
            'MsgBox (n2.Address)
        End If

        If Not AllEntRg.Find("atlnw", lookat:=xlWhole) Is Nothing Then
            Dim an1 As Range
            Set an1 = AllEntRg.Find("atlnw", lookat:=xlWhole)
            'MsgBox (an1.Address)
        End If

        If Not AllEntRg.Find("atln", lookat:=xlWhole) Is Nothing Then
            Dim an2 As Range
            Set an2 = AllEntRg.Find("atln", lookat:=xlWhole)
            'MsgBox (an2.Address)
        End If

        If Not AllEntRg.Find("atlse", lookat:=xlWhole) Is Nothing Then
            Dim ae1 As Range
            Set ae1 = AllEntRg.Find("atlse", lookat:=xlWhole)
            'MsgBox (ae1.Address)
        End If

        If Not AllEntRg.Find("atle", lookat:=xlWhole) Is Nothing Then
            Dim ae2 As Range
            Set ae2 = AllEntRg.Find("atle", lookat:=xlWhole)
            'MsgBox (ae2.Address)
        End If

        If Not AllEntRg.Find("atlsw", lookat:=xlWhole) Is Nothing Then
            Dim as1 As Range
            Set as1 = AllEntRg.Find("atlsw", lookat:=xlWhole)
            'MsgBox (as1.Address)
        End If

        If Not AllEntRg.Find("atls", lookat:=xlWhole) Is Nothing Then
            Dim as2 As Range
            Set as2 = AllEntRg.Find("atls", lookat:=xlWhole)
            'MsgBox (as2.Address)
        End If
    End With

        '---Create a new range in the Eviction GL Range that intersects
        '---------the rows of the specific cost center codes and the eviction GL columns
        If Not n Is Nothing Or Not n2 Is Nothing Then
            Dim n3 As Range
            For Each n3 In EvictionRg
               If n3.row = n.row Or n3.row = n2.row Then
                    Dim InlandRg As Range
                    If InlandRg Is Nothing Then
                        Set InlandRg = n3
                    Else
                        Set InlandRg = Union(InlandRg, n3)
                    End If
                End If
            Next n3
        End If
                Dim n3v As Double
                n3v = Application.WorksheetFunction.Sum(InlandRg)

        If Not an1 Is Nothing Or Not an2 Is Nothing Then
            Dim an3 As Range
            For Each an3 In EvictionRg
               If an3.row = an1.row Or an3.row = an2.row Then
                    Dim ATLNrg As Range
                    If ATLNrg Is Nothing Then
                        Set ATLNrg = an3
                    Else
                        Set ATLNrg = Union(ATLNrg, an3)
                    End If
                End If
            Next an3
        End If
                Dim an3v As Double
                an3v = Application.WorksheetFunction.Sum(ATLNrg)

        If Not ae1 Is Nothing Or Not ae2 Is Nothing Then
            Dim ae3 As Range
            For Each ae3 In EvictionRg
               If ae3.row = ae1.row Or ae3.row = ae2.row Then
                    Dim ATLErg As Range
                    If ATLErg Is Nothing Then
                        Set ATLErg = ae3
                    Else
                        Set ATLErg = Union(ATLErg, ae3)
                    End If
                End If
            Next ae3
        End If
                Dim ae3v As Double
                ae3v = Application.WorksheetFunction.Sum(ATLErg)

        If Not as1 Is Nothing Or Not as2 Is Nothing Then
            Dim as3 As Range
            For Each as3 In EvictionRg
               If as3.row = as1.row Or as3.row = as2.row Then
                    Dim ATLSrg As Range
                    If ATLSrg Is Nothing Then
                        Set ATLSrg = as3
                    Else
                        Set ATLSrg = Union(ATLSrg, as3)
                    End If
                End If
            Next as3
        End If
                Dim as3v As Double
                as3v = Application.WorksheetFunction.Sum(ATLSrg)

    End With '---closes Wk1 (PNL report)
End With '--closes wb2

''--------Cycle through the different PM regional office section (column) in assumptions tab
'---------Identify where Evictions ($) is located
'---------calculate total eviction GL amounts for each section (by Entity code only, by PM + cost center code)

With Wb1
With Wk4

    Wk4.Outline.ShowLevels RowLevels:=2

    Dim dateRow As Long
    dateRow = Wk4.Cells.Find("ACT", lookat:=xlWhole).Offset(1, 0).row

    Dim fRow2 As Long
    Dim AssumCol As Long
    Dim lRow2 As Long
    fRow2 = Wk4.Cells.Find("Global Assumptions", lookat:=xlWhole).row
    AssumCol = Wk4.Cells.Find("Global Assumptions", lookat:=xlWhole).Column
    lRow2 = Wk4.Cells(rows.Count, AssumCol).End(xlUp).row

    Dim AssumptionRg As Range
    Set AssumptionRg = Wk4.Range(Wk4.Cells(fRow2, AssumCol), Wk4.Cells(lRow2, AssumCol))

    Dim r2 As Range
    Dim isItem As Boolean

        For Each r2 In AssumptionRg
            Select Case r2
                Case "Evictions ($)"
                    isItem = True
                    Dim PM As Range
                    Set PM = r2.End(xlUp)
                        '---If PM Label is Entity Level, Inland Empire or is one of the Atlanta PMs then
                        '-----IF Entity Level, the sum up the Entity Range for the Evictions
                        '-----IF Inland Empire, sum up Inland Empire properties and Inland Empire Cost Center entries
                        '-----IF Atlanta, the sum up Atlanta PMs and their cost center entries individually
                        If PM = "Tie-Out To Actuals" Or PM = "Entity Level Assumptions" _
                        Or PM = "Inland Empire" Or PM = "Atlanta East" _
                        Or PM = "Atlanta North" Or PM = "Atlanta South" Then

                            If PM = "Tie-Out To Actuals" Then
                                Wk4.Cells(r2.row, 4) = z
                            End If

                            If PM = "Entity Level Assumptions" Then
                                Wk4.Cells(r2.row, 4) = v
                            End If

                            If PM = "Inland Empire" Then
                                    Wk4.Cells(r2.row, 4).Formula = _
                                    "=SUMPRODUCT(('[" & fname & ".xlsx]det'!" & OpsRg.Address & "=" & PM.Address & ")*'[" & fname & ".xlsx]det'!" & EvictionRg.Address & ")" _
                                    & "+" & n3v
                                    Wk4.Cells(r2.row, 4).Value = Wk4.Cells(r2.row, 4).Value
                            End If

                            If PM = "Atlanta East" Then
                                Wk4.Cells(r2.row, 4).Formula = _
                                "=SUMPRODUCT(('[" & fname & ".xlsx]det'!" & OpsRg.Address & "=" & PM.Address & ")*'[" & fname & ".xlsx]det'!" & EvictionRg.Address & ")" _
                                & "+" & ae3v
                            End If

                            If PM = "Atlanta North" Then
                                Wk4.Cells(r2.row, 4).Formula = _
                                "=SUMPRODUCT(('[" & fname & ".xlsx]det'!" & OpsRg.Address & "=" & PM.Address & ")*'[" & fname & ".xlsx]det'!" & EvictionRg.Address & ")" _
                                & "+" & an3v
                            End If

                            If PM = "Atlanta South" Then
                                Wk4.Cells(r2.row, 4).Formula = _
                                "=SUMPRODUCT(('[" & fname & ".xlsx]det'!" & OpsRg.Address & "=" & PM.Address & ")*'[" & fname & ".xlsx]det'!" & EvictionRg.Address & ")" _
                                & "+" & as3v
                            End If

                        Else

                            Dim CCCodeRow As Long
                            Dim CCCodeCol As Long
                            CCCodeRow = CLinkRg.Find(PM.Value, lookat:=xlWhole).Offset(0, 1).row
                            CCCodeCol = CLinkRg.Find(PM.Value, lookat:=xlWhole).Offset(0, 1).Column

                            If Wk5.Cells(CCCodeRow, CCCodeCol).Value = "None" Then
                                Wk4.Cells(r2.row, 4).Formula = _
                                "=SUMPRODUCT(('[" & fname & ".xlsx]det'!" & OpsRg.Address & "=" & PM.Address & ")*'[" & fname & ".xlsx]det'!" & EvictionRg.Address & ")"
                            Else
                                Wk4.Cells(r2.row, 4).Formula = _
                                "=SUMPRODUCT(('[" & fname & ".xlsx]det'!" & OpsRg.Address & "=" & PM.Address & ")*'[" & fname & ".xlsx]det'!" & EvictionRg.Address & ")" _
                                & "+SUMPRODUCT(('[" & fname & ".xlsx]det'!" & PropCodeRg.Address & "=" & "Validation!" & Wk5.Cells(CCCodeRow, CCCodeCol).Address & ")*'[" & fname & ".xlsx]det'!" & EvictionRg.Address & ")"
                            End If
                        End If
           End Select
        Next r2

    Set r2 = Nothing
    Set Wk4 = Nothing
End With '---closes assumptions tab
End With '---workbook2
'Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

A:

Whew, that is quite the read!  Although I agree with Comintern, I do see a pretty simple solution to trimming up your code, and making it easier to maintain.
I don't see a single function in the entire thing.  If you're writing scripts that long, and not using them, you need to start... They'll change your life.
Lets take a simple block that I see repeated several (8) times.  Note that I see several much larger blocks that are repeated throughout, but this one will be easy to learn on.
If Not AllEntRg.Find("atlsw", lookat:=xlWhole) Is Nothing Then
    Dim as1 As Range
    Set as1 = AllEntRg.Find("atlsw", lookat:=xlWhole)
End If

I only see three things that change from if to if in this part of the code, 2 on the input side are a range and a string, and it outputs a range if conditions are met.  So you write a function like this, and place it somewhere in any module in the same workbook.
Public Function DefMultiCCPMRange(rngSearchRange as range, strSearchString as string)as range
    If Not AllEndRg.Find(strSearchString, lookat:=xlWhole) Is Nothing Then
        set DefMultiCCPMRange = rngSearchRange.Find(strSearchString, Lookat:=xlWhole)
    End If
End Function

Now instead of rewriting this over and over.
If Not AllEntRg.Find("atlsw", lookat:=xlWhole) Is Nothing Then
    Dim as1 As Range
    Set as1 = AllEntRg.Find("atlsw", lookat:=xlWhole)
End If

You write this over and over.
Dim as1 as Range
set as1 = DefMultiCCPMRange(AllEndRg,"atlsw")

Also the lifetime of the variables that are used in the function, ends when the function ends, so your not storing every variable you use in memory for the entire duration of runtime.
That should take you a long way if you play with it.
I would also look into Arrays, Collections, and Dictionary items.  They'll change your life too once you see where their power really lies.  You could get creative and instead of declaring and setting that range 8 times, you could do a for loop, and put them all in one object named for the CC Code.
Dim arrCCCodes(3) as string 'change to arrCCCodes(7) for your 8 codes
arrCCCodes(0) = "cahied"
arrCCCodes(1) = "cahrvr"
arrCCCodes(2) = "atlnw"
arrCCCodes(3) = "atln"
'etc...
'add a reference to Microsoft scripting runtime

Dim odicCCRanges as New Dictionary

For i = 0 to UBound(arrCCCodes)
    odicCCRanges.Add arrCCCodes(i), DefMultiCCPMRange(AllEndRg, arrCCCodes(i))
next

This will give you a dictionary object with 4 ranges in it (would be 8 in your actual code), not to mention lose a couple pages of code.  You would call the values in the range like odicCCRanges("cahied").Item(1) or odicCCRanges(arrCCCodes(0)).Item(1).  Here's where it adds to your project lifetime.  If you need to add a new CC, you just change the arrCCCodes declaration to include one more item, then add it below, and the rest of our code will automatically pick it up, run the define ranges function, and add it to the dictionary.
Your code doesn't look all that bad, your testing for nulls, and declaring your vars, all good stuff. It's just all series scripted. Try stepping through your code, and watching the locals window in the VBA IDE.  Particularly expand a range node after its set.  It'll blow your mind what is actually in a Range Object.


Q:

Is it possible to generate sine tones in Processing.JS?

I am an amateur musician and I teach music basics to school children who have little to no prior music education.
I've coded a small app in Processing.JS which shows the 12 musical notes of the Western scale (A, A#, B, C, C#, D, D#, E, F, F#, G, G#) in a circle, and highlights the relationships between them from which musical scales/intervals are constructed.
I want to be able to touch a particular note name and generate the sine tone associated with that note (the very obvious one being A = ..., 220Hz, 440Hz, 880Hz, ...)
So to break it down, in Processing.JS, is it possible to generate a sine tone of a desired frequency upon detection of a mouse event? If someone can help me work that out, I can figure out the rest.
To be clear: I'm not too good at Javascript, and I'm moderate at Processing, at best. I know Javascript can do stuff like this but I don't know how to integrate the two languages in this webapp.

A:

Like you've hinted at, you're going to have to do this in JavaScript. George's comment is spot-on: you should start by reading through this page.
But basically, the thing to keep in mind is that Processing.js gets converted into JavaScript, so you can call JavaScript code directly from Processing.js.
I'd start by googling something like "JavaScript sine tone" for a ton of results. Tone.js seems to be a library that does what you want, but I'm sure there are many others.
To use the Tone.js library, you need to first import it in your HTML, exactly how you're already importing the Processing.js library:
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/13.3.10/Tone.js"></script>

Then you can use Tone.js in your Processing.js code:
var synth ;

void setup(){
  //create a synth and connect it to the master output (your speakers)
  synth = new Tone.Synth().toMaster();
}

void mousePressed(){
  //play a middle 'C' for the duration of an 8th note
  synth.triggerAttackRelease('C4', '8n')
}

void draw(){}

Note that Processing.js leaves JavaScript code alone when it does the conversion, so your final output is just a bunch of JavaScript code. That's why you can mix JavaScript code and Processing.js code like this.
But also like George said, you should probably consider switching over to P5.js, because Processing.js isn't maintained anymore.
Shameless self-promotion: here is a tutorial on Processing.js, and here are some tutorials on P5.js.


Q:

Stop form validating on first error codeigniter

I'm using CI 3.1.7 and want to stop validating form if there is an error. For example:
$config = array(
    array(
            'field' => 'username',
            'label' => 'Username',
            'rules' => 'required',
            'errors' => array(
                    'required' => '%s is required',
            ),
    ),
    array(
            'field' => 'password',
            'label' => 'Password',
            'rules' => 'required',
            'errors' => array(
                    'required' => '%s is required',
            ),
    ),
    array(
            'field' => 'email',
            'label' => 'Email',
            'rules' => 'required',
            'errors' => array(
                    'required' => '%s is required',
            ),
    )
);

When user leaves username and email blank, the form will show only username is required. Any help is appreciated, thank you!

A:

If i got your question right .. you want to stop on the first encountered form validation error then you have to edit the core form validation library which is extremely bad practice but luckily you can extend its functionality and either edit the run() method itself or create your own method and just copy the run() code and edit this block of code:
    // Execute validation rules
    foreach ($this->_field_data as $field => &$row)
    {
        // Don't try to validate if we have no rules set
        if (empty($row['rules']))
        {
            continue;
        }

        $this->_execute($row, $row['rules'], $row['postdata']);

        // here is the modification
        if(count($this->_error_array) > 0) return true; // error found
    }

now it will stop execution when finding its first error


Q:

Re-sample raster to acre grid using ArcGIS Desktop or R?

I have a 1m classified landcover raster layer that consists of values 1-4 representing various land covers.  I need to resample this layer to an acre grid.  Each acre in the resultant grid should contain the percentage of acre that one of the classification attributes (let's say value #1) comprises.
What's the most efficient way of doing this, considering my raster is quite large (>800 mb)? I assume it involves something like the zonal stats tool in ArcGIS Desktop, but I'm not sure.  I prefer ArcGIS Desktop or R solutions.

A:

That's not really resampling. Resampling would be converting all pixels in each grid square to whichever stat value (mean or max or whatever COUNTS not values since it's categorical data). But you want four values per cell, not one. It's categorical, so zonal stats won't work because it doesn't offer a count stat.
I believe you'll want Zonal Histogram. Your first step is to create the one acre grid, which you would use the Create Fishnet tool for (and make sure it's polygons). You can then use that as your zones in the Zonal Histogram tool.


Q:

Magento 2 How to override sales.order.items.renderers block in sales_order_view page?

I am trying to override sales_order_view.xml file sales.order.items.renderers block, I have followed below mentioned code but not worked:
overriding sales_order_view.xml in custom module :
Method 1 :
 <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="order_items">
                <block class="Magento\Framework\View\Element\RendererList" name="sales.order.items.renderers" as="renderer.list" template="Vendor_Namespace::order/items/renderer/default.phtml"/>
            </referenceBlock>

        </body>
    </page>

Method 2 :
<?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="sales.order.items.renderers">
               <arguments>
                    <argument name="template" xsi:type="string">Vendor_Namespace::order/items/renderer/default.phtml</argument>
                </arguments>
            </referenceBlock>
        </body>
    </page>

Method 3 :
<?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="sales.order.items.renderers">
                <action method="setTemplate">
                   <argument name="template" xsi:type="string">Vendor_Namespace::order/items/renderer/default.phtml</argument>
               </action>
            </referenceBlock>
        </body>
    </page>

and I created order/items.renderer/default.phtml file in custom module, but it is not overriding.
Any help will appreciate.

A:

You can use this
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="sales.order.items.renderers.default">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Vendor_Namespace::order/items/renderer/default.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Please use reference block name sales.order.items.renderers.default
Hope this will help you!


Q:

Minimax search: how to print the path from the chosen next move to the leaf

Confusing title. I'll try to elaborate: I have an AI chess game that uses minimax search to generate the computer's next move. After going down the minimax tree to a chosen depth (say 5), it finally finds the next best move to take. For my own testing purposes, I would like to be able to print out this next best move (represented as a chess board configuration), but also the following 4 moves that it used to determine the score for that next move. That is, the path of the best choices at each of the lower levels in the minimax tree, starting with the top node that was eventually chosen to be the best next move. Any ideas?

A:

You want to determine the Principal Variation.

The Principal variation (PV) is a sequence of moves that programs consider best and therefore expect to be played.
-- Chess Programming Wiki

My implementation of a game engine uses the transposition tabe to determine the PV. To print the PV the program does following steps:

move = the best move determined with the last search
Print move
Make move
Get the transposition table entry of the new board
Is the transposition table entry exact?

Yes: move = move stored in the transposition table entry. Go to step 2.
No: Undo moves. Go to step 6.

End


Q:

How to add SVG image to vuetify text field

I am using vuetify and would like to add an SVG icon to the start of the text field. I know you can prepend or append icons from v-icon, but I would like to use my own SVG image in a similar way.

A:

Just use the "prepend" slot:
<v-text-field label="My text field" type="text">

    <template v-slot:prepend>

      <img width="24" height="24" src="[PathToAssets]/whatever.svg" >

    </template>

  </v-text-field>


Q:

How to force div to appear after stretched div

html order is generated from template.
Sample output is below.
Elements in each row have fixed positions and sizes. This is implemented using
row div containing field div with absolute position.
Description element is defined as

RAM 16 GB - SSD 256 GB - DVD SuperMulti - GF GT 730M / HD Graphics 530 - GigE - Windows 7 Professional 64-bit Edition / Windows 10 Pro 64-bit Edition downgrade - pre-installed: Windows 7

Sometimes item description is long and should wrap into multiple lines. For this I tried to remove heights from divs by using

RAM 16 GB - SSD 256 GB - DVD SuperMulti - GF GT 730M / HD Graphics 530 - GigE - Windows 7 Professional 64-bit Edition / Windows 10 Pro 64-bit Edition downgrade - pre-installed: Windows 7

Next row does not move down automatically. First row item description overwrites next row item name:

How to fix this so that next row appers after variable height description ?
Using hard-coded bigger heights like

RAM 16 GB - SSD 256 GB - DVD SuperMulti - GF GT 730M / HD Graphics 530 - GigE - Windows 7 Professional 64-bit Edition / Windows 10 Pro 64-bit Edition downgrade - pre-installed: Windows 7

Fixes the issue but it is fdifficult to calculate correct height since it depends on div content, width, font sizes etc and there are multiple columns in row
How to force browser to render this properly ?
html5, ASP.NET MVC4 and Razor views are used.
Update
Expected result can produced using hard coded heights

and is

**Update 2 **
I tried to use relative position and min-height as recommended in answer using code below. This causes every field to apper in separate row. How to fix this so that multiple fields can appear nearly in same row like with absolute positioning ?
If style below is changed to
    .horizontalline, .field {
        position: absolute;
    }

fields appear poperly but strech causes overlap.
<!DOCTYPE html>

         1

HP ProDesk 490 G3 - Micro tower - 1 x Core i7 6700

31.12.2015

1

tk

1189

1189

RAM 16 GB - SSD 256 GB - DVD SuperMulti - GF GT 730M / HD Graphics 530 - GigE - Windows 7 Professional 64-bit Edition / Windows 10 Pro 64-bit Edition downgrade - pre-installed: Windows 7

         2

24x7 monitor: LG 32SL5B

29.12.2015

3

tk

878,79

580

1740

450cd/m2, HDMI / DP / DVI / RGB / RJ45 /etc, 24/7 Operation, laos

Output is:

A:

Try This:
Your HTML:

            HP ProDesk 490 G3 - Micro tower - 1 x Core i7 6700

tk

1189

1189

RAM 16 GB - SSD 256 GB - DVD SuperMulti - GF GT 730M / HD Graphics 530 - GigE - Windows 7 Professional 64-bit Edition / Windows 10 Pro 64-bit Edition downgrade - pre-installed: Windows 7

2

24x7 monitor: LG 32SL5B

Your CSS:


Q:

Filter by condition if string contains certain substring

I have a dataframe full of emails. Knowing that gmail has a 6 character minimum I want to filter my dataframe by getting rid of any gmail address that has a username of less than six characters. Therefore, the dataframe df
>> print(df)

        email
1   a@gmail.com
2   real.email@gmail.com
3   no.email@email.com
4   real@yahoo.com
5   poo@gmail.com

would become:
        email
2   real.email@gmail.com
3   no.email@email.com
4   real@yahoo.com

Using
df = df[
        (len(df['email'].str.split('@').str[0]) >= 6)
        (df['email'].str.split('@').str[1] == 'gmail.com')
       ]

will filter everything that isn't @gmail.com, so I can't use that. What I want is essentially (which obviously doesn't work and gives a TypeError: 'method' object is not subscriptable)
if df['email'].str.split['@'].str[1] == 'gmail.com':
    len(df['email'].str.split['@'].str[0]) >= 6

How do I accomplish this in a vectorized operation?

A:

You can do:
df=df.loc[~df.email.str.contains(r"^.{0,5}@gmail\.com$")]

Outputs:
                  email
1  real.email@gmail.com
2    no.email@email.com
3        real@yahoo.com


Q:

Getter and Setter problems in Java Spring

So, i have this bean:
<bean id="toMailController" class="com.appointments.kohler.controller.ToEmailController">
    <property name="templateTransformer" ref="templateTransformer"></property>
</bean>

and in my ToEmailController.java i have this (just the important lines):
public ToEmailController extends AbstractController {

public TemplateTransformer _templateTransformer;

@Required
public void setTemplateTransformer(TemplateTransformer templateTransformer)
{
    this._templateTransformer = templateTransformer;
}

public TemplateTransformer getTemplateTransformer()
{
    return this._templateTransformer;
}

}

If i execute this project from Localhost, it runs just fine, but when i put him in weblogic i receive the following error:
org.springframework.beans.NotWritablePropertyException: Invalid property 'templateTransformer' of bean class [com.appointments.kohler.controller.ToEmailController]: Bean property 'templateTransformer' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

But i can't get it. What am i doing wrong? Any ideas?

A:

After thousands of hours, i've tried deploy the project using ANT and it works, after that the BEA WebLogic interface do not gave me the error anymore.
Thanks for every answer!


Q:

CSS animation only loops 3 times then stops

I have a plane that I want to fly back and fourth infinitely. I have a Javascript listener for animationend that works just fine (I think.) It flies right, left, right, and then stops and resets at it's original position. When the listener fires, I just have it switch classes that are linked to the animations I want.
Here's the Javascript:
var runway = document.getElementById("myNavbar");

var plane = document.createElement('div');
plane.id = "plane";
plane.className = "plane-right";

runway.appendChild(plane);

$("#plane").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
    if (plane.className == "plane-right")
    {
        plane.className = "plane-left";
    }
    else
    {
        plane.className = "plane-right";
    }
});

I also understand there's a jQuery toggle() function but I can't get it to work. I tried $("#plane").toggle(".plane-right, .plane-left") inside the listener but that didn't do the trick.
And the CSS class
.plane-right {
    background-image: url("../img/zoomzoom.png");
    background-position: center;
    background-repeat: no-repeat;
    background-size: 100%;
    height: 50px;
    width: 100px;
    animation-name: moveLeftToRight;
    animation-duration: 10s;
    position: relative;
    animation-timing-function: linear;
    pointer-events: none;
}
.plane-left {
    background-image: url("../img/zoomzoom.png");
    background-position: center;
    background-repeat: no-repeat;
    background-size: 100%;
    height: 50px;
    width: 100px;
    -moz-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    transform: scaleX(-1);
    filter: FlipH;
    -ms-filter: "FlipH";
    animation-name: moveRightToLeft;
    animation-duration: 10s;
    position: relative;
    animation-timing-function: linear;
    pointer-events: none;
}

@keyframes moveLeftToRight {
  from   { left: -20%; }
  to { left: 110%; }
}
@keyframes moveRightToLeft {
  from   { left: 110%; }
  to { left: -20%; }
}

Update: I added an alert() to the listener, and the alert does not fire the last time the animation ends before the plane resets position. Not sure if this is significant or helpful, but there it is.

A:

Use "on" instead of "one".  Using "one" only triggers once, although in this case twice and I'm not 100% sure why. It may be multiple event types (webkitanimationend AND animationend), but I'd think those would happen one after another.
https://jsfiddle.net/ftgr6h1e/
$("#plane").on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){

Now, in general, animating position is slow. Consider animating transform3D instead to use the GPU to redraw your plane.


Q:

Getting the user home path in application.properties in Spring Boot

This should be a quite straight forward task, but after doing quite a bit of research I'm finding it hard to find any way to do this.
I just want to create a log file in the current user's home directory. According to the Official Documentation the variables I should modify are logging.file and logging.path. But how do I get the value of the user-home into the logging.path?
I have tried setting it up like:
logging.path=#{systemProperties['user.home']}

but without any success.

A:

If you use Linux or Mac OS, you can use logging.path=${HOME}/logs.
${HOME} is substituted by the environment variable HOME.

A:

I believe I have solved the problem. The log file in question was actually being generated in the class path only when run from the IDE (Eclipse Luna FYI). Later on when I made a jar file and ran that, the log file was being generated in the right location as specified in the application.properties file. I still have no clue to why it was generated in the class path when I ran it from Eclipse.


Q:

On a conceptual question on Theory of Equations.

We have two equations:
$$x^2+y^2=12\tag1$$
$$x^2+y^2-6x-2\sqrt3y=0\tag2$$
From these two equations we get a third equation
$$12-6x-2\sqrt3y=0\tag3$$
Thus
$$x=\frac{12-2\sqrt3y}6  ---(*) $$
Now $x$ is a root for $(3)$. Why isn't it for $(2)$ as well?
Reasoning:
In $(1)$, $x^2+y^2=12$ so basically $(3)$ is $(2)$ with the value of $x^2+y^2$ substituted.
What I tried doing: When I actually put $x$ from $(3)$ in equation $(1,2)$ i actually get the same quadratic $y^2-\sqrt3y-6=0$
Note: I am currently comfortable with algebra-precalculus and single variable calculus.

A:

You might note that geometrically, (1) and (2) are equations of circles.  The two circles intersect at two points.  Equation (3) represents a straight line that passes through both points.  But those are the only points where the line intersects either circle.


Q:

Customize the stroke of a JavaFX polyline

I have a shape that I would like to render as a JavaFX Polyline, but with multiple colours in the stroke. Essentially, it would be an 8-pixel wide blue line with a 2-pixel wide black border on either side of it. I can achieve the same effect by creating a Group, and then adding two Polylines into the Group:
Group group = new Group();
double[] coords = ...

Polyline bg = new Polyline(coords);
bg.setStroke(Color.BLACK);
bg.setStrokeWidth(12);

Polyline fg = new Polyline(coords);
fg.setStroke(Color.BLUE);
fg.setStrokeWidth(8);

group.getChildren().add(bg);
group.getChildren().add(fg);

So, while that renders the way I want, I now have a Group rather than a Polyline, so I can't treat it as a Shape. I can't see any way to specify a custom drawing mechanism, so is there a way to do this?

A:

Overall, I like the group based approach you outlined in your question.  It is unfortunate that it does not fit your particular situation, but for others who come across this question, it may be the preferred solution for their application.

You could apply a DropShadow effect to your PolyLine to generate the border color.  This will end up with slightly rounded edges for corners, which may or may not be what you wish.

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.effect.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polyline;
import javafx.stage.Stage;

public class Polyanna extends Application {
    @Override
    public void start(Stage stage) {
        Polyline polyline = new Polyline();
        polyline.getPoints().addAll(50.0, 50.0,
                200.0, 100.0,
                100.0, 200.0
        );
        polyline.setStrokeWidth(8);
        DropShadow borderEffect = new DropShadow(
                BlurType.THREE_PASS_BOX, Color.BLUE, 2, 1, 0, 0
        );
        polyline.setEffect(borderEffect);

        stage.setScene(
                new Scene(
                        new Group(polyline),
                        250, 250
                )
        );
        stage.show();
    }

    public static void main(String\[\] args) {
        launch(args);
    }
}

An alternate option is to draw a Polygon with a fill and stroke rather than a PolyLine.  You could write a routine which takes an array of points for a Polyline and generates a matching array of points for a Polygon from that input array (with a bit of work ;-)

You can use shape intersection capabilities to create an arbitrary shape that you can fill and stroke to possibly end up with the easiest way to get something closest to what you wish.  With this approach you have programmatic control over things like line caps, mitering and line join settings for the stroke of the border color.

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;

public class PolyIntersect extends Application {
    private static final double W = 250;
    private static final double H = 250;

    @Override
    public void start(Stage stage) {
        Polyline polyline = new Polyline();
        polyline.getPoints().addAll(50.0, 50.0,
                200.0, 100.0,
                100.0, 200.0
        );
        polyline.setStrokeWidth(8);
        Rectangle bg = new Rectangle(0, 0, W, H);
        Shape shape = Shape.intersect(bg, polyline);
        shape.setFill(Color.BLACK);
        shape.setStroke(Color.BLUE);
        shape.setStrokeType(StrokeType.OUTSIDE);
        shape.setStrokeWidth(2);

        stage.setScene(
                new Scene(
                        new Group(shape),
                        W, H
                )
        );
        stage.setResizable(false);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


Q:

Parsing py2neo paths into Pandas

We are returning paths  from a cypher query using py2neo. We would like to parse the result into a Pandas DataFrame. The cypher query is similar to the following query
query='''MATCH p=allShortestPaths(p1:Type1)-[r*..3]-(p2:Type1)
WHERE p1.ID =123456
RETURN distinct(p)''
result = graph.run(query)

The resulting object is a walkable object - which can be traversed. It should be noted that the Nodes and Relationships don't have the same properties.
What would be the most pythonic way to iterate over the object? Is it necessary to process the entire path or since the object is a dictionary is it possible to use the Pandas.from_dict method? There is an issue that sometimes the length of the paths are not equal.
Currently we are enumerating the object and if it is an un-equal object then it is a Node , otherwise we process the object as a relationship.
for index, item in enumerate(paths):
  if index%2 == 0:
    #process as Node
  else:
    #process as Relationship

We can use the isinstance method i.e.
 if isinstance(item, py2neo.types.Node ):
   #process as Node

But that still requires processing every element separately.

A:

I solve the problem as follows:
I wrote a function that receives a list of paths with the properties of the nodes and relationships
def neo4j_graph_to_dict(paths, node_properties, rels_properties):
    paths_dict=OrderedDict()
    for (pathID, path) in enumerate(paths):
        paths_dict[pathID]={}
        for (i, node_rel) in enumerate(path):
            n_properties = [node_rel[np] for np in node_properties]
            r_properties = [node_rel[rp] for rp in rels_properties]
            if isinstance(node_rel, Node):
                node_fromat = [np+': {}|'for np in node_properties]
                paths_dict[pathID]['Node'+str(i)]=('{}: '+' '.join(node_fromat)).format(list(node_rel.labels())[0], *n_properties)
            elif isinstance(node_rel, Relationship):
                rel_fromat = [np+': {}|'for np in rels_properties]
                reltype= 'Rel'+str(i-1)
                paths_dict[pathID][reltype]= ('{}: '+' '.join(rel_fromat)).format(node_rel.type(), *r_properties)
    return paths_dict

Assuming the query returns the paths, nodes and relationships we can run the following code:
query='''MATCH paths=allShortestPaths(
    (pr1:Type1 {ID:'123456'})-[r*1..9]-(pr2:Type2 {ID:'654321'}))
    RETURN paths, nodes(paths) as nodes, rels(paths) as rels'''

df_qf = pd.DataFrame(graph.data(query))
node_properties = set([k for series in df_qf.nodes for node in series for k in node.keys() ]) # get unique values for Node properites
rels_properties = set([k for series in df_qf.rels for rel in series for k in rel.keys() ]) # get unique values for Rels properites
wg = [(walk(path))  for path in df_qf.paths ]
paths_dict = neo4j_graph_to_dict(wg, node_properties, rels_properties)
df = pd.DataFrame(paths_dict).transpose()
df = pd.DataFrame(df, columns=paths_dict[0].keys()).drop_duplicates()


Q:

SQL select subquery that returns boolean value based on case statement

I have 2 tables and I want the case statement subquery to set the returned value string value 'Rural' if no match and 'Urban' if true.  I need the query to lookup table 2 to see if the City name exists.
Currently my query always returns the false value 'RURAL'
, CASE --This CASE is identifying Urban communities as listed in the contract, and leaving the rest as Rural.

WHEN t1.city in (select top 1 city from t1
                 left join t2 on t2.city2 = t1.city
                where t2.city2 = t1.city
                              )
            then 'Urban'
            ELSE 'Rural'
          end as URBAN_RURAL

select    t1.city
    , t2.city2
    , CASE --This CASE is identifying Urban communities and leaving the rest as Rural.
WHEN Exists (select top 1 from t1 where t1.city = t2.city2)
            then 'Urban'
            ELSE 'Rural'
      end as Urban_Status;

from t1  with (nolock)
    left join t2 with (nolock)
    on t1.city = t2.city

I want to use the lookup table as we may be modifying what qualifies as a City and just add or remove names from that table t2.  So if the case statement can return the Urban string value for matching results in both tables, and rural for unmatched, that would be ideal.
sample results would be
City    City2     UrbanRural
Orono   NULL      Rural
Bangor  Bangor    Urban
Machias Null      Rural

A:

I think this is what you want. But not really sure without sample expected results.
SELECT COALESCE(
         ( SELECT 'URBAN'
             FROM T2
            WHERE T1.city = T2.city
         ), 'RURAL' ) AS CITY_TYPE,
       T1.*
  FROM T1


Q:

Passing 2D char to function and only first element is filled

I am passing a 2D char array to a function.  If I print it in the calling function, I see it is filled with some elements.  If I print it in the called function, only the first element is filled:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int compareTopString(char * string1, char * string2){
    printf("%s %s\n", string1, string2);
    return 5;
}

int getMaxTopics(int numP, int numTop, int * subject[][1000]){

    for(int k = 0;k < numP;k++){
        printf("%s\n", subject[k]);
    }

    return 0;
}

int main() {

    int numP;
    int numTop;
    char subject[1000][1000];
    scanf("%d", &numP);
    scanf("%d", &numTop);

    for (int i = 0; i < numP; i++){
        scanf("%s", subject[i]);
    }

    printf("%d", getMaxTopics(numP, numTop, &subject));

    for(int k = 0;k < numP;k++){
        printf("%s\n", subject[k]);
    }

    return 0;
}

A:

You are mixing char and int. Are you sure that compiled without warnings?


Q:

Advanced search in data tables using PHP

I've created a data table using the following codes :-
main.php - it contain the script to call data table and the php script which is fetching the data from sql database
<!DOCTYPE html>

    <title>Data Table | Server Side | Basic | Zero Level</title>

<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

            Name	Gender	Age

            Name	Gender	Age

and dtServerSideBasicScript.php - It is the script which is fetching the data from sql server :-
<?php
header('Content-Type: application/json');
$con = mysqli_connect("localhost","root","","work");
$sql = "SELECT name,gender,age from test ";
$r = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($r)){
    array_push($result,array(
        "name"=>$row['name'],"gender"=>$row['gender'],"age"=>$row['age']
    ));
}
echo json_encode(array('data'=>$result));?>

Now, I've to apply advance filter section above the data table, which can be a form that consist of following fields - a name input, an age range input and a gender select input field. And on submission of this form the relevant search result should be displayed in the data table.

A:

Let me give you example for search by name you can do same for other search field also.
add below input tag in your html for search field
<input type="text" name="user_name" id="user_name" />

now change your script as per below,

on server side you will get user_name parameter in $_GET, like $_GET['user_name']. then you can use that value in your sql query with like.
Same way you can implement the age range and gender selection.


Q:

Neural Network in Swift

This is my first Neural Network, specifically a multilayer feed forward neural network that uses back-propagation for training, and I plan on using it for a multitude of projects. I started with the XOR function and now I'm moving to OCR. This network, as far as I know, can also be used for deep learning. I chose Swift because it's the language I'm most comfortable with. However, I may convert it to C++ for learning purposes.
Does anyone have any suggestions on how I could make this code more bullet proof, improve the quality, improve performance, more robust/versatile, etc.?
Also, is this a good style to use? Meaning is it common to use all class functions? I feel like this would reduce, if not eliminate, any side effects and makes the code more thread safe? I can easily whip up some instance methods that call the class methods, then in turn store the weights, activations, derivatives, etc..
It seems like it's pretty fast compared to other neural networks that I've downloaded and compared it to (only 2 in all honesty). However, as this is my first ANN, I'm not sure what "fast" is defined as. When attempting to train and test it with the MNIST dataset on a late 2015 iMac 4GHz Intel Core i7 Processor with 8GB DDR3 the results are as follows:
Topology
Number Of Layers: 3
Number of Input Neurons: 784
Number of Hidden Neurons: 20
Number of Output Neurons: 10
Training
Epochs: 100
Final Cost: 0.00529893
Cost Function: Mean Squared
Activation Function: Sigmoid
Number Of Training Examples: 60,000
Elapsed Time: 24 minutes and 6 seconds
Testing
Number of Testing Examples: 10,000
Number of Correct Predictions: 9,297
Ratio: 92.97%
Quick side note: I'm new to optimization as well but, it's definitely something I would like to be better at!
I would greatly appreciate any suggestions! Please be as harsh as you deem necessary! Also, if any more information is needed feel free to let me know.
EDIT 1:
I doubt this is applicable here but, I would like to implement some type of "live" testing where the user could draw a number on the screen, feed it forward, and get a predication.
Do I need to normalize the image the same way as the MNIST data? (e.g. normalize to fit in a 20x20 image while preserving the aspect ratio, center in a 28x28 image, and compute the center of mass. Then, translate the image so as to position this point at the center of the 28x28 field.) The only problem with that is I don't know the anti-aliasing technique used by the normalization algorithm to get the grey scale levels (hopefully I could just email Yann LeCun and find out though).
Here's the GitHub incase anyone finds that easier to read: JPSNeuralNetwork
JPSNeuralNetwork.swift
//
//  JPSNeuralNetwork.swift
//
//  Created by Jonathan Sullivan on 4/4/17.
//

import Foundation
import Accelerate

public protocol JPSNeuralNetworkDelegate
{
    func network(costDidChange cost: Float)
    func network(progressDidChange progress: Float)
    func network(overallProgressDidChange progress: Float)
}

public class JPSNeuralNetwork
{
    private typealias FeedForwardResult = (inputs: Matrix, activations: Matrix, activationRates: Matrix)

    private class func cost(costFunction: JPSNeuralNetworkCostFunction, activations: Matrix, targetOutputs: Matrix) -> Scalar
    {
        var cost: Scalar = 0

        for (activation, targetOutput) in zip(activations, targetOutputs) {
            cost += costFunction.cost(forOutputs: activation, targetOutputs: targetOutput)
        }

        cost /= Scalar(targetOutputs.count)

        return cost
    }

    private class func weights(forTopology topology: [Int]) -> Matrix
    {
        var weights = Matrix()

        var previousNumberOfInputs = topology[0]

        for neuronCount in topology[1..<topology.count]
        {
            // Plus one for the bias weight.

            let neuronWeights = JPSNeuralNetworkLayer.randomWeights(neuronCount: neuronCount, inputCount: previousNumberOfInputs + 1)
            weights.append(neuronWeights)

            previousNumberOfInputs = neuronCount
        }

        return weights
    }

    public class func feedForward(topology: [Int], activationFunction: JPSNeuralNetworkActivationFunction, inputs: Vector, weights: Matrix) -> Vector {
        return JPSNeuralNetwork.feedForward(topology: topology, activationFunction: activationFunction, inputs: inputs, weights: weights).activations.last!
    }

    private class func feedForward(topology: [Int], activationFunction: JPSNeuralNetworkActivationFunction, inputs: Vector, weights: Matrix) -> FeedForwardResult
    {
        var previousActivations = inputs

        var networkInputs = Matrix()
        var networkActivations = Matrix()
        var networkActivationRates = Matrix()

        // Ignore the input layer as it's just a place holder.

        for (neuronCount, layerWeights) in zip(topology[1..<topology.count], weights)
        {
            // Append one for the bias input.

            var layerInputs = previousActivations
            layerInputs.append(1)
            networkInputs.append(layerInputs)

            let feedForward = JPSNeuralNetworkLayer.feedForward(neuronCount: neuronCount, activationFunction: activationFunction, inputs: layerInputs, weights: layerWeights)

            previousActivations = feedForward.activations

            networkActivations.append(previousActivations)
            networkActivationRates.append(feedForward.activationRates)
        }

        return (networkInputs, networkActivations, networkActivationRates)
    }

    private class func outputGradientFor(costFunction: JPSNeuralNetworkCostFunction, activations: Vector, activationRates: Vector, targetOutputs: Vector) -> Vector
    {
        var gradient = Vector()

        for (activationRate, (activation, targetOutput)) in zip(activationRates, zip(activations, targetOutputs))
        {
            let costRate = costFunction.derivative(OfOutput: activation, targetOutput: targetOutput)
            let error = (costRate * activationRate)
            gradient.append(error)
        }

        return gradient
    }

    private class func gradientFor(costFunction: JPSNeuralNetworkCostFunction, activations: Matrix, activationRates: Matrix, weights: Matrix, targetOutputs: Vector) -> Matrix
    {
        let reversedWeights = weights.reversed()
        var reversedActivations = (activations.reversed() as Matrix)
        var reversedActivationRates = (activationRates.reversed() as Matrix)

        let outputLayerActivations = reversedActivations.removeFirst()
        let outputLayerActivationRates = reversedActivationRates.removeFirst()
        var previousGradient = JPSNeuralNetwork.outputGradientFor(costFunction: costFunction, activations: outputLayerActivations, activationRates: outputLayerActivationRates, targetOutputs: targetOutputs)

        var gradient = Matrix()
        gradient.append(previousGradient)

        for (layerActivationRates, (layerActivations, layerWeights)) in zip(reversedActivationRates, zip(reversedActivations, reversedWeights))
        {
            previousGradient = JPSNeuralNetworkLayer.gradientFor(activations: layerActivations, activationRates: layerActivationRates, weights: layerWeights, gradient: previousGradient)

            gradient.append(previousGradient)
        }

        return gradient.reversed()
    }

    private class func updateWeights(learningRate: Float, inputs: Matrix, weights: Matrix, gradient: Matrix) -> Matrix
    {
        var newWeights = Matrix()

        for ((layerInputs, layerWeights), layerGradient) in zip(zip(inputs, weights), gradient)
        {
            let newLayerWeights = JPSNeuralNetworkLayer.updateWeights(learningRate: learningRate, inputs: layerInputs, weights: layerWeights, gradient: layerGradient)
            newWeights.append(newLayerWeights)
        }

        return newWeights
    }

    private class func backpropagate(learningRate: Float, costFunction: JPSNeuralNetworkCostFunction, inputs: Matrix, weights: Matrix, activations: Matrix, activationRates: Matrix, targetOutput: Vector) -> Matrix
    {
        let gradient = JPSNeuralNetwork.gradientFor(costFunction: costFunction, activations: activations, activationRates: activationRates, weights: weights, targetOutputs: targetOutput)

        return JPSNeuralNetwork.updateWeights(learningRate: learningRate, inputs: inputs, weights: weights, gradient: gradient)
    }

    public class func train(delegate: JPSNeuralNetworkDelegate?, topology: [Int], epochs: Int, learningRate: Float, activationFunction: JPSNeuralNetworkActivationFunction, costFunction: JPSNeuralNetworkCostFunction, trainingInputs: Matrix, targetOutputs: Matrix) -> Matrix
    {
        var weights = JPSNeuralNetwork.weights(forTopology: topology)

        for epoch in 0..<epochs
        {
            var activations = Matrix()

            for (index, (inputs, targetOutput)) in zip(trainingInputs, targetOutputs).enumerated()
            {
                let progress = (Float(index + 1) / Float(targetOutputs.count))
                delegate?.network(progressDidChange: progress)

                let overallProgress = ((Float(epoch) + progress) / Float(epochs))
                delegate?.network(overallProgressDidChange: overallProgress)

                let feedForward: FeedForwardResult = JPSNeuralNetwork.feedForward(topology: topology, activationFunction: activationFunction, inputs: inputs, weights: weights)
                activations.append(feedForward.activations.last!)

                weights = JPSNeuralNetwork.backpropagate(learningRate: learningRate, costFunction: costFunction, inputs: feedForward.inputs, weights: weights, activations: feedForward.activations, activationRates: feedForward.activationRates, targetOutput: targetOutput)
            }

            let cost = JPSNeuralNetwork.cost(costFunction: costFunction, activations: activations, targetOutputs: targetOutputs)
            delegate?.network(costDidChange: cost)
        }

        return weights
    }
}

JPSNeuralNetworkLayer.swift
//
//  JPSNeuralNetworkLayer.swift
//
//  Created by Jonathan Sullivan on 4/4/17.
//

import Foundation
import Accelerate

public class JPSNeuralNetworkLayer
{
    /**
     Used to generate a random weights for all neurons.
     */
    public class func randomWeights(neuronCount: Int, inputCount: Int) -> Vector
    {
        var layerWeights = Vector()

        for _ in 0..<neuronCount
        {
            let neuronWeights = JPSNeuralNetworkNeuron.randomWeights(inputCount: inputCount)
            layerWeights.append(contentsOf: neuronWeights)
        }

        return layerWeights
    }

    /**
     Used to feed the inputs and weights forward and calculate the weighted input and activation.
     This method also precalculates the activation rate for use later on and to reduce the number of
     calculations.

     weightedInput = sum(x[i] * w[i])
     activation = sigma(weightedInput[j])
     activationRate = sigma'(activation[j])
     */
    public class func feedForward(neuronCount: Int, activationFunction: JPSNeuralNetworkActivationFunction, inputs: Vector, weights: Vector) -> (activations: Vector, activationRates: Vector)
    {
        var activations = Vector(repeating: 0, count: neuronCount)

        vDSP_mmul(weights, 1,
                  inputs, 1,
                  &activations, 1,
                  vDSP_Length(neuronCount), 1,
                  vDSP_Length(inputs.count))

        activations = activations.map({
            return activationFunction.activation($0)
        })

        let activationRates = activations.map({
            return activationFunction.derivative($0)
        })

        return (activations, activationRates)
    }

    /**
     Used to calculate the error gradient for each neuron.
     */
    public class func gradientFor(activations: Vector, activationRates: Vector, weights: Vector, gradient: Vector) -> Vector
    {
        var layerGradient = Vector(repeating: 0, count: activations.count)

        vDSP_mmul(gradient, 1,
                  weights, 1,
                  &layerGradient, 1,
                  1, vDSP_Length(activations.count),
                  vDSP_Length(gradient.count))

        vDSP_vmul(layerGradient, 1,
                  activationRates, 1,
                  &layerGradient, 1,
                  vDSP_Length(layerGradient.count))

        return layerGradient
    }

    /**
     Used to generate update each neurons weights on a per neuron error basis given the input.
     */
    public class func updateWeights(learningRate: Float, inputs: Vector, weights: Vector, gradient: Vector) -> Vector
    {
        var nagativeLearningRate = -learningRate
        var scaledGradient = Vector(repeating: 0, count: gradient.count)

        vDSP_vsmul(gradient, 1,
                   &nagativeLearningRate,
                   &scaledGradient, 1,
                   vDSP_Length(gradient.count))

        var scaledInputs = Vector(repeating: 0, count: weights.count)

        vDSP_mmul(scaledGradient, 1,
                  inputs, 1,
                  &scaledInputs, 1,
                  vDSP_Length(scaledGradient.count), vDSP_Length(inputs.count),
                  1)

        var layerWeights = Vector(repeating: 0, count: weights.count)

        vDSP_vadd(weights, 1,
                  scaledInputs, 1,
                  &layerWeights, 1,
                  vDSP_Length(weights.count))

        return layerWeights
    }
}

JPSNeuralNetworkNeuron.swift
//
//  JPSNeuralNetworkNeuron.swift
//
//  Created by Jonathan Sullivan on 4/4/17.
//

import Foundation

public typealias Scalar = Float
public typealias Vector = [Scalar]
public typealias Matrix = [Vector]

public enum JPSNeuralNetworkCostFunction: Int
{
    case meanSquared = 0
    case crossEntropy = 1

    func derivative(OfOutput output: Scalar, targetOutput: Scalar) -> Scalar
    {
        switch self
        {
        case .crossEntropy:
            return (output - targetOutput) / ((1 - output) * output)

        case .meanSquared:
            fallthrough

        default:
            return (output - targetOutput)
        }
    }

    func cost(forOutputs outputs: Vector, targetOutputs: Vector) -> Scalar
    {
        switch self
        {
        case .crossEntropy:
            return -zip(outputs, targetOutputs).reduce(0, { (sum, pair) -> Scalar in
                let temp = pair.1 * log(pair.0)
                return sum + temp + (1 - pair.1) * log(1 - pair.0)
            })

        case .meanSquared:
            fallthrough

        default:
            return 0.5 * zip(outputs, targetOutputs).reduce(0, { (sum, pair) -> Scalar in
                return pow(pair.1 - pair.0, 2)
            })
        }
    }
}

public enum JPSNeuralNetworkActivationFunction: Int
{
    case sigmoid = 0
    case hyperbolicTangent = 1

    func derivative(_ activation: Scalar) -> Scalar
    {
        switch self
        {
        case .hyperbolicTangent:
            return (1 - pow(activation, 2))

        case .sigmoid:
            fallthrough

        default:
            return (activation * (1 - activation))
        }
    }

    func activation(_ weightedInput: Scalar) -> Scalar
    {
        switch self
        {
        case .hyperbolicTangent:
            return tanh(weightedInput)

        case .sigmoid:
            fallthrough

        default:
            return (1 / (1 + exp(-weightedInput)))
        }
    }
}

public class JPSNeuralNetworkNeuron
{
    /**
        Used to generate a single random weight.
    */
    private class func randomWeight(inputCount: Int) -> Scalar
    {
        let range = (1 / sqrt(Scalar(inputCount)))
        let rangeInt = UInt32(2000000 * range)
        let randomDouble = Scalar(arc4random_uniform(rangeInt)) - Scalar(rangeInt / 2)
        return (randomDouble / 1000000)
    }

    /**
     Used to generate a vector of random weights.
    */
    public class func randomWeights(inputCount: Int) -> Vector
    {
        var weights = Vector()

        for _ in 0..<inputCount
        {
            let weight = JPSNeuralNetworkNeuron.randomWeight(inputCount: inputCount)
            weights.append(weight)
        }

        return weights
    }
}

A:

I am not an expert for neural networks or deep learning, so I cannot
review all aspects of your code. But here is some feedback:
In JPSNeuralNetworkNeuron.swift, some enums are defined with methods
which switch on the possible values of the enumeration, for example

func derivative(OfOutput output: Scalar, targetOutput: Scalar) -> Scalar
{
    switch self
    {
    case .crossEntropy:
        return (output - targetOutput) / ((1 - output) * output)

    case .meanSquared:
        fallthrough

    default:
        return (output - targetOutput)
    }
}

I would remove the fallthrough and the default: case:
func derivative(OfOutput output: Scalar, targetOutput: Scalar) -> Scalar
{
    switch self
    {
    case .crossEntropy:
        return (output - targetOutput) / ((1 - output) * output)

    case .meanSquared:
        return (output - targetOutput)
    }
}

That makes the code shorter and safer: If you add another enumeration
value later, the compiler will check that it is covered in the switch
statement.
There are several places where an array is created incrementally
using append(), e.g. in JPSNeuralNetworkNeuron.swift:

public class func randomWeights(inputCount: Int) -> Vector
{
    var weights = Vector()

    for _ in 0..<inputCount
    {
        let weight = JPSNeuralNetworkNeuron.randomWeight(inputCount: inputCount)
        weights.append(weight)
    }

    return weights
}

That can be simplified with map():
public class func randomWeights(inputCount: Int) -> Vector
{
    let weights = (0..<inputCount).map { _ in
        JPSNeuralNetworkNeuron.randomWeight(inputCount: inputCount)
    }
    return weights
}

That might also increase the performance because the runtime can
allocate the target array with the required size, instead of
re-sizing it repeatedly.
There are two feedForward methods with identical parameters:

public class func feedForward(topology: [Int], activationFunction: JPSNeuralNetworkActivationFunction, inputs: Vector, weights: Matrix)

-> Vector
private class func feedForward(topology: [Int], activationFunction: JPSNeuralNetworkActivationFunction, inputs:

Vector, weights: Matrix) -> FeedForwardResult

the former being a wrapper for the latter. But that wrapper method
is not used at all. If you remove it then you can also get rid
of the explicit type annotation in

let feedForward: FeedForwardResult = JPSNeuralNetwork.feedForward(...)

which is currently required to disambiguate between the two methods.
With regard to class functions or not: There are some "values" which
seem to be actually properties of the neural network, such as
activationFunction, costFunction, topology and perhaps more. At present,
those values are permanently passed around between the class functions.
I would recommend to define those values as (instance) properties of
the type:
public class JPSNeuralNetwork
{
    let activationFunction: JPSNeuralNetworkActivationFunction
    let costFunction: JPSNeuralNetworkCostFunction
    let topology: [Int]
    // ...

    init(activationFunction: JPSNeuralNetworkActivationFunction,
         costFunction: JPSNeuralNetworkCostFunction,
         topology: [Int]) {
        self.activationFunction = activationFunction
        self.costFunction = costFunction
        self.topology = topology
    }

    // ...
}

and then create an instance where you pass those values on
creation:
let network = JPSNeuralNetwork(activationFunction: .sigmoid, costFunction: .meanSquared,
                               topology: self.topology)
network.train(delegate: self, ... other parameters)

Advantages:

Many function arguments can be removed. That makes the code
better readable and might also improve the performance.
You can logically separate between constant properties of the
neural network, variable properties, and parameters which are only
used in a function (method) call.
Having an reference (a "handle") to the instance allows for more
opportunities, e.g. a cancel method which aborts the operation.
You can use the instance itself later to classify input images,
or perhaps to add additional training cycles (does that make sense?).


Q:

Meteor radio buttons don't return correct value

When I have a form with two radio buttons in Meteor, the first value is always returned in the .val() call. What is the correct way to access which radio button is checked?

Here is my sample code:
testRadioButtons.html:
<template name="testRadioButtons">
    <form class="main">

                <input name="insuranceDecision" type="radio" value="NoInsurance"/> &nbsp Don't Buy Insurance

                <input name="insuranceDecision" type="radio" value="BuyInsurance"/>  &nbsp Buy Insurance

                <input type="submit" value="Submit" class="btn btn-primary"/>

    </form>
</template>

testRadioButtons.js
  Template.testRadioButtons.events({
      'submit form': function(e) {
        e.preventDefault();

        console.log('running form submit')

        decision = $(e.target).find('[name=insuranceDecision]').val();
        // console.log($(e.target).find('[name=insuranceDecision]'));
        console.log("decision: " + decision); // ZZZZZ Why is NoInsurance always displaying, even when the other radio button is checked.?

    Meteor.Router.to('happyPage');
  }
});

And the following are needed to make what I wrote run but do not do anything important.
main.html

  <title>testRadioButtons</title>

{{renderPage}}

router.js
Meteor.Router.add({
    '/': 'testRadioButtons',
    '/happyPage' : 'happyPage'
})

happyPage.html
<template name="happyPage">

 Happy page

Test Radio Buttons Again

</template>

A:

I think this is the answer:
https://stackoverflow.com/a/4196937/233382
I have to loop over the individual elements and find the one that is "checked".


Q:

Why is my while loop activated, but nothing else happens?

So right now I'm trying to mess around with stdin and an input file by doing the following:
./a.exe < input.txt
The input.txt file just has a lot of random test cases so I can see if I'm doing this right or not. I'm trying to remove some punctuation marks from my input file through the use of stdin. You will notice that I have a couple of printf's laying in there saying "here". I put that there to see if the program reaches it or not.
So whenever I run it, I type "./a.exe < input.txt", and I get "bash: input.txt: No such file or directory". So I'm like... okay, I'll just type in a couple of random inputs to see if it works. I typed in random words, and it turns out the program doesn't even hit any of the words I typed after ./a.exe.
Can anyone explain why I'm having these errors?
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
    char textin[80], wordout[80];
    int i, j;
    int count = 0;

    printf("%d", argc);
    while (count != argc)
    {
        scanf("%s", textin);
        if (strcmp(textin, ".") == 0)
            printf("here");
        printf("here2");

        strcpy(wordout, textin);
        for (i = 0 ; i < strlen(wordout) ; i++)
        {
            if (wordout[i] == '.'  ||  wordout[i] == ','  ||
                wordout[i] == '"'  ||  wordout[i] == ';'  ||
                wordout[i] == '!'  ||  wordout[i] == '?'  ||
                wordout[i] == '('  ||  wordout[i] == ')'  ||
                wordout[i] == ':')
            {
                for (j = i ; j < strlen(wordout) - 1 ; j++)
                    wordout[j] = wordout[j + 1];
                wordout[j] = '\0';
            }
            printf("here3");
        }
        printf("%s\n", wordout);
        count++;
    }
    return 0;
}

A:

That first issue has nothing to do with your program, the error you're getting is a bash error, trying to open input.txt to connect to the standard input of your a.exe program. This happens before your code even begins to run.
You need to figure out why bash can't find your file, such as:

are you in the correct directory?
does the input.txt file actually exist?
have you created it in such a way that there are special characters in the file name (such as inpux<backspace>t.txt)?

As to the other issue, you appear to be using a mish-mash of two different methods of getting information from the user.
These two methods are arguments passed to the program (argc/v) and standard input (scanf()).
It may be that you're running your code with something like:
./a.exe arg1 arg2 arg3

and expecting it to do something with them. Unfortunately, the scanf() inside your loop will simply wait for you to type something on the terminal so it may seem that it has hung.
I think you need to figure out how you want to present the input to the program. If it's via arguments, you would use argv[N] where 1 <= N < argc. If it's via standard input, you probably don't need to concern yourself with argc/v at all.


Q:

Windows Service Installation using installshield

I have a windows service. How do I install and start it using installshield 2010?

A:

InstallScript have the following functions ServiceAddService and ServiceStartService for your requirement.


Q:

How to change Permalink by custom post type

I want to change permalink by following way. Please suggest me the best solution.
www.domain.com/gallery/image.png  to www.domain.com/india/image.png

A:

You can do it with a plugin.
Try this plugin:
https://de.wordpress.org/plugins/custom-post-type-permalinks/


Q:

How to extend localStorage across devices (without DB)

Goal: extend my already implemented localStorage in my app, to be well, non local I guess.

I like the implementation of saving simple user settings with local storage API. I have this working for my needs in a web app, but the only problem is it's local to that machine / browser being used/saved. I do not have access to a classic MySQL style table for this. I would like to extend or adapt my local storage to carry over to other browsers; or store my user settings in user JS objects and JS object properties.

I like the idea of just creating JSON or JavaScript objects with each user, whenever there is a new user, take the name, create an object or object[key] with the name, and have the field properties default variables at first, and variables become populated and or overridden when the user saves them.
Or if the above is frowned upon; would like to keep my localstorage implementation as it works so well and find
a plugin/library/extension of some sort that allows me to also save
this and re-render in different locations; this has gotten to be
thought of before. Although I would love to keep it client side; I am
open to a node.js solution as well as python solution, a simple
dataframe of sorts should work enough.
What about generating a file with my localStorage data? Perhaps a .csv file (this is non sensitive data) and have it update as my localStorage does?

A:

What about using sqlite?
Just one file on your server like csv. Sending a http request To update it using SQL statement by knex or something like that after updating the localstorage on the client-side.
At least it is better than cvs I think because you can define several tables, which is more scalable, and more efficient, you know, it is a database.


Q:

Click on header of a dynamic table, to fade content-rows out

I have a problem with jquery and a dynamic table. I want a click on the table header to cause all the rows (not the header) to fade out. Unfortunately I can't figure out how to select the rows. Until now I've only found examples, where they have fixed number of rows and therefore fixed IDs or classes. But as I said, in my case there could be an arbitrary number of rows.
I guess I would need something like $(this).tr.effect(...).
I know that I could try to figure out all the ID's of the rows with Javascript and then fade them out. But this seems a too complex approach to that problem. Does someone know an easy way to fade out the rows?
Edit:
Sorry, I think I didn't make myself clear enough (I try again :)). I said: "I have a dynamic table." But what I meant was: I have dynamic tables on one page, and therefore more then one header. Something like this(pseudo code):

   <rows />

   <rows />

   <rows/>

All this is auto generated. So I don't know how many there are (of course I could figure it out with javascript or write it in a hidden field). That's why I cant select an ID with $("#myTable") . Because there are more than one #myTable. My new approach is to code the ID of the rows I want to hide into the header ID and then select the header class with $(".myHeader"). After that I can decode the header-ID and hide the rows.
I am not sure, if this is a smart solution. So maybe someone has a better one?
(I hope you guys understand what I am trying to do ;))
What I am trying to ask is:
What is the smartest code to put in:
$(document).ready(function () {
    $(".myHeader").click(function () {
          //I try to hide the rows of the clicked header.
    });
});

A:

The best way is to wrap your headers in
 and your rows in
, then you can use this code:
$myTable = $("#myTable");

$("thead > tr", $myTable).click(function() {
    $("tbody > tr", $myTable).fadeOut();
});

But if you dont want to use them, this code will work (assuming only the first row is your header row):
$myTable2 = $("#myTable2");
$("tr:eq(0)", $myTable2).click(function() {
    $("tr:gt(0)", $myTable2).fadeOut();
});

Examples: http://jsfiddle.net/Wxa3W/1/
Edit:
Updated answer to your updated question.
Html:

Header 1	Header 2	Header 3

Data	Data	Data

Data	Data	Data

JavaScript:
$(function() {
    $(".MyTable > thead > tr").click(function() {
        $(this).closest(".MyTable").find("tbody > tr").fadeOut();
    });
});

And if you don't want thead/tbody:
Html:

Header 1	Header 2	Header 3

Data	Data	Data

Data	Data	Data

JavaScript:
$(function() {
    $(".myTable .myHeader").click(function() {
        $(this).closest(".myTable").find("tr:not(.myHeader)").fadeOut();
    });
});

Example: http://jsfiddle.net/Wxa3W/2/


Q:

Call Asp.Net webforms server control method using jQuery .ajax method

I'm trying to create a web forms server control and really wanted to leverage jQuery to handle the client side interaction.
So far I've not found any examples to being able to directly call a server control using the jQuery .ajax functionality and I'm wondering is it even possible?
I know I could go down the web service or Http Handler route but my aim is to create a control that can be dropped into existing sites and utilise session but with no intention of needing to use ViewState.
Can this be done? or do I have to use the ScriptControl and Asp.Net Ajax functionality?

A:

Unfortunately, no.
Probably the closest is to create an HttpHandler class and include it in your server control's DLL.  Then, you'll only need a single line added to your web.config to wire the handler class up to an endpoint that jQuery can communicate with.


Q:

How to fix Selenium WebDriverException: The browser appears to have exited before we could connect?

I have installed firefox and Xvfb on my centos6.4 server to use selenium webdriver.
But, when I run the code, I got an error.
from selenium import webdriver
browser = webdriver.Firefox()

Error
selenium.common.exceptions.WebDriverException: Message:
'The browser appears to have exited before we could connect. The output was: None'

I read some related pages on stackoverflow and someone suggested to remove all files in tmp folder, so I did it. But, it still doesn't work.
Could anyone please give me a help?
Thank you in advance!
Edit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/site-packages/selenium/webdriver/firefox/webdriver.py", line 59, in __init__
    self.binary, timeout),
  File "/usr/local/lib/python3.4/site-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in __init__
    self.binary.launch_browser(self.profile)
  File "/usr/local/lib/python3.4/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 64, in launch_browser
    self._wait_until_connectable()
  File "/usr/local/lib/python3.4/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 103, in _wait_until_connectable
    self._get_firefox_output())
selenium.common.exceptions.WebDriverException: Message: 'The browser appears to have exited     before we could connect. The output was: None'

A:

for Googlers, this answer didn't work for me, and I had to use this answer instead. I am using AWS Ubuntu.
Basically, I needed to install Xvfb and then pyvirtualdisplay:
sudo apt-get install xvfb
sudo pip install pyvirtualdisplay

Once I had done that, this python code worked:
#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(1024, 768))
display.start()

browser = webdriver.Firefox()
browser.get('http://www.ubuntu.com/')
print browser.page_source

browser.close()
display.stop()

Thanks to @That1Guy for the first answer

A:

I was running into this on an (headless) Ubuntu 14.04 server with Jenkins and xvfb installed. I had installed the latest stable Firefox (47) which started a build failing that ran a python script which used the Firefox driver for selenium (version 2.53).
Apparently Firefox 47+ is not compatible with the driver used in Selenium 2.53, and Selenium 3+ will be using a new driver called "Marionette" or "Gecko Driver" (which isn't officially released yet).
This page explains how to use the new driver pretty well, in several languages: https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver
Basically:

get/build the executable from the project on github: https://github.com/mozilla/geckodriver/releases (and make sure it's perms are set to be executable, IE chmod a+x /path/to/geckdriver-executable)
rename/copy binary to "wires"
make sure the binary's location is added to the PATH that the build uses when executing the selenium test
update the selenium test to use the new driver

For Python, step 4 looked something like the following for me:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
firefox_capabilities['binary'] = '/usr/bin/firefox'

driver = webdriver.Firefox(capabilities=firefox_capabilities)

A:

I too had faced same problem.  I was on Firefox 47 and Selenium 2.53; I downgraded Firefox to 45. This worked.

Remove Firefox 47 first :
sudo apt-get purge firefox

Check for available versions:
apt-cache show firefox | grep Version

It will show available firefox versions like:

Version: 47.0+build3-0ubuntu0.16.04.1
  Version: 45.0.2+build1-0ubuntu1

Install a specific version
sudo apt-get install firefox=45.0.2+build1-0ubuntu1

Next you have to not upgrade to the newer version again.
sudo apt-mark hold firefox

If you want to upgrade later
sudo apt-mark unhold firefox
sudo apt-get upgrade


Q:

how to use camera ontology in ROWLEX

I'm mot sure if I'm doing this wrong or not
I don't know if I am supposed to add other ontologies
If not, what can I do to get a camera ontology working please?
http://protege.cim3.net/file/pub/ontologies/camera/camera.owl
Thanks

A:

I tried you ontology with the OwlGrinder, and I indeed got an error message. (Next time please, report that).
Normally these messages report if your ontology is not valid. In your case, your ontology is OK, ROWLEX assumed that maxCardinality is always greater than zero, but according to the OWL spec, zero is a perfectly valid value. Therefore, this is a bug in ROWLEX, I recorded it, it will be fixed in the next version.
As a temporary solution, you need to change the ontology if you want to use ROWLEX. You can get rid of the restriction of #shutter-speed, or you may change the restriction like this:
<owl:maxCardinality>1</owl:maxCardinality>

instead of
 <owl:cardinality>0</owl:cardinality>

Important! The proposed change alter the meaning of your classes significantly, but it shuts OwlGrinder up.


Q:

Bind a list in prolog

I have a sort algorithm and I am trying to call a list but i seems only garbage variable. What is the right way?
This is what I got:
?- sort(list(K),Sorted).
K = Sorted, Sorted = [[_3796]]

This is the code:
list([[a,b,c,10],[e,f,g,2],[h,i,j,6]]).

sort([],[]):- !.
sort([X], [X]).
sort(list([Head|Tail]),Sorted):- %code to sort, split sort, sort and append

I don't have to do this:
?- sort( [ [a,b,c,10], [e,f,g,2], [h,i,j,6] ] , Sorted).

A:

The normal way to do this would be:
?- list(K),sort(K,Sorted).

list([[a,b,c,10],[e,f,g,2],[h,i,j,6]]).

sort([],[]):- !.
sort([X], [X]).
sort([Head|Tail],Sorted):- %code to sort, split sort, sort and append

You could call it the way that you were doing it, but you'd have to do this messy approach:
sort(list([Head|Tail]),Sorted):- list([Head|Tail]), %code to sort, split sort, sort and append


Q:

Кнопка нажимается только один раз

Я столкнулся с этой проблемой впервые, не могу найти конкретного решения.
Вот код:

var bet;
var endGame;
var i;
var startGame;

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

function error(number) {
  switch (number) {
    case 1:
      $("#result").text("Укажите сумму ставки.");
      break;
    case 2:
      $("#result").text("Вы проиграли " + bet + "$");
      break;
    case 3:
      $("#result").text("Вы поставили " + bet + "$! Желаем удачи!");
      break;
    case 4:
      $("#result").text("Вы выиграли " + (bet * i).toFixed(0) + "$.");
      break;
    case 5:
      $("#result").text("Игра уже идет!");
      break;

  }
}

function bet() {
  if ($("#betInput").val()) {
    bet = $("#betInput").val();
    game();
    error(3);
  } else {
    error(1);
  }
}

function game() {
  i = 1.0;
  endGame = getRandomFloat(1.0, 2.0);
  endGame.toFixed(1);
  startGame = setInterval(function() {

    if (i < endGame) {
      i = i + 0.1;

      $("#count").text(i.toFixed(1));
    } else {

      $("#count").text("1.0");
      clearInterval(startGame);
      error(2);
      i = 1.0;
      endGame = undefined;
      startGame = undefined;

    }

  }, 500)
}

function take() {

  if (i < endGame) {
    //Забрал лавэ.
    $("#count").text("1.0");
    clearInterval(startGame);
    error(4);
    i = 1.0;
    endGame = undefined;
    startGame = undefined;

  }

}

<input id="betInput" type="text" />
<button class="button" onclick="bet()">Поставить</button>

Так вот эта кнопка отрабатывает лишь один раз, при повторном нажатии ошибка:

Uncaught TypeError: bet is not a function
      at HTMLButtonElement.onclick (index.html:24)

Подскажите, пожалуйста, в чем проблема?

A:

var bet;

bet = $("#betInput").val();

В этих строках ошибка. Сначала ты создаёшь переменную bet, потом создаёшь функцию bet, то есть в переменную скорей всего будет эта функция, а внутри функции ты присваиваешь значение в эту переменную, тем самым затираешь функцию, замени bet на что-то другое, должно заработать


Q:

Give second or fourth column right side border using css in Internet Explorer

I just want to give second and fourth  right side border ...
as you can see I have following table:

      Name
      Class
      RollNo
      Batch

I have tried something like this in css
.secondtd  td+td {
  border-right:solid 1px red;
}

but not work for me .. I am using IE .

A:

You could assign the class two the 2nd and 4th element of the tables:

Or you could use nth-child:
td:nth-child(2), td:nth-child(4) {
 border-right:thick double #ff0000;
}

http://jsfiddle.net/ekHQf/
Which would select the 2nd and 4th element. If you only have 4 td's you could use even:
td:nth-child(even) {
  border-right:thick double #ff0000;
}

http://jsfiddle.net/ekHQf/1/
Edit:
From the comments to do this with a class applied:
.secondtd td:nth-child(2) {
  border-right:thick double #ff0000;
}