text:
Q: Javascript - saving and retrieving login credentials to an array Quick inquiry regarding saving and retrieving a user's credentials to an array (which I further intend to save to a text file, but that isn't the issue for the time being).
I have a simple login/register form in place, which seemingly has no overall flaws with it, but I am struggling immensely when trying to logically structure the function that would save the registered user's credentials to an array (allowing for multiple user's), and then and additional function which would read through the array looking for a match when logging in.
I'm entirely new to Javascript, and as it stands I'm not even sure where to begin with these functions, or how I'd structure/format the array, so any help would be immensely appreciated.
function createUser() {}

function getUser() {}

var users = [];

HTML for forms

         <form class="login-form" name="myForm">

Login Page

            <input name="username" type="text" placeholder="enter username"/>
            <input name="password" type="password" placeholder="enter password"/>
            <button type="button" onclick="validateLoginForm()">login</button>

Don't have an account? Register

         </form>

         <form class="register-form" name="otherForm">

Registration Page

            <input name="username" type="text" placeholder="choose username"/>
            <input name="password" type="password" placeholder="choose password"/>
            <input name="confirmation" type="password" placeholder="re-enter password"/>
            <input name="fname" type="text" placeholder="enter first name"/>
            <input name="lname" type="text" placeholder="enter last name"/>
            <input name="email" type="text" placeholder="enter email address"/>

            <button type="button" onclick="validateRegisterForm()">create</button>

Already have an account? Login

         </form>

A: Assuming you do want to do this, here's the javascript ES6 approach:
function createUser( username, password )
{
    const user = { username, password };  //create a user object to go in the array
    users.push( user );  //put it on the end of the array
}

function getUser( username, password )
{
    //loops through each user in the array and checks the stored username and password against the one you're looking for
    return users.find( eachUser => {
        return eachUser.username === username && eachUser.password === password;
    });
}

var users = [];


text:
Q: Attempting to create multiple child records from multi-value field I am attempting to use a trigger to create a child record to an object (Policy_Profile__c) for each value in its Product_Affected3__c field. Each value represents a record in a 3rd object (Vendor_Product__c) and so in order to create a link to that record I am querying that record, getting a couple of its field values and placing it in the newly created child record.
THIS IS THE SOLUTION :
trigger AutoCreateSubsServOnContrOv on Policy_Profile__c(after insert, after update)
{
    //Since, we need two values from Policy_Profile__c to be populated on the new Product_Affected_Entry__c record.
    //So, taking a Map instead of list. Earlier, List<String> subAccNames=new List<String>();
    //Map of subAccountNames and Policy_Profile__c Record.
    Map<String, Policy_Profile__c> subAccNames=new Map<String, Policy_Profile__c>();

    for(Policy_Profile__c newCont: Trigger.New)
    {
        //Checking of the field is empty or not.
        if(newCont.Products_Affected3__c!=Null && newCont.Products_Affected3__c!='')
        {
            system.debug('newCont.Products_Affected3__c---->'+newCont.Products_Affected3__c);
            String temp=newCont.Products_Affected3__c.normalizeSpace();
            temp=temp.replace(']',''); //No need for this if comma seperated values as I have taken.
            temp=temp.replace('[',''); //No need for this if comma seperated values as I have taken.

            //Iterate the number of values in the temp variable by slitting them by comma
            //add put them in subAccNames
            for(String acctName: temp.split(','))
            {
                subAccNames.put(acctName.normalizeSpace(), newCont);
                system.debug('subAccNames !!! '+subAccNames);
            }
        }
    }

    //Take a Map of Name and Record for holding Vendor_Product__c Name and Vendor_Product__c Record.
    Map<String, Vendor_Product__c> subAccIdsByName=new Map<String, Vendor_Product__c>();

    //Iterate over the Vendor Product records and create a Map with Venfor Product Id as Key and Vendor Product Record as Value.
    for(Vendor_Product__c subacc: [SELECT Id, Vendor__c, Name FROM Vendor_Product__c WHERE Name IN :subAccNames.keySet()])
    {
        //Putting record in place of Id, as value in the map.
        subAccIdsByName.put(subacc.Name, subacc);
        System.debug('subAcc Name and ID='+subacc.Name +'Id='+subacc.id+'Vendor_c='+subacc.Vendor__c);
    }

//    //This will hold the Product_Affected_Entry__c records to be upserted.
    List<Product_Affected_Entry__c> subs = new List<Product_Affected_Entry__c>();

    //Iterating over subAccNames Map.
    //No need to iterate again over Policy_Profile__c records as we have already taken the Policy_Profile__c record in the subAccNames Map.
    //Earlier: for (Policy_Profile__c newContract : Trigger.New)
    for(String ref1: subAccNames.keySet())
    {
        //Iterate over the subAccIdsByName Map.
        for(String ref2: subAccIdsByName.keySet())
        {
            //Match if the Name in the subAccNames Map is equal to Name in the subAccIdsByName Map.
            if(ref1==ref2)
            {
                Product_Affected_Entry__c ssoc = new Product_Affected_Entry__c();
                ssoc.Policy__c=subAccNames.get(ref1).Id;
                //Access Vendor Product Id from the Map.
                ssoc.Vendor_Product__c=subAccIdsByName.get(ref2).Id;
                //Access Vendor__c from the Map.
                ssoc.Vendor__c=subAccIdsByName.get(ref2).Vendor__c;
                //Access Name from the Map.
                ssoc.Policy_and_Product__c=subAccNames.get(ref1).Name+'~'+subAccIdsByName.get(ref2).Id;
                //Put the records in the subs list.
                subs.add(ssoc);
            }
        }
    }

    upsert subs Policy_and_Product__c;
}

A: This isn't a complete answer to your question, but it's more than I can put in a comment.
I see the following with your code:
Below, you've just declared your map. It's empty. No need to follow it with a debug statement.
    //----> Take a Map of Name and Record, instead of Name and Id.
    Map<String, Vendor_Product__c> subAccIdsByName=new Map<String, Vendor_Product__c>();
    System.debug('FIRSTsubAccIdsByName='+subAccIdsByName);

This may be at the root of your problem. Strings are immutable and can't be reassigned to themselves after you perform an operation on them as below:
        temp = temp.replace(']','');
        temp = temp.replace('[','');

Finally there is this section of code below:
            integer tempnum=0;
            for(String productsonpolicy: all)
            {
            System.debug('************************temp'+temp);
                //----> Iterate over the subAccIdsByName Map.
                for(Integer i=0; i<subAccIdsByName.keySet().size(); i++)
                {

                    System.debug('************************tempnumA'+tempnum);
                    tempnum = tempnum+1;

                    //----> Match if the Name in the productsonpolicy is equal to Name in the
                    //subAccIdsByName Map

                    if(productsonpolicy==(new List<String>(subAccIdsByName.keySet()))[i])
                    {

                        System.debug('************************tempnumB'+tempnum);

                        ..........
                        ..........

                        subs.add(ssoc);

                    }
                }
            }

I'm not certain what the purpose of tempnum in your code is, but I see where you're iterating it inside a for loop that's nested 2 layers deep. Why you're doing that is unclear to me.
It's also unclear why you iterate it at beginning of the nested loop instead of at the end of the loop. It would seem that you might be missing data that gets created or used the first time through although I don't see where the variable is used anywhere inside that section of code. That said, I can't help but question whether this should be nested within that loop, but instead perhaps within a loop that much further out if it needs to be iterated, and if so, located at the end of the loop its iterating.
Edit
I suspect the root of your problem could also be in this line:
         if(productsonpolicy==(new List<String>(subAccIdsByName.keySet()))[i])

In the above, [i] could be ignored as an iterator. The new list should be declared as:
new List<String>sbactIdsbyname = list<string>();
sbactIdsbyname.addAll(subAccIdsByName.keySet());

Once you've done the above, you can test it against list values of [i] in your if statement. In your current method, I suspect you're only testing it once.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I assign inputbox input to variable for each vba excel I have a for statement in a VBA script that goes through each cell in a range (number of cells in range is variable based on user input - could be three cells could be 100).  Each instance of the for loop calls an input box.  How do I assign the user input from each instance of the for loop to a variable for later use?
Here is the for with the input box:
For Each cell In MyQCData
text_string = cell.Value
WrdArray() = split(text_string, ",")
    For i = LBound(WrdArray) To UBound(WrdArray)
        strg = strg & vbNewLine & "Part No. " & i & " - " & WrdArray(i)
    Next i
        InputBox ("This part requires a " & WrdArray(0) & " measurement of the " & _
        WrdArray(1) & vbNewLine & vbNewLine _
        & "The range for this is input is " & vbNewLine & vbNewLine & "Lower Control Limit     " _
        & WrdArray(2) & vbNewLine & "Upper Control Limit     " & WrdArray(3))
        Erase WrdArray()
Next cell

A: It's kind of hard to tell without the rest of your code, but I assume that MyQCData is a Range.  Try the below. I sort of "brute forced" the Inputbox look with k, FYI.
Dim k As Long
k = 0
Dim inputArr() As Variant
ReDim inputArr(myqcdData.Cells.Count)
For Each cell In MyQCData
    text_string = cell.Value

    WrdArray() = Split(text_string, ",")
    For i = LBound(WrdArray) To UBound(WrdArray)
        strg = strg & vbNewLine & "Part No. " & i & " - " & WrdArray(i)
    Next i
    inputArr(k) = InputBox("This part requires a " & WrdArray(0) & " measurement of the " & _
                           WrdArray(1) & vbNewLine & vbNewLine _
                           & "The range for this is input is " & vbNewLine & vbNewLine & "Lower Control Limit     " _
                           & WrdArray(2) & vbNewLine & "Upper Control Limit     " & WrdArray(3))
    k = k + 1
    Erase WrdArray()
Next cell

'Check each value in the array. This is optional and can be removed/commented out
For k = LBound(inputArr) To UBound(inputArr)
    Debug.Print inputArr(k)
Next k

Edited per @Yow's astute comment

A: Yes, use an array:
Dim inputBoxAnswers() As String
ReDim inputBoxAnswers(1 To MyQCData.Cells.Count)
Dim cellCounter As Long
For Each cell In MyQCData
    text_string = cell.Value
    WrdArray() = split(text_string, ",")

    'Is this loop needed???
    For i = LBound(WrdArray) To UBound(WrdArray)
        strg = strg & vbNewLine & "Part No. " & i & " - " & WrdArray(i)
    Next i

    cellCounter = cellCounter + 1
    inputBoxAnswers(cellCounter) = InputBox("This part requires a " & _
                                   WrdArray(0) & " measurement of the " & _
                                   WrdArray(1) & _
                                   vbNewLine & vbNewLine & _
                                   "The range for this is input is " & _
                                   vbNewLine & vbNewLine & _
                                   "Lower Control Limit     " & WrdArray(2) & _
                                   vbNewLine & _
                                   "Upper Control Limit     " & WrdArray(3))
Next cell

If your MyQCData range is not a single column or a single row, you may find it easier to use a two-dimensional array, which could (perhaps) be dimensioned using
Dim inputBoxAnswers() As String
ReDim inputBoxAnswers(1 To MyQCData.Rows.Count, 1 To MyQCData.Columns.Count)

but then you will need to rework the indexes to use when assigning the elements their values.  It would probably need to be
inputBoxAnswers(cell.Row - MyQCData.Row + 1, cell.Column - MyQCData.Column + 1) = ....

but a lot depends on how you intend to use the array afterwards.

A: I'm going to dress this in a standalone code that you can easily run to get a feel for what's going on. Array variables must be declared hence Dim userInput(99) and the 99 is the upper limit (0-99 = 100 possible values). The first line of the first loop sets the variables, that's userInput(j) = InputBox("Sample InputBox", "InputBox Title", "blah" & j) the "blah" & j bit is the default entry, which is useful when you're writing/debugging as it's a lot faster to keep entering dummy data...
Sub inputBoxEg()
    Dim userInput(99)
    Dim MyQCData As Range

    Set MyQCData = Range("A1:A4")

    'Set InputBox inputs to a variable array called userInput:
    j = 0
    For Each cell In MyQCData
        userInput(j) = InputBox("Sample InputBox", "InputBox Title", "blah" & j)
        If userInput(j) = "" Then Exit Sub 'if user pressed cancel or entered blank
        j = j + 1
    Next cell

    'Collate variables collected by InputBoxes in a text string called allInputs:
    allInputs = ""
    For i = 0 To j - 1
        If i = 0 Then
            allInputs = i & ": " & userInput(i)
        Else
            allInputs = allInputs & vbNewLine & i & ": " & userInput(i)
        End If
    Next i

    MsgBox allInputs
End Sub


text:
Q: Using Google Map View on iOS versus on Android on iOS you don't need to specify the Google Map API key. But In android, you do have to specify, so the question why such difference?

A: They are completely different and the iOS one was written by Apple and directly licensed to them. The license is different.
Obviously features are different too with the iOS version in my opinion being more feature rich.


text:
Q: HTML and CSS how to move my logo to the left I want my logo to be at the left side or to use flex-start, but it doesnt move at all?
the html and css are here
https://codepen.io/medovanx/pen/zYERajx
header img {
  height:65px;
  display: flex;
  justify-content: flex-start;
}

A: header .github {
    margin-right: auto;
}

A: Something like this should do the trick:
header .github {
  margin: 0 auto 0 0;
}

A: You are declaring the header img as the flex-Container. Which means that all of the content in header img will be at the beginning of header img.
header img is inside of header, which itself is a flex-Container that tells all of its children to be justify-content: flex-end;.
As a child of header, header img will obey the rules of its parent.
If you want header img to be on the left and the rest on the right, you could wrap all of the header children you want to be on the right side in another div and set justify-content of the header to justify-content: space-between;.
That way, all of the direct children of header will be pushed apart as far as possible, since now it only has two children: header img and the newly created div containing everything else. If you now want the contents of the second child to be in a row, you simply give the div a class of display: flex;. You don't need to specific row, as that's the default flex-direction.
Here is an example:
Codepen Example
div.parent {
    display: flex;
    justify-content: space-between;
}

div.child-2 {
    display: flex;
}


text:
Q: Need to pull records from previous full hour regardless of time the query runs I want to pull records from the previous Full hour from when the query runs.
By this I mean regardless if it runs at 2:05 or 2:15 I will get records from 1:00:00 to 1:59:59.
Currently I get ORA-00907: missing right parenthesis error even though there are correct amount of parenthesis as far as I can tell. What am I doing wrong?
WHERE ((SS.NSAMPLE < SS.LSL OR SS.NSAMPLE > SS.USL) OR SS.FAILED = 'Y')
AND SD.DIMENSION_ID = SS.DIMENSION_ID
AND SUBDATE(STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d%H'), '%Y%m%d%H'), INTERVAL 1 HOUR) <= SS.SAMPLE_DATE AND SS.SAMPLE_DATE < STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d%H'), '%Y%m%d%H')

I also tried this and get the same missing right parenthesis error.
SUBDATE(SUBDATE(SUBDATE(SUBDATE(NOW(),
        INTERVAL EXTRACT(MICROSECOND FROM NOW()) MICROSECOND),
        INTERVAL EXTRACT(SECOND FROM NOW()) SECOND),
        INTERVAL EXTRACT(MINUTE FROM NOW()) MINUTE),
        INTERVAL 1 HOUR) <= SS.SAMPLE_DATE
    AND SS.SAMPLE_DATE < SUBDATE(SUBDATE(SUBDATE(NOW(),
        INTERVAL EXTRACT(MICROSECOND FROM NOW()) MICROSECOND),
        INTERVAL EXTRACT(SECOND FROM NOW()) SECOND),
        INTERVAL EXTRACT(MINUTE FROM NOW()) MINUTE)

A: You're using MySQL functions against an Oracle database. They are different database products, which both happen to be owned by Oracle Corp. (and have their documentation on docs.oracle.com), and the syntax varies. You might find the Oracle SQL Language Reference helpful.
To get data from the preceding hour in Oracle you can do:
AND SS.SAMPLE_DATE >= TRUNC(SYSDATE, 'HH') - INTERVAL '1' HOUR
AND SS.SAMPLE_DATE < TRUNC(SYSDATE, 'HH')

*

*SYSDATE gives you the system time, e.g. 2022-12-21 17:30:37

*TRUNC(SYSDATE, 'HH') gives you the system time truncated to the hour, e.g. 2022-12-21 17:00:00

*TRUNC(SYSDATE, 'HH') - INTERVAL '1' HOUR gives you the system time truncated to the hour, with an hour subtracted, e.g. 2022-12-21 16:00:00

The two filter conditions then look for values greater than or equal to the previous hour, and less than (but not including) this hour, so effectively for that example system time:
AND SS.SAMPLE_DATE >= timestamp '2022-12-21 16:00:00'
AND SS.SAMPLE_DATE <  timestamp '2022-12-21 17:00:00'

which covers all of the possible times in that hour-long period.
fiddle

The "ORA-00907: missing right parenthesis" error doesn't always mean you have the wrong number of parentheses. It means the parser got to a point where the next thing it expected to see was a right parenthesis, and it saw something else instead. It can have a variety of sometime non-obvious underlying problems.
In this case it's actually the interval syntax that's confusing it - if you change INTERVAL 1 HOUR to INTERVAL '1' HOUR to make it a valid Oracle interval literal then the error will change to "ORA-00904: "STR_TO_DATE": invalid identifier", which is easier to understand, as that's one of the MySQL functions that doesn't exist in Oracle.


text:
Q: Setting consider_all_requests_local temporarily for rspec testing rails I have some custom 404 and 500 pages I want to test, but I need Rails.application.config.consider_all_requests_local to be false for feature testing temporarily, and then turn it back on after the test is complete so that other tests can see the stack trace if they fail during testing. Is there any way of doing so or is there possibly another solution to achieve what I'm looking for?
For reference I am using Capybara and selenium-chrome to test.

A: You can set and the reset consider_all_requests_local in before/after blocks:
describe 'my awesome test' do
  before do
    Rails.application.config.consider_all_requests_local = false
  end

  after do
    Rails.application.config.consider_all_requests_local = true
  end

  it 'does something magical' do
    # some tests
  end
end


text:
Q: AWS IAM policy - How to check for multiple Tags as OR condition I'm trying to make a or condition in my IAM users but i don't know why it's not working...
I want two make a allow condition like this:
 if ec2:ResourceTag/User == "${aws:username}" || ec2:ResourceTag/Group == "Dev"

I have try many things but all not works...
"StringEquals": {
  "ec2:ResourceTag/User": "${aws:username}",
  "ec2:ResourceTag/Group": "Dev"
}
---
"ForAnyValue:StringEquals": {
  "ec2:ResourceTag/User": "${aws:username}",
  "ec2:ResourceTag/Group": "Dev"
}

EDIT ---
{
  "Effect": "Allow",
  "Action": [
      "ec2:StartInstances",
      "ec2:StopInstances",
      "ec2:RebootInstances",
      "ec2:TerminateInstances"
  ],
  "Resource": "*",
  "Condition": {
      "ForAnyValue:StringEquals": {
          "ec2:ResourceTag/User": "${aws:username}",
          "ec2:ResourceTag/Group": "Developers"
      }
  }
}

A: The following solution definitely works to check for distinct ResourceTag attributes with different values as OR condition. You can always put them into separate statements. Which is of course inconvenient:
{
  "Version": "2012-10-17",
  "Statement": [
      {
        "Sid": "sid1",
        "Effect": "Allow",
        "Action": [ ... ],
        "Resource": "arn:aws:...",
        "Condition": {
            "StringEquals": {
                "aws:ResourceTag/mytag": "myvalue"
            }
        }
      },
      {
        "Sid": "sid2",
        "Effect": "Allow",
        "Action": [ same as in sid1 ],
        "Resource": "same as in sid1",
        "Condition": {
            "StringEquals": {
                "aws:ResourceTag/myothertag": "myothervalue"
            }
        }
      }
  ]
}

I'm not aware of a solution which works with a single statement. If there is then it is not documented in AWS docs.


text:
Q: How to prevent Gitlab from counting merge commits when comparing two branches? I did web search on the topic and found and have read:
How to prevent Gitlab from creating extra merge commit on branch merge
What is the purpose of a separate merge commit in git?
So I see there maybe project setup to do fast-forward, but from other post I see separate merge commits serve useful purpose.
A, the problem: I'm working on (initial) copy of master branch (dev). I do commit in dev then merge to master via GitLab web GUI. I started to do so recently and just noted on such merge that GitLab informs me that my dev is behind ("Request to merge dev into master /
The source branch is 3 commits behind the target branch"). I took me a while (cause clicking on message gives full list of commits, not list of those 3) to realise those are my merge commits. AFAIK more standard way to use git is to branch, commit, merge and delete dev, but if I want to continue to use one branch, can I somehow quickly setup GitLab to ignore merge commits when comparing branches or quickly check in GitLab GUI that those differences are merge commits? Or else what can you advice except deleting dev every time?
ADDED:
Actually I have a related question (maybe because I have not used git log a lot (yet)). In docs there is a picture:
                   D---E-------F
                  /     \       \
                 B---C---G---H---I---J
                /                     \
               A-------K---------------L--M

So as I see it at point J middle brach merged to lower, but I do not see H, I etc on lower branch, but in GUI in GitLab for master I see both my merge commits and those commits I made on dev which were merged. Why is that?


text:
Q: ruby rails aquarium syntax error i having an issue with aquarium syntax for a rails app. its an app that i cloned from a github repository that i pushed it to, and it was working fine. im the only one pushing updates
========================
this is the error i get when i try to run rails s
/Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in require': /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/aquarium-0.3.0/lib/aquarium/aspects/exclusion_handler.rb:34: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n' (SyntaxError)
            when String: type_or_object.name.eql?(t)
                        ^
/Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/aquarium-0.3.0/lib/aquarium/aspects/exclusion_handler.rb:35: syntax error, unexpected keyword_when, expecting keyword_end
            when Symbol: type_or_object.name.eql?(t.to_s)
                ^
/Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/aquarium-0.3.0/lib/aquarium/aspects/exclusion_handler.rb:36: syntax error, unexpected keyword_when, expecting keyword_end
            when Regexp: type_or_object.name =~ t
                ^
/Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/aquarium-0.3.0/lib/aquarium/aspects/exclusion_handler.rb:37: syntax error, unexpected keyword_else, expecting keyword_end
            else type_or_object == t
                ^
/Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/aquarium-0.3.0/lib/aquarium/aspects/exclusion_handler.rb:61: syntax error, unexpected keyword_end, expecting $end
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:inblock in require'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:225:in block in load_dependency'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:593:innew_constants_in'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:225:in load_dependency'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:inrequire'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/aquarium-0.3.0/lib/aquarium/aspects/aspect.rb:5:in <top (required)>'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:inrequire'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in block in require'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:225:inblock in load_dependency'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:593:in new_constants_in'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:225:inload_dependency'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in require'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/aquarium-0.3.0/lib/aquarium/aspects.rb:2:in'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in require'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:inblock in require'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:225:in block in load_dependency'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:593:innew_constants_in'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:225:in load_dependency'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:inrequire'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/aquarium-0.3.0/lib/aquarium.rb:5:in <top (required)>'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327@global/gems/bundler-1.2.1/lib/bundler/runtime.rb:68:inrequire'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327@global/gems/bundler-1.2.1/lib/bundler/runtime.rb:68:in block (2 levels) in require'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327@global/gems/bundler-1.2.1/lib/bundler/runtime.rb:66:ineach'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327@global/gems/bundler-1.2.1/lib/bundler/runtime.rb:66:in block in require'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327@global/gems/bundler-1.2.1/lib/bundler/runtime.rb:55:ineach'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327@global/gems/bundler-1.2.1/lib/bundler/runtime.rb:55:in require'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327@global/gems/bundler-1.2.1/lib/bundler.rb:128:inrequire'
    from /Users/jcollyer/Documents/projects/hughes/hughes_cms/Funeral-Homes/config/application.rb:7:in <top (required)>'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.0.10/lib/rails/commands.rb:28:inrequire'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.0.10/lib/rails/commands.rb:28:in block in <top (required)>'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.0.10/lib/rails/commands.rb:27:intap'
    from /Users/jcollyer/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.0.10/lib/rails/commands.rb:27:in <top (required)>'
    from script/rails:6:inrequire'
    from script/rails:6:in `'
my gem file
source 'http://rubygems.org'

*

*gem 'rails', '3.0.10'

*gem 'sqlite3'

*gem 'mysql2','< 0.3'

*gem 'devise'

*gem 'simple-navigation'

*gem 'paperclip', '~> 2.4'

*gem 'jquery-rails', '>= 1.0.12'

*gem 'galetahub-simple_captcha', require: "simple_captcha"

*gem 'will_paginate', '~> 3.0'

*gem 'aquarium'

*gem "meta_search"

group :test, :development do
- gem "rspec-rails", "~> 2.6"
- gem "autotest"
- gem 'factory_girl'
end

A: Specify version of aquarium gem
gem "aquarium", "~> 0.5.1"

ruby 1.9.3 supports only from version 0.5.1

V0.5.1 (May 1, 2012): Now supports Ruby 1.9.3 and JRuby 1.6.7.

Source http://aquarium.rubyforge.org/
Or should I say use ruby-1.8.7 for this app instead of ruby-1.9.3. Because rails 3.0 can be incompatible with ruby-1.9.3


text:
Q: Xamarin: Using Community TabView to display two pages does not actually initialize the pages properly I have the following code behind - it loads in two pages from the app container.
I then add these to the TabView item, using their content. However, since this approach does not begin any type of "initialization" I had to add the _overviewPageViewModel.OnAppearing();
However, the content of the pages does not update at all when the data changes. I therefore added a messaging center solution, which also does not do anything.
I know this is already a hacky solution - does anyone know how to display two pages in a TabView properly, or atleast how to reflect change updates?
public partial class AdminOverviewTab : StyledPage
{
    private ApprovalPage _approvalPage = App.AppContainer.Resolve<ApprovalPage>();
    private OverviewPage _overviewPage = App.AppContainer.Resolve<OverviewPage>();
    private OverviewPageViewModel _overviewPageViewModel = App.AppContainer.Resolve<OverviewPageViewModel>();

    public AdminOverviewTab()
    {
        InitializeComponent();
        _overviewPageViewModel.OnAppearing();
        var ApprovalPage = new TabViewItem()
        {
            Text = "Approval",
            FontSize = 12,
            Content = _approvalPage.Content
        };

        var OverviewPage = new TabViewItem()
        {
            Text = "Overview",
            FontSize = 12,
            Content = _overviewPage.Content
        };

        MessagingCenter.Subscribe<OverviewPageViewModel>(this, "realTimeBalanceUpdate", (sender) =>
        {
            _overviewPage = App.AppContainer.Resolve<OverviewPage>();

            OverviewPage = new TabViewItem()
            {
                Text = "Overview",
                FontSize = 12,
                Content = _overviewPage.Content
            };
            Tab.TabItems[1].Content = _overviewPage.Content;
        });
        Tab.TabItems.Clear();
        Tab.TabItems.Add(ApprovalPage);
        Tab.TabItems.Add(OverviewPage);
        IconImageSource = "overview";
        Title = "Overview";
    }
}

}

A: You could use the INotifyPropertyChanged to update the data which you changed.
I make a tabview with two tabview items View1 and View2. In the View2 has a label with the Text BindableProperty. And there is a button in the tabview item View2. I use the button click event to update the data which i changed.
The code for TabView:
 public class Page8 : ContentPage, INotifyPropertyChanged
{
    private string _str;
    public string str
    {
        get { return _str; }
        set
        {
            _str = value;
            OnPropertyChanged("str");
        }
    }
    public Page8()
    {
        str = "hello";

        var view1 = new TabViewItem()
        {
            Text = "Approval",
            FontSize = 12,
            Content = new View1()

        };

        var v2 = new View2();
        v2.SetBinding(View2.TextProperty, "str");
        Button button = new Button();
        button.Clicked += delegate
        {
            str = "test";
        };

        var view2 = new TabViewItem()
        {
            Text = "Overview",
            FontSize = 12,
            Content = new StackLayout()
            {
                Children =
                {
                    v2,button
                }
            }
        };

        var tabView = new TabView();
        tabView.TabItems.Add(view1);
        tabView.TabItems.Add(view2);
        Title = "Overview";

        Content = tabView;

        this.BindingContext = this;

    }
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs((propertyName)));
    }

}

View2:
 Xaml:
   <ContentView.Content>
  <StackLayout>
      <Label x:Name="label" Text="{Binding Text}"  />

  </StackLayout>
 </ContentView.Content>

 Code behind:

  public partial class View2 : ContentView
{
    public static BindableProperty TextProperty = BindableProperty.Create(
propertyName: "Text",
returnType: typeof(string),
declaringType: typeof(View2),
defaultValue: string.Empty,
defaultBindingMode: BindingMode.OneWay,
propertyChanged: OnPropertyChanged);

    public string Text
    {
        get
        {
            return (string)GetValue(TextProperty);
        }
        set
        {
            SetValue(TextProperty, value);
        }
    }
    private static void OnPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var contentview = bindable as View2;
        contentview.label.Text = newValue.ToString();

    }
    public View2()
    {
        InitializeComponent();
    }

}


text:
Q: How to convert the & character to and using PHP I was wondering how can I convert user submitted data that contains an & to and using PHP before its stored in the database.

A: Use str_replace
$after = str_replace('&', 'and', $before);

Note that this will perform a straightforward replacement, hence (as seen on ideone.com):
$text = "ben & jerry, vanilla&coke";

echo str_replace('&', 'and', $text)."\n";
# ben and jerry, vanillaandcoke

If you want to insert spaces when there previously wasn't, then you may want to use regular expressions function like preg_replace as follows:
echo preg_replace('/\s*&\s*/', ' and ', $text)."\n";
# ben and jerry, vanilla and coke

The pattern \s* is the regex pattern for "zero or more" (*) of whitespace characters (\s). In other words, this will replace &, including any preceding and following whitespaces (of any length), and replace it with ' and '.

A: You could do it like this:
$str = str_replace("&", "and", $str);

A: Using str_replace (if your data is in a single character encoding) or mb_ereg_replace (preceded by mb_regex_encoding) otherwise.
Note, however, that str_replace is (in this case) safe for UTF-8.


text:
Q: Why does not cross-referencing of end nodes work with `enotez` and `cleveref`? It does not seem that cref works with enotez. The output refers to the chapter number rather than the number of the end note.
I had similar issue in this question: Why does not cross-referencing of exercises work with exsheets?
. It seems that the solution for exsheets does not work for enotez, because question is an environment while \endnote is a command

My source code
\documentclass{book}
\usepackage[x11names]{xcolor}

\usepackage{hyperref}
\hypersetup{linkbordercolor=DodgerBlue3, linkcolor=DodgerBlue3, colorlinks=true}

\usepackage{enotez}
% This package allows for the use of end notes

    \setenotez{mark-format=\tiny, list-name=End Notes of Chapter \thechapter,backref}
    \renewcommand{\theendnote}{\thechapter.\alph{endnote}}

    \DeclareInstance{enotez-list}{custom}{paragraph}{
        heading=\chapter*{#1},
        % Spacing
        notes-sep=0.5\baselineskip,
    %
        % Styling of the printed end notes
    %
            % Notes
            format=\normalfont,
    %
            % Numbering
            number-format=\normalfont,
    %
        % Notes numbering
        number=#1\hspace{3mm}
                                                    }

\usepackage{cleveref}
\crefformat{endnote}{End Note #2#1#3}
\crefrangeformat{endnote}{End Notes #3#1#4 to #5#2#6}
\crefmultiformat{endnote}{End Notes #2#1#3}{ and #2#1#3}{, #2#1#3}{ and #2#1#3}
\crefrangemultiformat{endnote}{End Notes #3#1#4 to #5#2#6}{ and #3#1#4 to #5#2#6}{, #3#1#4 to #5#2#6}{ and #3#1#4 to #5#2#6}

\newcommand{\sampletext}{\noindent This is a sample text for testing purposes}

\begin{document}

    \chapter{My Chapter}

    \sampletext \endnote{My End Note 1 \label[endnote]{en:endnote1}}

    \sampletext \endnote{My End Note 2 \label[endnote]{en:endnote2}}

    \sampletext \endnote{My End Note 3 \label[endnote]{en:endnote3}}

    \sampletext \endnote{My End Note 4 \label[endnote]{en:endnote4}}

    \sampletext \endnote{My End Note 5 \label[endnote]{en:endnote5}}

    \sampletext \endnote{My End Note 6 \label[endnote]{en:endnote6}}

    \sampletext \endnote{My End Note 7 \label[endnote]{en:endnote7}}

    \sampletext \endnote{My End Note 8 \label[endnote]{en:endnote8}}

    \sampletext \endnote{My End Note 9 \label[endnote]{en:endnote9}}

    \vspace{\baselineskip}

    \cref{en:endnote1,en:endnote2,en:endnote3}

    \cref{en:endnote4,,en:endnote5,,en:endnote6}

    \cref{en:endnote1,en:endnote2,en:endnote3,en:endnote5,en:endnote6,en:endnote9}

    \cref{en:endnote2,en:endnote3,en:endnote5,en:endnote6,en:endnote7,en:endnote8,,en:endnote9}

    \cref{en:endnote1,en:endnote2,en:endnote3,en:endnote5,en:endnote6,en:endnote7,en:endnote8,en:endnote9}

    \printendnotes[custom]

\end{document}

A:
I found the in Cleveref won't work with enotez
    \ExplSyntaxOn
    \cs_set_protected:Npn \enotez_endnote_mark:n #1
      {
        \int_gincr:N \g__enotez_endnote_id_int
        \quark_if_no_value:nTF {#1}
          {
            \refstepcounter {endnote}
            % \show \theendnote
            % \cs_gset:cpx {@currentlabel} {\theendnote}
            \enotez_write_mark:xn
              { \int_use:N \g__enotez_endnote_id_int }
              { \theendnote }
          }
          {
            \cs_gset:cpn {@currentlabel} {#1}
            % \cs_gset_eq:NN \theendnote \@currentlabel
            \enotez_write_mark:xn { \int_use:N \g__enotez_endnote_id_int } {#1}
          }
        \bool_if:NT \l__enotez_disable_bool
          {
            \int_gdecr:N \g__enotez_endnote_id_int
            \addtocounter {endnote} {-1}
          }
      }
    \ExplSyntaxOff

Full code

\documentclass{book}
\usepackage[x11names]{xcolor}

\usepackage{hyperref}
\hypersetup{linkbordercolor=DodgerBlue3, linkcolor=DodgerBlue3, colorlinks=true}

    \usepackage{enotez}

            \renewcommand{\theendnote}{\thechapter.\alph{endnote}}
            \setenotez{list-name=End Notes of Chapter \thechapter}
            \setenotez{backref=true}

        \DeclareInstance{enotez-list}{custom}{paragraph}{
            heading=\chapter*{#1},
            % Spacing
            notes-sep=0.5\baselineskip,
                % Default=0.5\baselineskip
        %
            % Styling of the printed end notes
        %
                % Notes
                format=\normalfont,
        %
                % Numbering
                number-format=\normalfont,
        %
            % Notes numbering
            number=#1\hspace{3mm}
                                                        }

        \ExplSyntaxOn
        \cs_set_protected:Npn \enotez_endnote_mark:n #1
        {
            \int_gincr:N \g__enotez_endnote_id_int
            \quark_if_no_value:nTF {#1}
            {
                \refstepcounter {endnote}
                % \show \theendnote
                % \cs_gset:cpx {@currentlabel} {\theendnote}
                \enotez_write_mark:xn
                { \int_use:N \g__enotez_endnote_id_int }
                { \theendnote }
            }
            {
                \cs_gset:cpn {@currentlabel} {#1}
                % \cs_gset_eq:NN \theendnote \@currentlabel
                \enotez_write_mark:xn { \int_use:N \g__enotez_endnote_id_int } {#1}
            }
            \bool_if:NT \l__enotez_disable_bool
            {
                \int_gdecr:N \g__enotez_endnote_id_int
                \addtocounter {endnote} {-1}
            }
        }
        \ExplSyntaxOff

\usepackage{cleveref}
\crefformat{endnote}{End Note #2#1#3}
\crefrangeformat{endnote}{End Notes #3#1#4 to #5#2#6}
\crefmultiformat{endnote}{End Notes #2#1#3}{ and #2#1#3}{, #2#1#3}{ and #2#1#3}
\crefrangemultiformat{endnote}{End Notes #3#1#4 to #5#2#6}{ and #3#1#4 to #5#2#6}{, #3#1#4 to #5#2#6}{ and #3#1#4 to #5#2#6}

\newcommand{\sampletext}{\noindent This is a sample text for testing purposes}

\begin{document}

    \chapter{My Chapter}

    \sampletext \endnote{My End Note 1} \label{en:endnote1}

    \sampletext \endnote{My End Note 2} \label[endnote]{en:endnote2}

    \sampletext \endnote{My End Note 3} \label[endnote]{en:endnote3}

    \sampletext \endnote{My End Note 4} \label[endnote]{en:endnote4}

    \sampletext \endnote{My End Note 5} \label[endnote]{en:endnote5}

    \sampletext \endnote{My End Note 6} \label[endnote]{en:endnote6}

    \sampletext \endnote{My End Note 7} \label[endnote]{en:endnote7}

    \sampletext \endnote{My End Note 8} \label[endnote]{en:endnote8}

    \sampletext \endnote{My End Note 9} \label[endnote]{en:endnote9}

    \vspace{\baselineskip}

    \cref{en:endnote1}

    \cref{en:endnote1,en:endnote2,en:endnote3}

    \cref{en:endnote4,,en:endnote5,,en:endnote6}

    \cref{en:endnote1,en:endnote2,en:endnote3,en:endnote5,en:endnote6,en:endnote9}

    \cref{en:endnote2,en:endnote3,en:endnote5,en:endnote6,en:endnote7,en:endnote8,,en:endnote9}

    \cref{en:endnote1,en:endnote2,en:endnote3,en:endnote5,en:endnote6,en:endnote7,en:endnote8,en:endnote9}

    \AfterNextEndnotesList{A sample of text that comes before end note list}
    \AtNextEndnotesList{A sample of text that comes after end note list}
    \printendnotes[custom]

\end{document}


text:
Q: OpenCV input delay in capturing frames I have written a code to enable capturing images from webcam feed using OpenCV. However there is an input delay whenever I press the key to capture my frame. There is no delay when I use it to quit, but there a significant delay when I use capture. I measured this by printing a statement inside both the cases, on pressing c the statement takes a delay before printing. The problem seems to me something like...the camera resources are being used and not freed up in time for the next key press or something like that....but not sure.
import cv2 as cv
import numpy as np
import glob
import matplotlib.pyplot as plt

cap = cv.VideoCapture(1)

img_counter = 0

while True:
    ret, frame = cap.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # cv.imshow('frame',frame)
    cv.imshow('gray', gray)
    if not ret:
        break

    if cv.waitKey(1) & 0xFF == ord('q'):
        print('helloq')
        break

    elif cv.waitKey(1) & 0xFF == ord('c'):
        print('hello{}'.format(img_counter))
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv.imwrite(img_name, gray)
        img_counter += 1

I am using an external web camera and
cv2.__version__ = 3.4.2`

A: Solved your issue, it seems like its caused by your key check.
You should not call waitKey(1) more than once. It causes lag.
Try this solution:
cap = cv.VideoCapture(0)

img_counter = 0

while True:
    ret, frame = cap.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # cv.imshow('frame',frame)
    cv.imshow('gray', gray)
    if not ret:
        break

    key = cv.waitKey(1)

    if key==ord('c'):
        print('img{}'.format(img_counter))
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv.imwrite(img_name, gray)
        img_counter += 1
        print("Succesfully saved!")

    if key==ord('q'):
        print('Closing cam...')
        break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()


text:
Q: Angular 4 Data is not getting displayed in table Trying an example in angularjs 4 to display the list of items in bootstrap table, I am loading the data from the .json file and trying to display using bootstrap table the table header is displaying properly but the data is not getting displayed let me know if I am making any mistakes
Here is the code,
Below is the component.ts file

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import * as _ from "lodash";

@Component({
  moduleId: module.id,
  selector: 'drivers-list',
  templateUrl: './drivers-list.component.html',

})
export class DriversListComponent implements OnInit {
    public data: any[];
    public filterQuery = "";
    public rowsOnPage = 10;
    public activePage = 1;
    public sortBy = "email";
    public sortOrder = "asc";
    public itemsTotal = 0;
    constructor(private http: Http) {
    }
    ngOnInit(): void {
        this.loadData();
    }

    public loadData() {
        this.http.get("assets/data2.json")
            .subscribe((data) => {
                setTimeout(() => {

                    this.data = _.orderBy(data.json(), this.sortBy, [this.sortOrder]);
                    this.data = _.slice(this.data, (this.activePage-1)*this.rowsOnPage, (this.activePage-1)*this.rowsOnPage + this.rowsOnPage);
                    this.itemsTotal = data.json().length;
                }, 2000);
            });
    }

    public toInt(num: string) {
        return +num;
    }

    public sortByWordLength = (a: any) => {
        return a.city.length;
    }

Below is the html file template file,

                        DRIVER
                        LAST ACTIVE
                        CYCLE
                        GROUPS
                        APP VERSION
                        STATUS
                        ACTIONS

                        {{item.id}}
                        {{item.name}}
                        {{item.price}}

using ngFor to iterate the rows

A: The bootstrap table https://github.com/wenzhixin/bootstrap-table/ is not working with angular 4.
Started using the below table
https://github.com/CasperTech/angular2-datatable-pagination
Now every thing is working fine.


text:
Q: Generalized binomial coefficients While doing an alternate way of establishing the binomial seris
$$(1+x)^{\alpha}=\sum_{n=0}^{\infty} {\alpha \choose n}x^n=f(x) $$
where $\alpha$ is any number.
I am asked to prove the following: (assuming the converge of $f(x)$ for $|x|<1$)
show that $(1+x)f'(x)=\alpha f(x)$
My attempt is as follows:
$$\begin{align*} (1+x)f'(x) = & (1+x)\sum_{n=1}^{\infty}n{\alpha \choose n}x^{n-1}\\
= & \sum_{n=0}^{\infty}\left[n{\alpha \choose n}+(n+1){\alpha \choose {n+1}}\right]x^n
\end{align*}$$
Now i wish to establish that
$$ n{\alpha \choose n}+(n+1){\alpha \choose {n+1}}=\alpha{\alpha \choose n}$$
So I rewrite the lefthandside as
$$\frac{n\alpha(\alpha-1)\dots(\alpha-n+1)}{n!}+\frac{(n+1)\alpha(\alpha-1)\dots(\alpha-n+2)}{(n+1)!}=\frac{(n(\alpha-n+1)+1)\alpha(\alpha-1)\dots(\alpha-n+2)}{n!}$$
Here i have trouble continuing. If $\alpha$ where a whole number then I could have done the above by writing ${\alpha \choose n}=\frac{\alpha!}{n!(\alpha-n)!}$ but here it does not seem to apply. Any tips or hints?

A: $\frac{n\alpha(\alpha-1)\dots(\alpha-n+1)}{n!}+\frac{(n+1)\alpha(\alpha-1)\dots(\alpha-n)}{(n+1)!}=\frac{(n)(\alpha)...(\alpha-n+1)+(\alpha)...(\alpha-n+1)(\alpha-n)}{n!}=\frac{(\alpha)...(\alpha-n+1)(n+(\alpha-n))}{n!}=\alpha\frac{(\alpha)...(\alpha-n+1)}{n!}=\alpha{\alpha \choose n}$


text:
Q: VBA to stop running nested macros in excel? I have a button on my spreadsheet that when clicked, triggers a series of nested subs. Example:
Sub Button1_Click()
    Macro1
    Macro2
    Macro3
    Macro4
    Macro5
    Macro6
End Sub

Because the time to run all these subroutines can be rather lengthy, and the user cannot do anything else in excel while it is running, I was wondering if there was a way to create a button that, when clicked, can halt the running of all these subs? I've seen recommendations of adding DoEvent to the code, however, I'm not sure where in my code to implement it.
Any insight would be much appreciated.

A: The DoEvents statement will allow any lagging user input and handling of events.
The Solution
What you probably want to do is overload the OnKey event handler and use it to set the value of a global variable. Next in your code above you need to verify if that variable is set. If it is abort execution. Be sure to add DoEvents statements in any moments in your code where you want this to run.
Optionally, w/o the OnKey handler, DoEvents will allow the user to hit ESC to stop the execution of your macro. But it will revert to debug mode and highlight the current executed row in your procedure. Not sure this is what you want however.
Tip - what to do first
Having said that... what I personally think you should do FIRST is optimize your VBA code. I would assume there is probably a lot of room for improving the execution time of your procedure (my tutorial).

A: You can create Macro to perform below steps/operation and call when you want to abort the other running macros:
Step 1-- Menu bar -> Run -> Reset
Step 2-- Menu bar -> Run -> Break


text:
Q: Как восстановить пароль к бд в формате .FDB Имеется локально программа, в ней есть бд в формате .FDB и скорее всего, она под паролем. Т.к ни одна программа и скрипт не могут сделать коннект, могу ли я как-то сбросить или подобрать его?

A: Если Firebird версии меньше 3.0, то сама база точно не запаролена. Список пользователей и пароли хранятся на сервере. Самый простой способ - перенести базу на другой сервер, где пароль известен.


text:
Q: Lua nvim_command highlight not working unless manually run I have the following line at the very end of my init.lua
vim.api.nvim_command('hi CursorLineNr guibg=bg')

But it doesn't work. When I launch nvim, the CursorLineNr highlight group is still wrong. And yet, when I manually type :hi CursorLineNr guibg=bg, it works.
I'm not sure if this has to do with any Packer plugins finishing execution after the very last line of my init.lua or something?

A: I have no idea if this is "correct", but it worked for me:
vim.api.nvim_command[[
  autocmd ColorScheme * highlight CocErrorSign guifg=#bf616a
]]

A: Make sure to put highlight settings after the colorscheme is set in your init.lua because it resets the highlight.
vim.cmd("colorcheme gruvbox")
vim.cmd("hi CursorLineNr guibg=bg")

In this order


text:
Q: Git - End of line characters causing fake diffs I have a git repository which is hosted in bit bucket. I use source tree to work with git. I have a pull request in which some files appear as modified, but the contents of the file are essentially unchanged. I noticed that when I compared the two branches in bit bucket and source tree. This is what the diff looks like in those tools :
-j1
-j2
-j3
+j1
+j2
+j3

This is very confusing because (1) it makes it appear as though there are many changes, even though there are no real changes, and (2) any changes to a particular line could be missed if you have a huge file (unlike the small one I showed above.)
But, when I compared the two branches in command line (git diff branch1 branch2), I saw that there is a ^M character at the end of each line in one branch which is responsible for the difference.
How do I ensure that end of line characters like ^M, TAB, SPACE etc. get removed in git so that we can avoid confusion in pull requests ? Also, how do I find out why these EOL characters got added in the first place ?

A: Try first
git config --global core.autocrlf false

Then clone again, and make sure there is no diff.
That will ensure there is no "automagic" eol conversion.
Then you can add in a .gitattributes eol directives (example here)


text:
Q: multidimensional arrays arrays inside an array in ruby Data Structure is my weakness and I want to get a deeper understanding on it. would appreciate some clarification here.
sandwiches = [["cheese", "ham"], ["avocado", "bacon"], ["tomato","pesto","cheese","mayo"], ["egg"], ["turkey", "ketchup", "mustard"]]

Please correct me if I am wrong. thanks!
Inside sandwiches, there is 1 array.
Inside the sub-sandwiches array, there are 5 arrays.
But I'm stuck on understanding how many elements there are in the sandwiches array and the sub sandwiches array.

A: You can use Ruby itself to figure out the answer to such questions:
sandwiches.map(&:length)
#=> [2, 2, 4, 1, 3]

This gives you the length of each array nested in sandwiches.
Note that .map(&:length) is the short version of .map { |x| x.length }.

A: The sandwiches array contains 5 elements (and each of these elements is also an array):
sandwiches = [
["cheese", "ham"], #first element of sandwiches -> an array with 2 elements (cheese and ham)
["avocado", "bacon"], #second element of sandwiches, an array with 2 elements (avocado and bacon)
["tomato","pesto","cheese","mayo"], # third element of sandwiches, an array with 4 elements (tomato, pesto, cheese and mayo)
["egg"], # fourth element of sandwiches, an array with one element (egg)
["turkey", "ketchup", "mustard"] # fifth element of sandwiches, an array with 3 elements (turkey, ketchup and mustard)
]

A: you have 1major array with 5 elements [0,1,2,3,4]
Element at position 0 is another array with 2 elements
Element at position 1 is another array with 2 elements too
Element at position 2 is another array with 4 elements
Element at position 3 is another array with 1 element
Element at position 4 is another array with 3 elements
Ps: u can consider a position each element separated by comas (,)
i.e:  [ fisrt_element,  second_element,  [fist_element_of_this_arry, second_element_of_this_arry], fourth_element]
so the array above is one major array with 4 elements and element 3 is an array with two elements:   [0,1, [ 0,1], 3]
remember that array position aways begin from 0


text:
Q: Sci-fi short story collection: alien hunting humans, NOVA bombs, pet generating antibodies Many years ago I read a book — a collection of short sci-fi stories — and I remember vaguely a couple of them. I think the book was called "Dust," and the cover had an alien imagery of an ocean with alien structures (almost looking like ships).
One of the stories was from a point of view of an alien who was hunting humans. Every time a human was found dead, a large part of the protein was missing. At the end the alien tried to run away with a ship, but was caught by humans as we had the ability to stop abruptly in space..., etc.
I remember a detail of another story: it was some kind of war and there were NOVA bombs being used. The only protection was using fields which do not allow fast moving objects — most of the fighting within those fields was with melee weapons and arrows.
And my last vague recollection was of a story about a scientist who had a pet able to generate antibodies for any disease as long a sample was injected in a pre-numbed area.
Lots of nostalgia for this book — I read it in the late '80s. I appreciate any help!

A: For the record I'll document the identifications of the three stories made in the comments. I have made this a community wiki answer so please feel free to update/correct it as necessary.
The first story is Black Destroyer by A. E. Van Vogt. The creature is called Coeurl and is the last of its kind on a desert planet. It feeds by extracting a chemical from the creatures it kills. In the original story this was phosphorus, though when the story was included in the fix-up novel The Voyage of the Space Beagle this was changed to potassium. The humans trick Coeurl by stopping their ship instantly then approaching Coeurl so their ship looks like Coeurl's home star. Coeurl commits suicide when it realises it is doomed.
The second story is from Joe Haldeman's Forever War series. It could be an excerpt from one of the novels, or it could be the novella End Game published in 1975, which has an extended sequence of actual melee combat in the stasis field, punctuated by a nova bomb. This contains the scene mentioned in a comment where a quarterstaff is poked through the statis field and becomes red hot:

I took one of the quarter staffs down to the edge of the field and poked it through, a centimeter or so. When I drew it back. the point was melted off. When I showed it to Charlie, he just rocked back and forth (the only way you can nod in a suit); this sort of thing had happened before, one of the first times the stasis field hadn't worked. They simply saturated it with laser fire and waited for us to go stir-crazy and tum off the generator. They were probably sitting in their ships playing the Tauran equivalent of pinochle .

The third story could be The Mutant Weapon by Murray Leinster, which is part of his Med Ship series. The creature is called Murgatroyd:

Murgatroyd was the tormal member of the Aesclipus Twenty's crew. During three weeks of overdrive travel he was his normal self. He was a furry, companionable small animal who adored Calhoun, coffee, and pretending to be human, in that order. Calhoun traveled among the stars on professional errands, and Murgatroyd was perfectly happy to be with him. His tribe had been discovered on one of the Deneb planets; their charming personalities made them prized as pets. A long while ago it had been noticed that they were never sick. Then it developed that if they were exposed to any specific disease, they instantly manufactured overwhelming quantities of antibody for that infection. Now it was standard Med Service procedure to call on them for this special gift. When a new strain or a novel variety of disease-producing germ appeared, a tormal was exposed to it. They immediately made a suitable antibody, the Med Service isolated it, analyzed its molecular structure, and synthesized it. So far there hadn't been a single failure. So tormals were highly valued members of Med Ship crews.

In particular, The Mutant Weapon contains the text:

The tormal wriggled as Calhoun made the injection. But it did not hurt. There was an insensitive spot on his flank where the pain-nerves had been blocked off before he was a week old.

However all three of these are really novellas rather than short stories so including them would make for a long anthology. Also there is no anthology containing all three listed on the ISFDB. This makes it sound like you might have read an unauthorised collection.


text:
Q: how to configure QT creator cross compiling
Actually i installed QT creator in my debian linux system which is having i386 processor.Now i need to cross compile the QT for debian linux with ARM processor.
So for this cross compile process i installed the compiler arm-linux-gnueabi-gcc-4.4 manually and add it in the QT creator "Tools->Options->Build&Run-->Compiler".
After that i have no idea of how to configure the installed (arm-linux-gnueabi-gcc-4.4) compiler in kit option. Because in kit option "Device Type" , it is expecting for the Qmake file of arm-linux-gnueabi-gcc-4.4.Here my doubt is

*

*Is it possible to create Qmake file for the compiler (arm-linux-gnueabi-gcc-4.4)

*If that case what is the procedure to create Qmake file for the compiler (arm-linux-gnueabi-gcc-4.4)

*If not in the case any dependencies need to install.

*By googling around for this solution finally i felt my head rotate because in QT documentQT document they mention 5 steps.Among 5 steps i stuck in 2nd step itself (./configure -embedded arm -xplatform qws/linux-arm-g++ ).In this step im not able to understand what is configure , embedded, arm, xplatform etc...

*In some link link number 2 they suggested to install bitbake and some steps.Here im not able to install bitbake also.

*In some qt documents they mentioned embedded linux (is embedded linux is a OS like debian) and mkspecs etc..
Finally i decided to create Qmake file for the compiler arm-linux-gnueabi-gcc-4.4 but not having the single clue also.So if anybody knows what exactly i need to configure QT creator (either Qmake for compiler arm-linux-gnueabi-4.4  or something else ) so that i will follow exactly the required thing without any confusion.

A: Qt cross compiling for arm based board can be sucessfully done using Angstrom cross compiler. Just download Angstrom cross compiler as per your board configuration  , unpack it and create cross compiler using that package.


text:
Q: Creating dummy hardware to send data to ros node with specific ip address I have ros node which is continuously polling on some packets and it accepts them only from specific ip, now I want to send some packets so that node will receive it.
How do I create dummy h/w which will have that specific ip address and my ros node will capture data from that?

A: If you can set an IP in your node then you don't need DUMMY H/W.
You can use your own local IP (127.0.0.1 AKA localhost) and custom port (if your code accepts it).


text:
Q: What is the definite integral from c to c of a function that is undefined at x=c? Since when $f(x)$ is undefined at $x=c$ and $a \leq c \leq b$
$\int_{a}^{b}f(x)dx$
is undefined as it takes the definite integral over an undefined region of the function. Or in another sense, since all definite integrals that cover an undefined portion of $f(x)$ are undefined.
And since
$\int_{a}^{a}f(x)dx=0$
is considered true (at least to my understanding) for any value, $a$, and any function, $f(x)$. Does that make
$\int_{c}^{c}f(x)dx=0$
or
$\int_{c}^{c}f(x)dx$ undefined
When $f(x)$ is undefined at $x=c$?


text:
Q: How to display dynamically textfields and checkboxes and filling them with database data Im making school project, it's survey system,
Its client/server application using mysql database,
Server gets data(poll titles) from mysql database and sends it to the client while he connects.
Those titles are being displayed in JComboBox so user can choose which poll he want to answer.
I want to click on poll title in JComboBox and want to display on JPanel questions and available answers linked to chosen poll title, each poll can have diffrent questions count and diffrent answers count, and I want to display those poll questions and answers in Jcomponents:
Questions: I want to display them in JTextFields
Answers: I want to display them in Labels with checkboxes near them so user can select answer he wants
Also I want to have displayed Labels with Question 1 Question 2 etc near questions,
so how to make it dynamically? Please help me
Thank you

A: Have you considered using JSF with EJB  for this process?
JSF allows you to create a webpage UI, which is connected to a java beans controller, which is then connected to a controller for your database. Everything is very clear and independed in this model and is specifically designed for these situations. You can see a simple example here :
http://www.adam-bien.com/roller/abien/entry/simplest_possible_jsf_2_ejb
In case you have to use swing it wont do for you although its something good to know, and its design can help you in other situations.


text:
Q: Full Referrer not showing full URL I am trying to exclude "Affirm.com" from my analytics property. I have already added "affirm.com" to my referral exclusion list, but I am still getting results for "affirm" in my channel report.
Is there any reason that it is showing just "affirm" under the Full Referrer and not "affirm.com"? It is also showing just affirm for the source, medium, and campaign.
screenshot of the GA results
Thanks - let me know if you need more details. (Affirm is a payment system similar to Paypal)

A: Probably because you pass it to Analytics with UTM parameters.


text:
Q: Three post requests to the same method, how to run the method just once time sharing the result to the three of them? I have three post flask requests that goes to 3 different APIs, get_max, get_min, get mean.
These three APIs are calling the same method, because a method returns all the information in a dictionary.
How could I just run the method one time without changing the three API calls and not using self? Is there any pattern for this?
API Calls:
self.app.add_url_rule(API + '/get_max', 'get_max', self.get_max, methods=['GET', 'POST'])
self.app.add_url_rule(API + '/get_min', 'get_min', self.get_min, methods=['GET', 'POST'])
self.app.add_url_rule(API + '/get_mean', 'get_mean', self.get_mean, methods=['GET', 'POST'])

Shared method:
def get_all(self, data):
    result={}
    result["max"] = data["price"].max()
    result["min"] = data["price"].min()
    result["mean"] = data["price"].mean()
    return result

Thanks in advance.


text:
Q: How to control the very audio play icon instead of looping them all? Music and Icons are linking alright. I've been trying to toggle the icon for play and pause, and it work.
But how can I toggle only the one with music playing?
Here is the HTML:

NutCracker

 Kinderszenen

 <audio id="Kinderszenen" src="https://p.scdn.co/mp3-preview/ac35d32b11fdf0d60f676b0060fd1874d663726f?cid=774b29d4f13844c495f206cafdad9c86"></audio>
 <audio id="Nutcracker" src="https://p.scdn.co/mp3-preview/08f0833d7a2132f0a3863bb51b439a3061f55717?cid=774b29d4f13844c495f206cafdad9c86"></audio>

And JavaScript
const musicOn = document.querySelectorAll('.album-btn');
const controlIcon = document.querySelectorAll('.album-btn .fas');

musicOn.forEach(comeOn =>{
  comeOn.addEventListener('click', ()=> musicToggle(comeOn))
})

function musicToggle(comeOn) {

  const musicAudio = document.getElementById(comeOn.dataset.music);

  controlIcon.forEach(playPause => {

    if (playPause.classList.contains('fa-play-circle')){

        musicAudio.play(playPause);
        playPause.classList.remove('fa-play-circle');
        playPause.classList.add('fa-pause-circle');
    } else {
      musicAudio.pause(playPause);
      playPause.classList.remove('fa-pause-circle');
      playPause.classList.add('fa-play-circle');
    }
 })
}

A: Use the paused event to check audio is playing or not
let aud = document.getElementById("myAudio");
alert("Audio paused: ", aud.paused);

Also you can get the first played range, You can get the starting and ending seconds.
let aud = document.getElementById("myAudio");
alert("Start: " + aud.played.start(0) + " End: " + aud.played.end(0));

A: Using e.target
const musicOn = document.querySelectorAll('.album-btn');

const controlMusic = document.querySelectorAll('.album-btn .fas');

musicOn.forEach(comeOn =>{
  comeOn.addEventListener('click', e=> musicToggle(comeOn, e))
})

function musicToggle(comeOn, e) {

  const musicAudio = document.getElementById(comeOn.dataset.music);

  let playPause = e.target

    if (playPause.classList.contains('fa-play-circle')){

      musicAudio.play(playPause);

      playPause.classList.remove('fa-play-circle');
      playPause.classList.add('fa-pause-circle');
      playPause.style.color = "#fff";
    } else {

      musicAudio.pause(playPause);

      playPause.classList.remove('fa-pause-circle');
      playPause.classList.add('fa-play-circle');
    }
}


text:
Q: How to send an email using an API in python with an email that was received using POST method in html form? I'm trying to create an HTML form wherein when the user inputs their email, it'll immediately execute an email being sent to them. I'm doing this through a Mailgun API and a super simple HTML form, and whilst the form works and the code for sending the email works on its own as its own separate python file, I can't for the life of me figure out how the two can connect. Any help or direction would be greatly appreciated!
from flask import Flask, render_template, request
import requests
app = Flask("MyApp")

@app.route('/')
def main():
    return render_template("emailform.html")
@app.route("/mail", methods=["POST"])
def sign_up():
    form_data = request.form
    print form_data["email"]
    return "Thanks"

def send_simple_message():
    return requests.post(
    "https://api.mailgun.net/v3/sandboxurl",
         auth=("api", "myapikey"),
         data={"from": "Excited User <mailgun@sandboxurl.mailgun.org>",
            "to": "email",
            "subject": "This is a subject line",
            "text": "This is the email body"})
send_simple_message()
app.run(debug=True)

A: Replace your print statement in sign_up with the code to send the message.
You'll probably need to form_data to fill out the email call, replacing the hard-coded strings you are using in send_simple_message with information from the form (I'd suggest passing the form as a parameter to send_simple_message).


text:
Q: How can I create a nonnegative integer regular expression? I want to compile a Pattern that matches nonnegative integers. It should look for a sequence of one or more consecutive digits that is not preceded by another digit or a negative sign. I have been able to compile the following:
Pattern digit = Pattern.compile("\\d");  //looks for single digits

But suppose I declare the following:
String a = "90 210";
String b = "-90 210";
String c = "z90p210";
String d = "pz-90210";

digit would match "9", "0", "2", "1", and "0" in all four of these. I'm interested in a Pattern that would match "90" and "210" in a, "210" in b, "90" and "210" in c, and would not match anything in d.
Is there a way to disregard sequences of digits preceded by a negative sign or another digit?

A: You can use a negative lookbehind assertion: (?<!...) (not preceded by)
Pattern digit = Pattern.compile("(?<![\\d-])\\d+");

A: public static void main(String[] args) {
    String[] s = { "90 210", "-90 210", "z90p210", "pz-90210" };
    for (String str : s) {
        System.out.println(str
                .matches("(-|[A-Za-z])*?\\d+(\\s|[a-zA-Z])+\\d+"));

    }
}

O/P : true
true
true
false


text:
Q: Error in Merging one LSTM model output and VGG model output

#make custom embedding layer
embedding_layer = Embedding(len(word_index) + 1,
                        EMBEDDING_DIM,
                        weights=[embedding_matrix],
                        input_length=max_length_of_text,
                        trainable=False)

#make lstm model
inputs = Input((max_length_of_text, ))
x = embedding_layer(inputs)
x = LSTM(units=512, return_sequences=True)(x)
x = Dropout(0.1)(x)
x = LSTM(units=512, return_sequences=False)(x)
x = Dropout(0.1)(x)
x = Dense(1024, activation='tanh')(x)
lstm_model = Model(inputs,x)

#make vgg model
vgg = VGG16(weights=None, include_top=True)
vgg.load_weights('./vgg_weights.h5')
vgg.layers.pop()
for l in vgg.layers[:]:
    l.trainable = False
inp = vgg.input
out = Dense(1024, activation='tanh')(vgg.layers[-1].output)
vgg_model = Model(inp,out)

#make final model
fc_model = Sequential()
fc_model = Multiply()([vgg_model.output,lstm_model.output]))
fc_model.add(Merge([vgg_model, lstm_model], mode='mul'))
fc_model.add(Dropout(0.2))
fc_model.add(Dense(512, activation='tanh'))
fc_model.add(Dropout(0.2))
fc_model.add(Dense(26, activation='softmax'))
fc_model.compile(optimizer='rmsprop', loss='categorical_crossentropy',
    metrics=['accuracy'])

fc_model.summary()

'''
if os.path.exists(model_weights_filename):
   print "Loading Weights..."
   fc_model.load_weights(model_weights_filename)

'''

#Train

#--
img_lis_train = img_lis[ : 108032]
img_lis_test  = img_lis[ 108032 : ]
questions_train = questions[ : 108032]
questions_test  = questions[ 108032 : ]
answers_train = answers[ : 108032]
answers_test  = answers[ 108032 : ]

def mygen(questions_train,img_lis_train,answers_train):
    start = 0
    data_size = len(questions_train)
    batch_size = 64
    while True:
        if( start+batch_size <= data_size ):
            batch_ques = questions_train[ start : start+batch_size ]
            batch_ans = answers_train[ start : start+batch_size ]
            batch_img_names = img_lis_train[ start : start+batch_size ]
        elif(start < data_size):
            batch_ques = questions_train[ start : ]
            batch_ans = answers_train[ start : ]
            batch_img_names = img_lis_train[ start : start+batch_size ]
        else:
            break

        batch_img = []
        for img_name in batch_img_names:
            img = load_img('./dataset/images/' + str(img_name) + '.png' , target_size = (224,224))
            img = img_to_array(img)
            batch_img.append( preprocess_input(img) )

        start += batch_size
        print('start = ' + str(start))
        yield [np.array(batch_img), np.array(batch_ques)] ,np.array(batch_ans)

class WeightsSaver(Callback):
    def __init__(self, N):
        self.N = N
        self.batch = 0

    def on_batch_end(self, batch, logs={}):
        if self.batch % self.N == 0:
            name = './weights/weights.h5'
            self.model.save_weights(name)
        self.batch += 1

fc_model.load_weights('./weights/weights.h5')
fc_model.fit_generator(mygen(questions_train, img_lis_train , answers_train ), steps_per_epoch = 1688, epochs = 100 ,callbacks=[WeightsSaver(10)])

The errors I am getting is fc_model is converting to tensor using:
fc_model = Multiply()([vgg_model.output,lstm_model.output]))

and in earlier version of Keras
fc_model.add(Merge([vgg_model, lstm_model], mode='mul'))

was working but Merge is removed from new versions of Keras. I want to multiply the output LSTM model and VGG model in fc_model. Can anyone suggest me anything?

A: You need to use Keras functional API to be able construct a non-sequential model. So your code would look like this:
mult = Multiply()([vgg_model.output,lstm_model.output])
x = Dropout(0.2)(mult)
x = Dense(512, activation='tanh')(x)
x = Dropout(0.2)(x)
out = Dense(26, activation='softmax')(x)

fc_model = Model([vgg_model.input, lstm_model.input], out)


text:
Q: Categorization of Group Scheme of rank 2 I got stuck on this Exercise 2.11 in the book Introduction to Affine Group Scheme of Waterhouse. I really appreciate if anyone can give me a hint.

Let $A$ be a Hopf algebra over $k$ (a base ring) which is free of rank 2. I proved that $I = Ker(\epsilon) = kx$ for some $x$, and $\Delta(x) = x \otimes 1 + 1 \otimes x + b x\otimes x$ for some $b$ in k. Show that $x^2 + ax = 0$ for some $a$, so $A = k[X]/(X^2 + aX)$.

I guess we can obtain the equation $x^2 + ax = 0$ from $\Delta(x) = x \otimes 1 + 1 \otimes x + b x\otimes x$. We can apply multiplication to both sides of the equation, but I don't know how $\Delta$ behaves under multiplication. Thanks in advance.

A: Since $\{1, x\}$ is a basis for $A$, you can write $x^2 = c_1 + c_2 x$ for some $c_1, c_2 \in k$.  Apply $\epsilon$ to this equation to show that $c_1 = 0$, so that $x^2 = c_2 x$.


text:
Q: Interior of the boundary of an open set is empty Let $(X, \mathcal{T})$ be a topological space. Suppose $A \in \mathcal{T}$. We define the interior of $A$, the closure of $A$ and the boundary of $A$ as follows:
$\operatorname{int}A=\lbrace x \in A\mid A \in \gamma(x) \rbrace$, where $\gamma(x)$ denotes the neighborhood filter of $x$.
$\operatorname{cl}A=\lbrace x \in X\mid \forall V \in \gamma(x): V \cap A \neq \emptyset \rbrace$
$\partial A= \operatorname{cl}A \cap \operatorname{cl}(X\setminus A)$
How do you prove that $\operatorname{int}(\partial A) = \emptyset$? I already have that $\operatorname{int}(\partial A)=\operatorname{int}(\operatorname{cl}A \setminus A)$, but how do you continue from this point?

A: When A is open
int $\partial$A = int (cl A $\cap$ cl $A^c$)
= int cl A $\cap$ int cl A$^c$ = int cl A - cl int A
= int cl A - cl A = empty set.
The crutial step uses the important
self dual theorem of topological duality.
cl K$^c$ = (int K)$^c$;  int K$^c$ = (cl K)$^c$


text:
Q: Rails 3.0 / net-ldap - works in irb, but not in app I've looked around and can't seem to find the answer to this... I'm trying to use net-ldap with rails.
in irb, I can run a quick bind and it works:
irb(main):003:0> ldap_con = Net::LDAP.new({:host => 'myhost.ad',
irb(main):004:2*       :base => 'DC=myhost,DC=ad',
irb(main):005:2*       :port => 389,:auth=>{:method=>:simple,:username => 'bsharpe@myhost.ad',
irb(main):006:3*       :password => 'letmein' } } )
=> #<Net::LDAP:0x292089f0 @host="myhost.ad", @open_connection=nil, @encryption=nil, @auth={:password=>"letmein", :method=>:simple, :username=>"bsharpe@myhost.ad"}, @verbose=false, @port=389, @base="DC=myhost,DC=ad">
irb(main):007:0> ldap_con.bind
=> true

but if i run the app i get
no such file to load -- net/ldap

which is from my require net/ldap
I checked $LOAD_PATH and it does contain /usr/local/lib/ruby/gems/1.8/gems/net-ldap-0.1.1/lib
What am I missing here?

A: I had the same problem. Adding: require 'rubygems' before require 'net/ldap
For example:
#!/usr/bin/ruby -w
require 'rubygems'
require 'net/ldap'

ruby version 1.8.7 and net/ldap(0.3.1)


text:
Q: rails does not apply JavaScript to appended items in remote true? I have this code below and when I click on the pagination it appends parent but without any JavaScript added ? I tried to put the scripts on js file but no use , the only way it works is in the js.erb file but this will lead to duplicate coding and this has a huge impact on the performance and the rest of the code.

<% @replies.each do |x| %>

<%= x.content %>

<% end %>

<%= paginate @replies, remote: true %>


text:
Q: Get method do not have time to pull data from the server I have a very basic problem but I don't know the best way to do that. My problem is in on click on the button I want to send data and get the same data from the server. And in some situation, my backend can time to store data in my DB and when I retrieve data I pull without last changes.
  storeCategory() {
 this.categoryService.storeCategory(this.currentFileUpload, this.category).subscribe();
this.adminService.getCategoryFromServer();

Does anyone know have a proposal?

A: You need to retrieve the data when the storing has completed by putting getCategoryFromServer() inside the subscribe() of storeCategory(this.currentFileUpload, this.category):
storeCategory() {

    this.categoryService.storeCategory(this.currentFileUpload, this.category)
    .subscribe(() => {

        this.adminService.getCategoryFromServer();

    });
}

This way you should get the latest changes.


text:
Q: The color from xml is not the same as for a drawable I need a 1px stroke (yes, physical pixel, not dp) around my LinearLayout which I define using an xml shape
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">

    <corners android:radius="1px"/>
    <solid android:color="@color/white"/>
    <stroke android:color="@color/lightgray" android:width="1px" />
</shape>

And in colors.xml
<color name="lightgray">#b8b8b8</color>

On a different element within the layout, I set a 9-patch background image and since it also needs a top border of 1px to be consistent with the layout I defined that in the image with the same color. On testing this, the color around the LinearLayout is different than what I have defined, it's a much lighter color as seen below in the zoomed version of the 1px border.

The first image displays the border colors defined in xml which should be #b8b8b8, the second image is the correct color from the 9-patch drawable. Now, the funny thing is that if have something larger on screen such as a text the color is displayed correctly. How can I make these two consistent? I'm looking to find out by just how much they differ to make my drawable a lighter version. Or some other solution.


text:
Q: How to load listview with images from project resources I am wondering how I can take a image that's in the project settings resources and load this image into a listview without a imagelist. I am getting errors about a imagelist not loading correctly everyone once in a while so I am trying to find a way I can remove the image list without loosing the images I have in the listview.

A: This is the what you can do without implementing some custom list:
private void Form1_Load(object sender, EventArgs e)
{
    ImageList imageList = new ImageList {ImageSize = new Size(200, 200)};
    Image img = new Bitmap(Properties.Resources.Your_Image);
    imageList.Images.Add(img);
    this.listView1.View = View.LargeIcon;
    this.listView1.Items.Add(new ListViewItem { ImageIndex = 0 });
    this.listView1.LargeImageList = imageList;
}

If you need more advanced functionality from your listview take a look at this.


text:
Q: F#, loop control until n-2 I am currently learning functional programming and F#, and I want to do a loop control until n-2. For example:
Given a list of doubles, find the pairwise average,
e.g. pairwiseAverage [1.0; 2.0; 3.0; 4.0; 5.0] will give [1.5; 2.5; 3.5; 4.5]

After doing some experimenting and searching, I have a few ways to do it:
Method 1:
let pairwiseAverage (data: List<double>) =
        [for j in 0 .. data.Length-2 do
            yield (data.[j]+data.[j+1])/2.0]

Method 2:
let pairwiseAverage (data: List<double>) =
        let averageWithNone acc next =
            match acc with
            | (_,None)           -> ([],Some(next))
            | (result,Some prev) -> ((prev+next)/2.0)::result,Some(next))

        let resultTuple = List.fold averageWithNone ([],None) data

        match resultTuple with
        | (x,_) -> List.rev x

Method 3:
let pairwiseAverage (data: List<double>) =
        // Get elements from 1 .. n-1
        let after = List.tail data

        // Get elements from 0 .. n-2
        let before =
            data    |> List.rev
                    |> List.tail
                    |> List.rev

        List.map2 (fun x y -> (x+y)/2.0) before after

I just like to know if there are other ways to approach this problem. Thank you.

A: Using only built-ins:
list |> Seq.windowed 2 |> Seq.map Array.average

Seq.windowed n gives you sliding windows of n elements each.

A: One simple other way is to use Seq.pairwise
something like
list |> Seq.pairwise |> Seq.map (fun (a,b) -> (a+b)/2.0)

A: The approaches suggested above are appropriate for short windows, like the one in the question. For windows with a length greater than 2 one cannot use pairwise. The answer by hlo generalizes to wider windows and is a clean and fast approach if window length is not too large. For very wide windows the code below runs faster, as it only adds one number and subtracts another one from the value obtained for the previous window. Notice that Seq.map2 (and Seq.map) automatically deal with sequences of different lengths.
let movingAverage (n: int) (xs: float List) =
    let init = xs |> (Seq.take n) |> Seq.sum
    let additions = Seq.map2 (fun x y -> x - y) (Seq.skip n xs) xs
    Seq.fold (fun m x -> ((List.head m) + x)::m) [init] additions
    |> List.rev
    |> List.map (fun (x: float) -> x/(float n))
xs = [1.0..1000000.0]
movingAverage 1000 xs
// Real: 00:00:00.265, CPU: 00:00:00.265, GC gen0: 10, gen1: 10, gen2: 0

For comparison, the function above performs the calculation above about 60 times faster than the windowed equivalent:
let windowedAverage (n: int) (xs: float List) =
    xs
    |> Seq.windowed n
    |> Seq.map Array.average
    |> Seq.toList
windowedAverage 1000 xs
// Real: 00:00:15.634, CPU: 00:00:15.500, GC gen0: 74, gen1: 74, gen2: 71

I tried to eliminate List.rev using foldBack but did not succeed.

A: A point-free approach:
let pairwiseAverage = List.pairwise >> List.map ((<||) (+) >> (*) 0.5)

Online Demo
Usually not a better way, but another way regardless... ;-]


text:
Q: Map linked members under condition with parameter I have the following model and dtos:
//Model
    public class User
    {
        //Key
        public int UserId { get; set; }
        public string UserName { get; set; }

        public List<ElementMember> ElementMembers { get; set; }

    }
    public class ElementMember
    {
        //Foreign Key
        public int UserId { get; set; }
        //Foreign Key
        public int ElementId { get; set; }

        public bool IsActiveMember { get; set; }

        public virtual Element Element { get; set; }
        public virtual User User { get; set; }
    }
    public class Element
    {
        //Key
        public int ElementId { get; set; }
        public string ElementName { get; set; }

        public List<ElementMember> ElementMembers { get; set; }

    }

    //DTO
    public class ElementMemberDto
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        //Some properties
    }

    public class ElementDetailsDto
    {
        public int ElementId { get; set; }
        public string ElementName { get; set; }
        public ElementMemberDto ElementMember { get; set; }
    }

In my controller, with the help of Automapper, I would like to Project the User + ElementMember informations in the ElementDetailsDto object only if the ElementMember table has UserId equal to a controller supplied key + IsActiveMember == true. If not, this object in the DTO can remain null.
public bool GetElementDetailsController(int elementId)
    {
        ElementDetailsDto elementDetailsDto = _db.Elements.ProjectTo<ElementDetailsDto>().FirstOrDefault(e => e.ElementId == elementId);

        int userId = GetCurrentUserId();

        elementDetailsDto.ElementMember = _db.ElementMember.ProjectTo<ElementMemberDto>()
            .FirstOrDefault(e => e.UserId == userId && e.ElementId == elementId && e.IsActiveMember == true);
    }

Would be great if could avoid calling twice the database. I am just a bit lost with the advanced functionalities of Automapper.
Regards,

A: I am not sure if it can be done in just one query. But you can get it to work like below:
var mapElementDetails = new MapperConfiguration(cfg =>
    cfg.CreateMap<Element, ElementDetailsDto>());

var mapElementMember = new MapperConfiguration(cfg =>
    cfg.CreateMap<ElementMember, ElementMemberDto>()
    .ForMember(dto => dto.UserName, conf => conf.MapFrom(ol => ol.User.UserName)));

ElementDetailsDto elementDetailsDto = _db.Elements.ProjectTo<ElementDetailsDto>(mapElementDetails).FirstOrDefault(e => e.ElementId == elementId);

elementDetailsDto.ElementMember = _db.ElementMember
    .Where(e => e.UserId == userId && e.ElementId == elementId && e.IsActiveMember == true)
    .ProjectTo<ElementMemberDto>(mapElementMember).FirstOrDefault();


text:
Q: Is the DOM oninput event supported in LWC? This oninput Event documentation explains:

The oninput event occurs when an element gets user input.
This event occurs when the value of an  or  element
is changed.
Tip: This event is similar to the onchange event. The difference is
that the oninput event occurs immediately after the value of an
element has changed, while onchange occurs when the element loses
focus, after the content has been changed. The other difference is
that the onchange event also works on  elements.

I'd like to use that from this LWC code:
<lightning-input-field
    ...
    oninput={handleOnInput}
    ...
></lightning-input-field>

but the handle function never gets called, at least in my code.
Should this work? Is there some LWC documentation that explains which DOM events are supported?

A: As mentioned in the documentation

The native HTML  element provides two events,
input and change. The lightning-input component provides two custom
events, change, and commit.
The component's change event behaves the same as the native input and
change events together. It fires whenever you change the input value,
as the  element's input event does. It also fires when you
finish changing the input, as the  element's change event does.
The component's commit event fires only when you finish changing the
input, which is the same behavior as the HTML  element's change
event.
The component doesn't provide an input event because the behavior is
provided in the change event.
To summarize, the component's change event is equivalent to the input
and change events of the  element. The component's commit event
is equivalent to the change event of the  element.

So you should use onchange for normal input fields and oncommit for search types
<lightning-input label="My input" onchange={handler}></lightning-input>

if the change event doesn't suit the need, we can always switch to a standard HTML input element

    My input

        <input type="text" oninput={handler} class="slds-input" value={value}>


text:
Q: can't mount partition - how can I troubleshoot it? I have an SD card which was used in Raspberry Pi. I want to mount this SD card on a Linux PC to get files from it, but I can't.
When I put the SD card in a card reader, my dmesg says:
  [  114.117896] usb 4-1: new full-speed USB device number 2 using ohci-pci
  [  114.292885] usb 4-1: New USB device found, idVendor=214b, idProduct=1101
  [  114.292897] usb 4-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
  [  114.292904] usb 4-1: Product: USB2.0 Device
  [  114.292910] usb 4-1: Manufacturer: Generic
  [  114.292914] usb 4-1: SerialNumber: 0201202010201000
  [  114.383603] usb-storage 4-1:1.0: USB Mass Storage device detected
  [  114.383803] scsi6 : usb-storage 4-1:1.0
  [  114.383956] usbcore: registered new interface driver usb-storage
  [  115.386965] scsi 6:0:0:0: Direct-Access     USB2.0   CARD-READER      1.01 PQ: 0 ANSI: 2
  [  115.388961] sd 6:0:0:0: Attached scsi generic sg2 type 0
  [  115.409892] sd 6:0:0:0: [sdc] Attached SCSI removable disk
  [  115.471798] sd 6:0:0:0: [sdc] 30679040 512-byte logical blocks: (15.7 GB/14.6 GiB)
  [  115.505782] sdc: detected capacity change from 0 to 15707668480
  [  115.534776]  sdc: sdc1 sdc2 < sdc5 sdc6 > sdc3

The partition table of this card is:
  # parted /dev/sdc
  GNU Parted 3.2
  Using /dev/sdc
  Welcome to GNU Parted! Type 'help' to view a list of commands.
  (parted) print
  Model: USB2.0 CARD-READER (scsi)
  Disk /dev/sdc: 15,7GB
  Sector size (logical/physical): 512B/512B
  Partition Table: msdos
  Disk Flags:

  Number  Start   End     Size    Type      File system  Flags
   1      1049kB  1275MB  1274MB  primary   fat32        lba
   2      1278MB  15,7GB  14,4GB  extended
   5      1279MB  1342MB  62,9MB  logical   fat16        lba
   6      1343MB  15,7GB  14,3GB  logical
   3      15,7GB  15,7GB  33,6MB  primary

When I check this device with fdisk, it says:
  # fdisk /dev/sdc -l

  Disk /dev/sdc: 14.6 GiB, 15707668480 bytes, 30679040 sectors
  Units: sectors of 1 * 512 = 512 bytes
  Sector size (logical/physical): 512 bytes / 512 bytes
  I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disklabel type: dos
  Disk identifier: 0x000daf86

  Device     Boot    Start      End  Sectors  Size Id Type
  /dev/sdc1           2048  2490234  2488187  1.2G  e W95 FAT16 (LBA)
  /dev/sdc2        2496512 30609407 28112896 13.4G 85 Linux extended
  /dev/sdc3       30613504 30679039    65536   32M 83 Linux
  /dev/sdc5        2498560  2621439   122880   60M  c W95 FAT32 (LBA)
  /dev/sdc6        2623488 30607359 27983872 13.4G 83 Linux
  Partition table entries are not in disk order.

It seems that /dev/sdc6 is the biggest partition, so I want to mount it. When I try to mount it, I get this result:
  # mount -v /dev/sdc6 test
  mount: wrong fs type, bad option, bad superblock on /dev/sdc6,
         missing codepage or helper program, or other error

         In some cases useful info is found in syslog - try
         dmesg | tail or so.

Dmesg doesn't say anything when I try to mount /dev/sdc6.
When I check this partition with file command, it says:
    # file -s /dev/sdc6
    /dev/sdc6: data

When I check the filesystem with fsck, I get:
  # LC_ALL=C fsck.ext3 -n /dev/sdc6
  e2fsck 1.43.4 (31-Jan-2017)
  ext2fs_open2: Bad magic number in super-block
  fsck.ext3: Superblock invalid, trying backup blocks...
  root was not cleanly unmounted, check forced.
  Pass 1: Checking inodes, blocks, and sizes
  Pass 2: Checking directory structure
  Pass 3: Checking directory connectivity
  Pass 4: Checking reference counts
  Pass 5: Checking group summary information
  Free blocks count wrong for group #0 (4245, counted=11608).
  Fix? no

  Free blocks count wrong for group #1 (1373, counted=707).
  Fix? no

  Free blocks count wrong for group #2 (1699, counted=1880).
  Fix? no

  (...)

  Inode bitmap differences:  -(57345--131072) -172034 -172037 -(172042--172043) -172045 -172047 -172049 -172053 -172057 -172059 -172062 -172065 (...)
  Fix? no

  root: ********** WARNING: Filesystem still has errors **********

  root: 91692/876544 files (0.8% non-contiguous), 1413337/3497984 blocks

I understand that due to some unknown reason Linux can't mount this filesystem. I would like to know why - is filesystem broken, or is there some other reason? And I would like either to mount this filesystem or somehow recover its files.
What should I do now to troubleshoot this problem?
EDIT: I want to thank everybody for help! Finally I found - using fsck - that the partition does contain Linux ext filesystem, but the filesystem is broken and this is why I could not mount it. I did a backup of the card (with "cat /dev/sdc | gzip > mybackup") and then checked if the device contains bad blocks. It does not contain any bad blocks (maybe the filesystem on the SD card was broken by usind it with a broken SD card reader?), so I just fixed the filesystem with fsck, put the card in the Raspberry Pi and then it booted without problems.

A: According to the posted fsck output, there is hope that some data might be recovered.
I would recommend:

*

*make a dd copy of the filesystem to a disk file (e.g. fdsump.orig). If it fails, try ddrescue. Make sure you have enough free space before you begin.

*Do not work directly on this file, but create a new copy (e.g. cp fsdump.orig fsdump), so you can always return to this step and start again.

*with mount -o loop create a device from the fsdump data file (e.g. /dev/loop1)

*try fsck.ext3 /dev/loop1 until there will be no errors. The more passes will be needed, the bigger is the damage.

*mount the /dev/loop1 to a directory. Copy all files to a  safe location. (Use cp -a or rsync to preserve file attributes). Any of them may be corrupted, truncated, etc.

*You may now umount the loop filesystem.

See man pages of the mentioned utilities for details.

A: You might use file(1) as file -s /dev/sdc6 this would read some bytes from the block device and guess what is there.
If nothing is recognized, you are in trouble and you might have lost your data; to do anything to recover it, you should know a priori what file system was there.
If some file system is recognized, you could try to use mount(8) with an explicit -t type

Partition table entries are not in disk order

This smells not very good. Perhaps you'll need to repartition entirely your disk  (but backup its data before); it looks that you have two partitions overlapping (sdc2 and sdc6)
Since you are running on some other Linux PC, you could copy the data from the SD card to the PC (into some file), perhaps using dd(1)
dd if=/dev/sdc6 of=$HOME/diskdata bs=4k

BTW, do check with dmesg after that command that the copy went well.
You could even copy with dd the entire SD card.
Then you might spend hours (or months) of work to try to decipher the mess in that $HOME/diskdata file on your Linux PC. You could use debugfs(8) for that purpose, if you believe the original file system was ext3 or ext4
SD cards are fragile devices and they wear out quickly. I guess yours is physically broken. Prepare yourself to some definitive data loss.


text:
Q: JavaScript: I need to iterate over each character in `strArray` and see if it exists in `charArray` I am given a string and an array of single character strings as an argument. I need to return the shortest substring that can be found in the given string that contains every character in the array.
I am assuming that all characters are lower case and that the substring will be at least two characters long.
This is how I have it set up:
const solve = (strArg, charArray) => {
  let result = '';
  const strArray = strArg.split('');
  return;
}

solve("environmental earth science", ["n","e","i","m"]);

I want to loop over the strArg and say does this letter exist in the charArray, but I want to use an ES6 array helper method and I have looked at filter(), but if I look at how T.J Crowder defines the use of filter(), that is more for creating a new array.
So then I have also looked at the for..of loop, but I am unclear as to whether I am applying it wrong or the for..of is not the best for the job. I need to iterate over each character in strArray and see if it exists in charArray.

A: A brute-force solution would be to start at each index of the input string, then increment indicies until all required characters have been found. Do this starting at index 0, then at index 1, etc.

const solve = (str, charArray) => {
  let bestStr = str;
  for (let i = 0; i < str.length; i++) {
    const chars = new Set(charArray);
    for (let j = i; j < str.length; j++) {
      chars.delete(str[j]);
      const thisLen = j - i + 1;
      if (chars.size === 0 && bestStr.length > thisLen) {
        bestStr = str.slice(i, j + 1);
        break;
      }
    }
  }
  return bestStr;
}

console.log(solve("environmental earth science", ["n","e","i","m"]));

I don't think filter is very useful here, because constructing an intermediate array doesn't lead to accomplishing anything useful as far as I can see. for..of, while it looks cleaner, doesn't keep track of indicies as well as a plain for loop.