text:
Q: Display random unique possibilities from rows from a table I want to display random different possibilities from a specific data table. I am trying to grab random unique (cannot be used more than once) IDs from column "A" (about 100 IDs in this field), and making sure criteria is met from columns "B" and "C"(Usually only whole number or .5 decimal numbers).
Example list below, but very shortened format. I want to have total number (column "C") equal 19.5 or 20, and have:

*

*Red from column "B" to be > 5 in column "C".

*Green from column "B" have at least 2 in column "C"

*Yellow from column "C" cannot be more than 7 in column "C"

I want it so that every time I press a button, it will have another random possibility to fit specific criteria.

ID
Colour
Number

111
Red
1.5

112
Blue
2

113
Green
1

114
Blue
1.5

115
Yellow
2

116
Blue
1

I have been trying to freestyle with the little knowledge that I have and have the below so far. I am not sure if I am going in the right direction.
Sub RandomPossibilities()

Dim NoOfIDs As Long
Dim RandomNumber As Integer
Dim IDs(), Colour() As String
Dim i As Byte
Dim CellsOut As Long
Dim ArI As Byte
Dim RedCount, BlueCount, YellowCount, GreenCount, TotalCount As Variant

Application.ScreenUpdating = False
RedCount = 0
BlueCount = 0
GreenCount = 0
YellowCount = 0
TotalCount = 0
CellsOut = 6
ReDim IDs(1 To 20)
ReDim Colour(1 To 20)
NoOfIDs = Application.CountA(Range("A:A")) - 1

i = 1
Do Until (TotalCount = 20 Or TotalCount = 19.5) And RedCount >= 5 And GreenCount >= 2 And YellowCount <= 7

RandomNo:
    RandomNumber = Application.RandBetween(2, NoOfIDs + 1)
    For ArI = LBound(IDs) To UBound(IDs)
        If IDs(ArI) = Cells(RandomNumber, 1).Value Then
            GoTo RandomNo
        End If
        If Cells(RandomNumber, 2).Value = "Not Available"
            GoTo RandomNo
        End If
     Next ArI

 IDs(i) = Cells(RandomNumber, 1).Value
 Colour(i) = Cells(RandomNumber, 2).Value

 If Cells(RandomNumber, 2).Value = "Red" Then
     RedCount = RedCount + Cells(RandomNumber, 3).Value
 ElseIf Cells(RandomNumber, 2).Value = "Yellow" Then
     YellowCount = YellowCount + Cells(RandomNumber, 3).Value
 ElseIf Cells(RandomNumber, 2).Value = "Blue" Then
     BlueCount = BlueCount + Cells(RandomNumber, 3).Value
 ElseIf Cells(RandomNumber, 2).Value = "Green" Then
     GreenCount = GreenCount + Cells(RandomNumber, 3).Value
 End If

 If TotalCount = 20 Or TotalCount = 19.5 Then
    If RedCount >= 5 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
    End If
    If GreenCount >= 2 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
    End If
    If YellowCount <= 7 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
    End If
 End If

 If TotalCount >= 9 Then
    If RedCount >= 5 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
    End If
 If GreenCount >=2 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
       TotalCount = 0
 End If
 If YellowCount <=7 2 Then
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
      YellowCount = 0
       TotalCount = 0
    End If
       i = 0
       RedCount = 0
       BlueCount = 0
       GreenCount = 0
       YellowCount = 0
    TotalCount = 0
 End If
    i = i + 1

TotalCount = GreenCount + BlueCount + YellowCount + RedCount

Loop

For ArI = LBound(IDs) To UBound(IDs)
    Cells(CellsOut + 2, 6) = IDs(ArI)
    Cells(CellsOut + 2, 7) = Colour(ArI)
    CellsOut = CellsOut + 1
Next ArI
Cells(8, 9) = YellowCount
Cells(9, 9) = BlueCount
Cells(10, 9) = GreenCount
Cells(11, 9) = RedCount
Cells(12, 9) = TotalCount
Application.ScreenUpdating = True
End Sub


text:
Q: How do I refactor this code by using any type of loops? everyone. I am new to the programming and I can't figure out how to refactor this code using loops, so the panels would be switching exactly like in the slider by pressing right arrow key(I commented out my attempt).
document.addEventListener("keydown", (e) => {
  if (e.key === "ArrowRight") {
    if (panels[0].classList.contains("active")) {
      panels[0].classList.remove("active");
      panels[1].classList.add("active");
    } else if (panels[1].classList.contains("active")) {
      panels[1].classList.remove("active");
      panels[2].classList.add("active");
    } else if (panels[2].classList.contains("active")) {
      panels[2].classList.remove("active");
      panels[3].classList.add("active");
    } else if (panels[3].classList.contains("active")) {
      panels[3].classList.remove("active");
      panels[4].classList.add("active");
    } else if (panels[4].classList.contains("active")) {
      panels[4].classList.remove("active");
      panels[0].classList.add("active");
    }
    //     for (let i = 0; i < panels.length; i++) {
    //       if (panels[i].classList.contains("active")) {
    //         panels[i].classList.remove("active");
    //         panels[++i].classList.add("active");
    //       }
    //       if (i > panels.length - 1) {
    //         panels[panels.length - 1].classList.remove("active");
    //         panels[0].classList.add("active");
    //       }
    //     }
    //   }
  }
});

A: you can do something like this :
document.addEventListener("keydown", (e) => {
  if (e.key === "ArrowRight") {
    for (let i = 0; i < 5; i++) {
      let j = (i + 1) % 5;
      if (panels[i].classList.contains("active")) {
        panels[i].classList.remove("active");
        panels[j].classList.add("active");
        break;
      }
    }
  }
});

This code uses modulo, so that in the last loop, the second number eqauls to
5%5 = 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Select unmatched records from two tables with a filter on second table I have 2 mysql tables a and b. I need to show all records in a that are not in b using a common column 'ID'. Normally this is pretty straight forward but my problem here is this: I need to put a where clause on table b because I'm not interested in all unmatched records just the ones that meet the table 2 where clause criterion:
SELECT a.ID, a.Description
FROM a
LEFT JOIN b ON a.ID = b.ID
WHERE a.Inactive = 0
AND b.Room = '101'
AND b.ID Is Null

This returns nothing. However if I remove the AND b.Room = '101' part, it displays the expected results. But I need that condition because I need only unmatched records specific to a 'room' and not all unmatched records

A: Move the conditions involving table b from WHERE to ON clause:
SELECT a.ID, a.Description
FROM a
LEFT JOIN b ON a.ID = b.ID AND b.Room = '101'
WHERE a.Inactive = 0
AND b.ID Is Null

It'll find rows where a does not have a match in b (id matches and room number = 101).


text:
Q: Solving differential equation for table in python So, I have a list of cells and I need to solve DE for each of them. Problem is, that equations depend on each other, because for diff_u and diff_s functions I need to check 6 neighbours values.
da_idt = 1/tau_a*(P_a*np.heaviside(a[i] - a_a, 1) - lambda_a*a[i] + G*np.heaviside(h(i,t, array) - h_1, 1)*(1 - np.heaviside(u[i] - u_1, 1)) + S*np.heaviside(s[i] - s_1, 1))*(1 - np.heaviside(u[i] - u_1, 1))

du_idt = 1/tau_u*(P_u*np.heaviside(a[i] - a_u, 1) - lambda_u*u[i] + D_u*diff_u(u, neighbour, i))

ds_idt = 1/tau_s*(P_s*np.heaviside(a[i] - a_a, 1) - lambda_s*s[i] + D_s*diff_s(s, neighbour, i))

def diff_u(u: list, neighbour: list, i: int) -> float:
    return 6/len(neighbour[i])*D_u*sum(u[neigh] - u[i] for neigh in neighbour[i])

I have this code in Wolfram Mathematica. There u can simply enter table of equations and give it to NDSolve
sol=First@NDSolve[eqs~Join~incond/.parval,Flatten@Table[{a[i][t],u[i][t],s[i][t]},{i,Length@cells}],{t,0,300}]

But in odeint or solve_ivp I need to create a function, that gives back [da_idt, du_idt, ds_idt] and if I do that, its solves for each i cell from 0 to 300 seconds and that way neighbours still remain zero values for whole time, before I reach neighbour cell in cycle.
How can I solve this? If there are more convenient functions than odeint and solve_ivp I'm open to change it.
Ty in advance


text:
Q: Finding last empty row not working for one sheet only My mind is broken. I have spent days trying to figure out why this is happening:
After a user form is filled out there is a button to populate a corresponding spreadsheet. The sheet is determined by the first combo box (catSel.value). To find the last empty row I use the rngSrch portion of the code below.
On one sheet If Application.WorksheetFunction.CountA(Acell.EntireRow) = 0 comes back as false and firstBlankRow = Acell.row is not run.
I have tried deleting the sheet and creating a new one(copying one that works), changing the name and commenting out/changing the code.
Any ideas why this is happening? Also ws.Range("A" & firstBlankRow) = Me.equipId.value is coming back with Run-time Error '1004': method 'Range' of object '_worksheet' failed
Private Sub AddCont_Click()

Dim firstBlankRow As Long
Dim ws As Worksheet
Dim srchRng As Range
Dim Acell As Range

Set ws = Worksheets(CatSel.value)

On Error GoTo Err

With ws
    Set srchRng = .UsedRange.Columns(1).Find("")
    If Not srchRng Is Nothing Then
        Set srchRng =.UsedRange.Columns(1).SpecialCells(xlCellTypeBlanks)
        For Each Acell In srchRng
            If Application.WorksheetFunction.CountA(Acell.EntireRow) = 0     Then
                firstBlankRow = Acell.row
                Exit For

            End If

        Next
    Else
        If Application.WorksheetFunction.CountA(Cells(.Rows.Count, 1).EntireRow) = 0 Then
            MsgBox "Please start a new sheet"
        Else
            firstBlankRow = .UsedRange.SpecialCells(xlCellTypeBlanks).row + 1

        End If
    End If

'Equipment ID
    ws.Range("A" & firstBlankRow) = Me.equipId.value
'Parent or Next Level
    ws.Range("B" & firstBlankRow) = Me.NextLev.value
'Keyword
    ws.Range("C" & firstBlankRow) = Me.KeySel.value
'Cost Center
    ws.Range("E" & firstBlankRow) = Me.CostSel.value
'Department
    ws.Range("F" & firstBlankRow) = Me.DepartSel.value
'Location 1
    ws.Range("G" & firstBlankRow) = Me.Loc1.value
'Location 2
    ws.Range("H" & firstBlankRow) = Me.Loc2.value
'Location 3
    ws.Range("I" & firstBlankRow) = Me.Loc3.value
'Location 4
    ws.Range("J" & firstBlankRow) = Me.Loc4.value
'Beginning of specs
'L5
    ws.Range("L" & firstBlankRow) = Me.L3Sel.value
'M5
    ws.Range("M" & firstBlankRow) = Me.M3Sel.value
'N5
    ws.Range("N" & firstBlankRow) = Me.N3sel.value
'O5
    ws.Range("O" & firstBlankRow) = Me.O3Sel.value
'P5
    ws.Range("P" & firstBlankRow) = Me.P3Sel.value
'Q5
    ws.Range("Q" & firstBlankRow) = Me.Q3Sel.value
'R5
    ws.Range("R" & firstBlankRow) = Me.R3Sel.value
'S5
    ws.Range("S" & firstBlankRow) = Me.S3Sel.value
'T5
    ws.Range("T" & firstBlankRow) = Me.T3Sel.value
'U5
    ws.Range("U" & firstBlankRow) = Me.U3Sel.value

    MsgBox ("successfully Added")

End With

Err: MsgBox ("something went wrong")

End Sub

A: I think in this part of the code
Set srchRng = .UsedRange.Columns(1).Find("")
If Not srchRng Is Nothing Then
    Set srchRng =.UsedRange.Columns(1).SpecialCells(xlCellTypeBlanks)
    For Each Acell In srchRng
        If Application.WorksheetFunction.CountA(Acell.EntireRow) = 0     Then
            firstBlankRow = Acell.row
            Exit For

        End If

    Next
Else
    If Application.WorksheetFunction.CountA(Cells(.Rows.Count, 1).EntireRow) = 0 Then
        MsgBox "Please start a new sheet"
    Else
        firstBlankRow = .UsedRange.SpecialCells(xlCellTypeBlanks).row + 1

    End If
End If

you are trying to find the first blank row, so that you can insert a new record.
If so, I suggest you replace that code with:
If IsEmpty(.Cells(.Rows.Count, 1)) Then
    firstBlankRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
Else
    MsgBox "Please start a new sheet"
    Exit Sub
End If

That code will look for the last non-empty cell in column A and set the firstBlankRow variable to point to the row after it.

If your records sometimes have an empty value in column A, but you have another column that can be guaranteed to always have a value, just change the above code to refer to that column instead of to column 1.  E.g. (assuming column D is always populated):
If IsEmpty(.Cells(.Rows.Count, "D")) Then
    firstBlankRow = .Cells(.Rows.Count, "D").End(xlUp).Row + 1
Else
    MsgBox "Please start a new sheet"
    Exit Sub
End If

If you have records where no column is guaranteed to be non-empty, perhaps this code will work:
firstBlankRow = .Rows.Count + 1
If IsEmpty(.Cells(.Rows.Count, "A")) Then
    For firstBlankRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 To .Rows.Count
        If Application.WorksheetFunction.CountA(.Rows(firstBlankRow)) = 0 Then
            Exit For
        End If
    Next
End If
If firstBlankRow = .Rows.Count + 1 Then
    MsgBox "Please start a new sheet"
    Exit Sub
End If


text:
Q: how to check how many token been sold for my Smart contract I want to create a smart contract and launch it for ICO. I also create a website where people can buy my token. I want know how to check how many token been sold (live)? so i can create a live bar counter to show how many percentages of the token already been sold.
Or is there a way i can monitor the token sale process in the smart contract?

A: A token contract is no different than any other smart contract. There are no special built in Solidity features or logic associated with them. They are just regular smart contracts that follow a specification.
So, if you want access to the number of tokens sold, you code that into your contract. While tokens sold is not part of the standard ERC20/ERC721 interface, nothing prevents you from adding a constant function to retrieve this information. In fact, if you're using the basic Zeppelin Crowdsale contract, you can just calculate it using the public state variables weiRaised / rate (Chances are you should be creating your own Crowdsale subcontract, so it's better to add the functionality you want there).

A: We can use the Etherscan Developer API to review transactions against a given contract address and find out the total supply or number of items available for sale.
There is a lot you can do with the Etherscan Developer API. For example, here's one URL that pulls data from Ethereum Mainnet -> Etherscan -> JSON parser -> Shields.io and renders it as an image to calculate the number of Su Squares remaining for sale:

Source: https://img.shields.io/badge/dynamic/json.svg?label=Su+Squares+available&url=https%3A%2F%2Fapi.etherscan.io%2Fapi%3Fmodule%3Daccount%26action%3Dtokenbalance%26contractaddress%3D0xE9e3F9cfc1A64DFca53614a0182CFAD56c10624F%26address%3D0xE9e3F9cfc1A64DFca53614a0182CFAD56c10624F%26tag%3Dlatest%26apikey%3DYourApiKeyToken&query=%24.result
^ I don't know if SO is going to cache the image here. But that URL is a live URL which pulls the number of Su Squares available hot off the blockchain.


text:
Q: Scala streams with array/vector performance characteristics I am taking a class on algorithms, and I'm solving a few exercises on dynamic programming right now.
I looked up how I would solve some of the problems in a functional way in Scala, and from what I read from the scaladoc on the standard library, I found stream, view, and iterator as something that might be plausible.
But I would be using a lot of random access, so Streams would be extremely inefficient since singly linked lists take O(n) time for indexed accesses. Views, as far as I know, can't be used to build something infinite, and iterators, which can be infinite, don't store any values inside themselves.
And then, I found this from the haskell wiki, and this is exactly what I need, except that it is in Haskell:
import Data.Array
import Control.Monad(guard,mplus)

buy n = r!n
    where r = listArray (0,n) (Just (0,0,0) : map f [1..n])
          f i = do (x,y,z) <- attempt (i-6)
                   return (x+1,y,z)
                `mplus`
                do (x,y,z) <- attempt (i-9)
                   return (x,y+1,z)
                `mplus`
                do (x,y,z) <- attempt (i-20)
                   return (x,y,z+1)
          attempt x = guard (x>=0) >> r!x

What would be a good way to translate this into Scala? I have a feeling that I would need to import an external library (like scalaz) (but I won't be able to turn in the assignment) or write a new Stream implementation based on Scala Array or Vector.
Thanks in advance!

A:
Views, as far as I know, can't be used to build something infinite, and iterators, which can be infinite, don't store any values inside themselves.

The Haskell solution isn't infinite either.

What would be a good way to translate this into Scala?

I'd start with defining
class Lazy[A](calculation: => A) {
  lazy val value: A = calculation
}

=> A is a by-name parameter, which means when you write val x = Lazy { ... }, the code inside ... isn't executed immediately; instead it will be when value is accessed.
Then use Array[Lazy[A]] (Array[Lazy[(Int, Int, Int)]] for this specific function).


text:
Q: Gradle build fails after updating to Android Gradle plugin 3.2 I'm currently trying to update all of the old dependencies on one of our company's apps but struggle with updating the Android Gradle plugin. Version 3.1.4 is building the app perfectly fine, but after updating to 3.2.0 or 3.2.1 the build fails.
Since neither I nor my co-workers were able to find a solution for this problem, I try to find some help here.
I'm on Android Studio 3.2.1, Android Gradle plugin on 3.2.1, Gradle version 4.10.3.
Build output (starting at the error because stackoverflow won't let me write more than 30000 characters):
ferneding_david@PWAC0051:~/Code/MobileAppDebug/ufho.mobile$ ./gradlew clean :lib:assembleDebug :app:assembleVwsDebug
[...]
> Task :app:transformClassesWithDexBuilderForVwsDebug
com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/ferneding_david/Code/MobileAppDebug/ufho.mobile/ufho.lib/app/build/intermediates/intermediate-jars/debug/classes.jar
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
        at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
        at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:720)
        at com.android.ide.common.internal.WaitableExecutor.waitForTasksWithQuickFail(WaitableExecutor.java:146)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.transform(DexArchiveBuilderTransform.java:405)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
        at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:301)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:293)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
        at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
        at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:301)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:293)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
        at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:74)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph.execute(DefaultTaskExecutionGraph.java:143)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:40)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:40)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:24)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:46)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:49)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:40)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:33)
        at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:355)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:301)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:293)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:219)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:124)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:154)
        at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:50)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:301)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:293)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:47)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:44)
        at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:79)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:81)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
        at java.lang.Thread.run(Thread.java:748)
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/ferneding_david/Code/MobileAppDebug/ufho.mobile/ufho.lib/app/build/intermediates/intermediate-jars/debug/classes.jar
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:900)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.lambda$convertToDexArchive$6(DexArchiveBuilderTransform.java:825)
        at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
        at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
        at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
        at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
        at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.
        at com.android.builder.dexing.D8DexArchiveBuilder.getExceptionToRethrow(D8DexArchiveBuilder.java:124)
        at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:101)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:895)
        ... 6 more
Caused by: com.android.tools.r8.errors.Unreachable: Unexpected type adjustment from java.io.Serializable to int
        at com.android.tools.r8.ir.desugar.LambdaMainMethodSourceCode.adjustType(LambdaMainMethodSourceCode.java:378)
        at com.android.tools.r8.ir.desugar.LambdaMainMethodSourceCode.prepareReturnValue(LambdaMainMethodSourceCode.java:288)
        at com.android.tools.r8.ir.desugar.LambdaMainMethodSourceCode.prepareInstructions(LambdaMainMethodSourceCode.java:276)
        at com.android.tools.r8.ir.synthetic.SyntheticSourceCode.setUp(SyntheticSourceCode.java:152)
        at com.android.tools.r8.ir.conversion.IRBuilder.build(IRBuilder.java:365)
        at com.android.tools.r8.ir.synthetic.SynthesizedCode.buildIR(SynthesizedCode.java:43)
        at com.android.tools.r8.graph.DexEncodedMethod.buildIR(DexEncodedMethod.java:243)
        at com.android.tools.r8.ir.conversion.IRConverter.rewriteCode(IRConverter.java:631)
        at com.android.tools.r8.ir.conversion.IRConverter.processMethod(IRConverter.java:598)
        at com.android.tools.r8.ir.conversion.IRConverter.optimizeSynthesizedMethod(IRConverter.java:581)
        at com.android.tools.r8.graph.DexClass.forEachMethodThrowing(DexClass.java:146)
        at com.android.tools.r8.ir.conversion.IRConverter.optimizeSynthesizedClass(IRConverter.java:573)
        at com.android.tools.r8.ir.desugar.LambdaRewriter.synthesizeLambdaClasses(LambdaRewriter.java:177)
        at com.android.tools.r8.ir.conversion.IRConverter.synthesizeLambdaClasses(IRConverter.java:247)
        at com.android.tools.r8.ir.conversion.IRConverter.convertToDex(IRConverter.java:275)
        at com.android.tools.r8.D8.optimize(D8.java:203)
        at com.android.tools.r8.D8.run(D8.java:163)
        at com.android.tools.r8.D8.lambda$run$1(D8.java:93)
        at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:55)
        at com.android.tools.r8.utils.ExceptionUtils.withD8CompilationHandler(ExceptionUtils.java:43)
        at com.android.tools.r8.D8.run(D8.java:90)
        at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:99)
        ... 7 more

> Task :app:transformClassesWithDexBuilderForVwsDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithDexBuilderForVwsDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/ferneding_david/Code/MobileAppDebug/ufho.mobile/ufho.lib/app/build/intermediates/intermediate-jars/debug/classes.jar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.10.3/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 1m 44s
47 actionable tasks: 43 executed, 4 up-to-date

EDIT:
To clarify: I deleted all my gradle caches before building and made sure that my gradle-wrapper.properties files all reference Gradle 4.10.3
All gradle files were re-downloaded at the start of the build, I just had to leave that part out in the log I posted, because otherwise the question would be too long to post.


text:
Q: If $x=2+i$, $gcd(a,b,c)=1$, and $ax^4+bx^3+cx^2+bx+a=0$, then what is $|c|$?
Suppose
  $$a(2+i)^4 + b(2+i)^3 + c(2+i)^2 + b(2+i) + a = 0,$$
  where $a,b,c$ are integers whose greatest common divisor is $1$.
  Determine $|c|$.

So I first simplified the exponents and combined like terms.
I received $$a(-6+24i)+b(4+12i)+c(3+4i)=0.$$
I don't really know how to progress. What is the answer $|c|$?

A: We use your calculation. Note that as the other answers show there would have been nicer ways to proceed.
From the equation that you obtained we get $-6a+4b+3c=0$ and $24a+12b+4c=0$. Divide the second expression through by $4$, and add the first expression. We get $7b+4c=0$.
Thus $4c=-7b$ and therefore $c=7k$, $b=4k$ for some integer $k$. Substituting in the first equation we get $6a=5k$. It follows that $k=6m$ for some integer $m$. Thus $c=42m$, $b=-24m$, and $a=5m$.
By relative primality we get $|m|=1$, and therefore $|c|=42$.

A: Hint: since $a,b,c \in \mathbb Z$ the conjugate of any root will also be a root.
Because the coefficients are symmetric, there is another easy way (applicable to such symmetric polynomials) to obtain another root. I think you wouldn't have been given this question without knowing, or having in your notes, how that works in the case where roots are rational. It works for complex roots too (easy to prove).
That gets you all the roots easily and you should be able to find an efficient way of finding the polynomial.
You are being asked to notice the features of the polynomial you are given and use them in an unusual situation. Give it a go and see what you come up with.

A: A polynomial of this symmetric form can be reduced in degree by the following trick. Divide by $x^2$ and get:
$\begin{align}
a (x^2 + x^{-2}) + b (x + x^{-1}) + c
  &= a (x + 1/x)^2 + b (x + 1/x) + c - 2 a
\end{align}$
The substitution $y = x + 1/x$ finishes this off.
This works because the powers of $x + 1/x$ turn out to be combinations of $x^k + x^{-k}$.


text:
Q: Adding and removing class from buttons in ajax script I have the following jQuery/ajax script:
jQuery("input.button").click(function(){
   jQuery.ajax({
      url: 'addfav.php',
      type: 'POST',
      data: {'id':jQuery(this).closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        jQuery(this).removeClass('before');
        jQuery(this).addClass('after');
        jQuery(this).attr('disabled', 'disabled');
      },
      error: function() {
        jQuery('#error').html('
Error! Unable to add food item.
');
      }
    });
});

Which handles clicking on buttons such as these:

<input type="button" class="button before"/>

<input type="button" class="button before"/>

The adding and removing of classes to whichever but is clicked does not work however.  It works for a single button with an ID, i.e.:
jQuery("input#button1").click(function(){

But not when I use classes.  What changes do I need to make to get this script to add or remove classes to whichever button is clicked when I just use a class for the button?

A: You should cache the selector, try the following:
jQuery("input.button").click(function(){
   var $this = $(this);
   jQuery.ajax({
      url: 'addfav.php',
      type: 'POST',
      data: {'id': $this.closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        $this.removeClass('before');
        $this.addClass('after');
        $this.attr('disabled', 'disabled');
      },
      error: function() {
        jQuery('#error').html('
Error! Unable to add food item.
');
      }
    });
});


text:
Q: Exponential family forms a group Let $X$ be a Banach space and $T ∈ B(X)$. Let $f_t(ζ) = e^{-tζ}$ , with $f_t
: Ω → \mathbb{C}$ and $t ∈ \mathbb{R}$.
Define the exponential family
$e^{−tT} = f_t(T)$.
Show that $e^{−tT}$ forms a group. That is, $e^{−(t+s)T} = e^{−tT} e^{−sT}$ for all $s, t ∈ \mathbb{R}$.
I don't really understand what to do, actually..

A: From the way you state you state your problem, it looks like you are thinking of $e^{-tT}$ as being defined by holomorphic functional calculus (By the way, do you want $\Omega = \mathbb{C}$? Because your functions $f_t$ are entire...). If you already understand this tool, then the conclusion you want holds because, at the level of functions, $f_t f_s = f_{t+s}$, and holomorphic functional calculus is a homomorphism, i.e. $(fg)(T) = f(T)g(T)$.
On the other hand, you can also define $e^{-tT}$ using the absolutely convergent series $\sum_{n=0}^\infty (-tT)^n/n!$. If that is the route you are taking, then you should just follow the proof that $e^{s+t} = e^s e^t$ in the single-variable context. It goes through more or less unchanged.


text:
Q: Silverlight Memory usage I'm designing a screen and I take data from a web service.
I was going to design the screen so that it called the web service everytime it needed data.
However I came to the realization that there are only 6 possible combinations returned from the web service.  So why don't I just keep the data in memory and use that instead.
Then I begin to wonder... how much memory is this really going to take up on the client?
Any idea how I can figure that out?
ie my array of custom objects is taking up 356k

A: You can use CLR Profiler to see how much memory a type and all the objects it references is taking up on the heap (Silverlight is CoreCLR):
David Broman's CLR Profiling API Blog: CLRProfiler V4 Released


text:
Q: I've been trying to fetch the data from a URL by using UrlFetchApp in appscript but in my case it returns empty values, How to solve this problem? Actually,  I'm trying to fetch the data from this First URL and when I browse it in chrome at the very first time it returns an array having key's with blank values but when I load the Index Page of this website and then reload the first URL then it returns an array having key's with their values and from this, I'm assuming that the first URL depends on cookies and only the index page creates the cookies and when I try to get the data from First URL by using UrlFetchApp method in app-script it returns only keys with empty values like it happens when you open the first url at the first time in your browser without having cookies in your browser, It seems like there is a problem with the cookies of this website and it is stopping me to fetch the data from the First URL so in my case, the UrlFetchApp doesn't work or I'm doing it wrong and if there is anyone can tell me how should I do it then this would be a great help.
Mentioned below is the code I'm using to fetch the data.
  function ESTIMATED_SALES() {
    var link = "https://fbatoolkit.com/estimate_ajax?category=UGV0IFN1cHBsaWVz&rank=6000";
    const respond = UrlFetchApp.fetch(link).getContentText();
  Logger.log(respond);
}

And here is the execution log of my code
12:26:58 AM Notice  Execution started
12:26:57 AM Info    {"sales_per_day_30day_avg": "", "tg_flash": null, "sales_per_day_1day_avg": ""}
12:26:59 AM Notice  Execution completed

OR if there is any way to get the data directly from the index page by posting payload data into the specific input field of the index page and get the response back?


text:
Q: Cannot read property 'setState' of undefined I'm trying to use flickr api to fetch public photos and create an image carousel with them but seems it does not want to get photos in the beginning. Since I'm new to React, it is really hard to figure out what I'm doing wrong here so any kinda help will be appreciated.. Thank you.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import _ from 'lodash';

import Button from './components/button';

const urlArr = [];
const apiKey = "YOUR_API";
const userId = "YOUR_ID";
const url = `https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=${apiKey}&user_id=${userId}&format=json&nojsoncallback=1`;

class App extends Component {
  constructor(props) {
    super(props);

    this.state = { urlArr: [] };

    axios.get(url)
    .then(function(photoData) {
      _.forEach(photoData.data.photos.photo, (photo) => {
        // this.setState({ urlArr: `https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg` });
        urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`);
      });
      this.setState({ urlArr });
    });
  }

  render() {
    return (
      <div>
        <Button />
      </div>
    );
  }
};

ReactDOM.render(<App/>, document.querySelector('.container'));

Code above returns 'TypeError: Cannot read property 'setState' of undefined' and I'm not quite sure what that means..

A: You're calling the setState() in a callback function of a Promise.
The error is because the this is not the React Component.
You should use an arrow function or bind the React Component instance to your callback function.
For example:
axios.get(url)
.then((photoData) => {
  _.forEach(photoData.data.photos.photo, (photo) => {
    // this.setState({ urlArr: `https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg` });
    urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`);
  });
  this.setState({ urlArr });
});

Or:
axios.get(url)
.then(function(photoData) {
  _.forEach(photoData.data.photos.photo, (photo) => {
    // this.setState({ urlArr: `https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg` });
    urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`);
  });
  this.setState({ urlArr });
}.bind(this));


text:
Q: Make CPPickerView scroll faster with large data sources I'm using CPPickerView in my app to accomplish a horizontal UIPickerView, and it works great, but with large data sources (dozens of items) it scrolls very slowly which makes navigation before (especially considering a normal UIPickerView can go very fast through them).
I don't mean performance-wise, by the way, I mean the view decelerates very quickly, making traversal difficult.
It's just a subclass of UIScrollView with pagingEnabled set to YES. What can I do?

A: I looked in the source, and it seems CPPickerView is using a scroll view. Scroll views have a decelerationRate property. Play with that and see which value makes for the best result.

A: Don't fill CPPickerView with all data.
For example fill with first 20 items and if it reaches to the end add another 20.

A: As mentioned above you can use the decelerationRate property, setting it to UIScrollViewDecelerationRateNormal might help.
scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;

If that still doesn't solve your problem you could also buffer your inputs into the scroll. See this:
Advanced scrollview techniques

A: Creator of CPPickerView here - I've recently updated CPPickerView to add an allowSlowDeceleration property, which should do what you're looking for. Check out the latest code on Github, or Cocoapods version 1.2.0.
For the purposes of documentation, here's how the solution works. Like you mentioned CPPickerView just a scrollview with pagingEnabled set to YES, so the solution I found was to disable paging when the user scrolls with enough velocity.
UIScrollViewDelegate has an optional method scrollViewWillEndDragging:withVelocity:targetContentOffset:, which is called when the user's finger is lifted after swiping/scrolling on the scrollview, and it's still called even when paging is enabled. Based on that value you can tell if the user was trying to scroll quickly through items, or just move one or two items.
I played around with the CPPickerViews in the Demo project, and found that a velocity of about 2.9f seems to be about the normal "fast swipe" threshold. So if the velocity is greater than this threshold (which I defined as kCPPickerDecelerationThreshold in CPPickerView.m) and allowSlowDeceleration is set to YES, CPPickerView now sets pagingEnabled to NO before the deceleration starts. This allows the picker to "coast" and decelerate like a normal scrollview.
It then catches the end of the deceleration, OR the user touching to stop the scroll, by the call to the scrollViewDidEndDecelerating: delegate method. The current item is determined (based on the offset of the scrollview), and then if the scrollview's pagingEnabled property is set to NO a call to the private method scrollToIndex:animated: is made with animation set to YES. This scrolls the CPPickerView to the current item, which necessary as it's unlikely the coasting scroll ended right on a page boundary.
Finally, when the animated scroll completes, the scrollViewDidEndScrollingAnimation: delegate method is called, at which point pagingEnabled is set back to YES.
If you find that you're having trouble getting it to recognize a "fast" swipe, try playing with the kCPPickerDecelerationThreshold value. In hindsight that maybe should be a customizable property, so perhaps I'll roll that into the next update.


text:
Q: how to declare sql parametrs in vb.net hi i need to get the customer name from the user as in combo box when the user selets the user i want that selected customer name should be searched in the sql table (here table name is "obbalance ")and all the entries in the table having the name as the selected customer naem it should be shown in the data grid view
cmd.Parameters.Add(New SqlParameter("@p1", SqlDbType.NVarChar).Value = ComboBox1.SelectedItem.ToString)

cmd = New SqlCommand("select obbalance from balance where custname=@p1", con)

dr = cmd.ExecuteReader()
Form2.Show()

after thios also it shows a error plz can u help me out if the code is wrong den help me to
do correct it i am new to vb.net plz ..........
it shows error in declaration so can u send me any other code or if this code den plz send the correct code plz

A:  cmd.Parameters.Add(New SqlParameter("@p1", SqlDbType.NVarChar).Value = ComboBox1.SelectedItem.ToString)

cmd = New SqlCommand("select obbalance from balance where custname=@p1", con)

dr = cmd.ExecuteReader()

Instead of doing this you can do this also
cmd=New SqlCommand("select columnname from tablename where custname='"& ComboBox1.SelectedItem.ToString &"'",con)
 dr = cmd.ExecuteReader()

Why do you want parameterized query

A: You need to add the parameter after creating the new command:
cmd = New SqlCommand("select obbalance from balance where custname=@p1", con)

cmd.Parameters.Add(New SqlParameter("@p1", SqlDbType.NVarChar).Value = ComboBox1.SelectedItem.ToString)

dr = cmd.ExecuteReader()
Form2.Show()

Additionally, you are creating a boolean value as the parameter to the Add method:
New SqlParameter("@p1", SqlDbType.NVarChar).Value = ComboBox1.SelectedItem.ToString

Do this instead:
Dim param as SqlParameter = New SqlParameter("@p1", SqlDbType.NVarChar)
param.Value = ComboBox1.SelectedItem.ToString)
cmd.Parameters.Add(param)


text:
Q: ¿Cómo insertar el caracter ℓ en Latex? No sé que código poner para insertar este tipo de l en Látex.

A: El carácter lo consigues con: \ell
Recuerda que para hacer uso de este comando debes estar en un entorno matemático.


text:
Q: Insert Data from a textbox into a database . c# Hello stack overflow you are my only hope, Its my first question here. I'm having problem with inserting things into a database from textboxes i searched throught it i tried everything it just doesnt work. Here is my code ->
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace E_BANK
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            //objekti per konektim me DBne
            SqlConnection conn = new SqlConnection(@"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True");

            conn.Open();
            using (SqlCommand command = conn.CreateCommand())
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string accref = tb_accref.Text;
                        int deposit = Convert.ToInt32(tb_depamount.Text);
                        int psID = Convert.ToInt32(tb_personalID.Text);
                        string query = "INSERT INTO Bank1(accref, deposit, psID) " +
                "Values('" + accref + "', '" + deposit + "', '" + psID + "')";
                    }
                }
            }

            //mbylle lidhjen me DB
            conn.Close();
            MessageBox.Show("Transition Updatet Sucessfully");
        }

        private void btn_reset_Click(object sender, EventArgs e)
        {
            tb_accref.Text = "";
            tb_depamount.Text = "";
            tb_personalID.Text = "";
            lblamount.Text = "0";
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}

A: Try this way
    private void btn_save_Click(object sender, EventArgs e)
    {

        using (SqlConnection sqlConn = new SqlConnection(@"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True"))
        {
            using (SqlCommand sqlComm = new SqlCommand("INSERT INTO Bank1 (accref, deposit, psID) VALUES (@accref, @deposit, @psID)", sqlConn))
            {
                if (sqlComm.Connection.State == ConnectionState.Closed)
                    sqlComm.Connection.Open();
                string accref = tb_accref.Text;
                int deposit = Convert.ToInt32(tb_depamount.Text);
                int psID = Convert.ToInt32(tb_personalID.Text);

                sqlComm.Parameters.AddWithValue("@accref", accref);
                sqlComm.Parameters.AddWithValue("@deposit", deposit);
                sqlComm.Parameters.AddWithValue("@psID", psID);
                sqlComm.ExecuteNonQuery();
                MessageBox.Show("Transition Updatet Sucessfully");
            }
        }
    }

A: You need to actually run the INSERT command. Check out the ExecuteNonQuery method on the SqlCommand class.

A: EXECUTE Command missing
private void btn_save_Click(object sender, EventArgs e)
{
    //objekti per konektim me DBne
    SqlConnection conn = new SqlConnection(@"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True");

    conn.Open();

    string accref = tb_accref.Text;
    int deposit = Convert.ToInt32(tb_depamount.Text);
    int psID = Convert.ToInt32(tb_personalID.Text);
    //try all fields are string
    string query = "INSERT INTO Bank1(accref, deposit, psID) Values('" + accref + "', '" + deposit + "', '" + psID + "')";
    //try last fields are numeric
    //string query = "INSERT INTO Bank1(accref, deposit, psID) Values('" + accref + "', " + deposit + ", " + psID + ")";

    SqlCommand command = new SqlCommand();
    command.Connection = conn;
    command.CommandText = query;
    command.ExecuteNonQuery()

    //mbylle lidhjen me DB
    conn.Close();
    MessageBox.Show("Transition Updatet Sucessfully");

}

private void btn_reset_Click(object sender, EventArgs e)
{
    tb_accref.Text = "0";
    tb_depamount.Text = "0";
    tb_personalID.Text = "0";
    lblamount.Text = "0";
}

private void btn_exit_Click(object sender, EventArgs e)
{
    Close();
}


text:
Q: Knockout: click binding to add/remove item in hierarchy I would like to understand how to call add/delete functions from within a knockout hierarchy.  For example, if I am inside nested foreach, and I click on a delete button, how can I call a function that will let me delete the item (and do some other things too)?
Here's a Fiddle of the problem. https://jsfiddle.net/4a3z4urc/
In the html, the commented-out button works, but I need the function to be inside my script tags (which isn't working).
function ViewModel(data){
    var self = this;
    self.pages = ko.mapping.fromJS( data );
    self.OutputJson = function(){
        console.log(ko.toJSON(self));
    }

    self.removePage = function(pageName) { self.pages.remove(pageName) };
    self.removeRow = function(rowType) { self.pages.pageRows.remove(rowType) };
    self.removeSlide = function(slide) { self.slides.remove(slide)  };
    self.addSlide = function(slide) {}
}

How can I make the RemoveRow and RemoveSlide functions delete the correct item?  (Json is shown below the demo).  Thanks!

A: Your problem is that in your "inner" remove method you don't have the information of the "currently selected" page, pageRow, slide, etc.
One solution would be to pass in the current $parent into your click handlers:

      <button type="submit" data-bind="click: $root.removeRow.bind($parent, $data)"
          class="btn-delete">×</button>

     ...

And now you can access the "currently selected" page with this in your handler:
self.removeRow = function(rowType) { this.pageRows.remove(rowType) };

Demo JSFiddle.
Note that you also need to use $root to access the "top level" if you inside are multiple foreach bindings.
You can also pass in the $parent as a paramter: root.removeRow.bind(null, $parent, $data), and in this case your handle would look like this:
self.removeRow = function(page, rowType) { page.pageRows.remove(rowType) };

You can read more about the different additional paramter passing options in the documentation.


text:
Q: llv8call on Mac OS X - 2nd try I didn't give a lot of info in my last question.
I've built llv8call from http://code.google.com/p/llv8call/, v0.4. I've gotten the known dependencies installed, being libxml-2.0 and libreadline. My dev system is Mac OS X 10.5. llv8call is built with Scons.
When I attempt to run llv8call via ./llv8call, I get this error:
library loading error: org.coderepos.env is not found in : (loadBinary)

I am not sure how to troubleshoot this error. The author hasn't responded to me yet. I need some tips on how to troubleshoot this more than an explicit answer, though if someone has one it's very welcome.
The files are installed to /usr/local/llv8call. There is a directory structure under llv8call/lib/llv8call/org/coderepos but it doesn't contain an "env" directory. My first guess is that whatever library its looking for at org.coderepos.env is supposed to be in this path, but "env" doesn't exist. If this sounds reasonable, it might be a place that I should start looking at but I need confirmation.

A: Your intuition seems right. Doing a grep:
grep -r "org.coderepos" *|less

I see it checks for many "libraries" under org.coderepos. Furthermore, in src/main.cc in the preload_builtin_classes function, we see:
Handle<Value> args[1];
args[0] = String::New("org.coderepos.fs");
loadBinary->Call(v8ext, 1, args);
args[0] = String::New("org.coderepos.env");
loadBinary->Call(v8ext, 1, args);

if (try_catch.HasCaught()) {
    String::Utf8Value error(try_catch.Exception());
    fprintf(stderr, "library loading error: %s\n", *error);
    exit(2);
}

That, my friend, is your smoking gun.

A: It is looking for a library called env (i.e., libenv.so) in the directory /org/coderepos.
Either make /org/coderepos and copy the libraries into it, or ask your dynamic linker to look for /org/coderepos content elsewhere.

A: I fixed this by doing the following from the top-level directory of my llv8call source directory (after running scons to build everything):
mkdir -p out/lib/llv8call/org/coderepos
find ext -name \*.dylib -exec cp {} out/lib/llv8call/org/coderepos \;

"dtruss -f test.sh" was helpful in finding where v8 was looking for the libs.


text:
Q: How to correctly setup a SSH Key @ forge.laravel.com? I created a server on Linode using forge.laravel.
Everything seems to work fine but now I'm trying to access the server via SSH. Forge by default creates servers that do now allow SSH access via password and so I must add an SSH key to the server and there is an option on the control panel under the server manager tab to do so.
I followed an article from github to create the SSH keys and it works fine connecting to github.
help.github.com/articles/generating-ssh-keys
After placing my public key on forge I tried access the server via SSH using the following:
ssh MY_SERVER_PUBLIC_IP

 ssh forge@MY_SERVER_PUBLIC_IP -i /home/MYUSER/.ssh/id_rsa.pub

I got the following error:
Permission denied (publickey)

Any ideas on how to solve this problem????

A: When creating a key, there are two parts; the public and the private keys.
Go to forge and create a ssh key, you give it a name (any is fine) and then cut and paste the public key into the form field provided.
Then save the private key into you local .ssh folder using the same connection code reference the private key.


text:
Q: Open Pdf file using third party on click on list view item I have PDF files in my assets folder now i am able to view that PDF files in list view .But the problem is now on click of any pdf i want to open pdf in my pdf viewer.
Here is my code
    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AssetManager asset = getAssets();
        try {
            final String[] arrdata = asset.list("PDFfolder");
            List<String> pdflist = new ArrayList<String>();
            int size = arrdata.length;
            for(int i = 0;i<size;i++)
            {
              if(arrdata[i].contains(".pdf"))

              {
                pdflist.add(arrdata[i]);
               }
            }
            ArrayAdapter<String> adapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,pdflist);
            ListView listView = (ListView) findViewById(R.id.listView1);
            listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
             public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                if(position == 0 ) {
                    File pdffile = new File("file:///android_assets/AAI.pdf");
                    //File ff = new File(getAssets().open("AAI.pdf"));
                     Uri path = Uri.fromFile(pdffile);
                     Intent intent = new Intent(Intent.ACTION_VIEW);
                     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                     intent.setDataAndType(path, "application/pdf");
                     startActivity(intent);
                     }

                }

        });
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

     }
}

Now please help me out how to open it using intent from my assets folder. i am getting error of having no activity found to handle intent as i already have pdfviewer in my phone.

A: You need an app installed to handle opening the PDF. You should use the Intent Chooser, like so:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
}

The files in the assets directory doesn't get unpacked. Instead they are read directly from the APK ZIP file.
So, you really can't make stuff that expects a file accept an asset 'file'.
Instead you'll have to extract the asset and write it to a separate file ,like this :
File f = new File(getCacheDir()+"/fileName.pdf");
  if (!f.exists()) try {

    InputStream is = getAssets().open("fileName.pdf");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();

    FileOutputStream fos = new FileOutputStream(f);
    fos.write(buffer);
    fos.close();
  } catch (Exception e) { throw new RuntimeException(e); }

Also you can use the AssetManager to manage files in your asset folder. In the activity, call getAssets () method to get an AssetManager Instance.
Hope it helps you.

A: Work perfectly in my project try this code
/**
         * get on item click listener
         */
        userList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    final int position, long id) {

                TextView tv_paper_name = (TextView) v.findViewById(R.id.tv_paper_name);
                String PaperName = tv_paper_name.getText().toString();
                File extStore = Environment.getExternalStorageDirectory();
                File myFile = new File(extStore.getAbsolutePath() + "/Exam Papers/"+PaperName+".pdf");

                if (myFile.exists()) {

                File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Exam Papers/" +PaperName+".pdf");  // -> filename
                Uri path = Uri.fromFile(pdfFile);
                Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                pdfIntent.setDataAndType(path, "application/pdf");
                pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    try {
                    startActivity(pdfIntent);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(MainActivity.this, "Download file first", Toast.LENGTH_SHORT).show();
                }

            }
        });


text:
Q: UpdateSingleSalesforceObject Custom Object with multiple types ampscript I have a question concerning the UpdateSingleSalesforceObject and did not find the right answer.
Normally it is not problem to update a custom object, but in this case, the custom Object has multiple types.
There is a Consent Object with a Consent Type field. Only if the right Type is selected, the field I want to update would be available. Ist this possible? To define type and field in one AMPScript?
Those two are not working (I tried without the type in the second one):
set @result_account = UpdateSingleSalesforceObject('Candidate_Consents__c','Candidate ID','Consent_Type__', 'Type_ID', 'Status__c', 'I do not Consent')

 set @result_account = UpdateSingleSalesforceObject('Candidate_Consents__c','Candidate ID','Status__c', 'I do not Consent')


text:
Q: AngularJS ignores link function for "some" of multiple nested directives In Angularjs 1.0.7 and 1.1.5, if I try to have multiple directly nested directives, all with replace set to true, the link function gets called only for the bottom 2 levels, while for all top levels it gets ignored
This plunk  - as an example  - does the following for the directive levelThree
 - <level:three /> is replaced by <level:two />
 - <level:two /> is replaced by <level:one />
 - <level:one /> is replaced by <level:zero />
 - <level:zero /> is replaced by
LEVEL 0

So levelThree gets eventually resolved into
LEVEL 0

Reason why I'm doing this is because I want to have at levelZero a very basic/abstract component that is customized by higher level directives. The only problem is that the link function is called only for levelZero and levelOne (You can see in console output), while for levelTwo and levelThree is being ignored. Is that somehow an expected behavior?

A: The problem is because you're using replace, and there is no extra DOM in your upper level templates, so the nested directive structure is somehow lost in the compiling process. It seems to be a bug, but I'm not 100% sure.
But to workaround it is quite easy. In your template 1, 2 and 3, try to wrap <level:n></level:n> in a div. For example, template2.html is changed to:

    <level:one></level:one>

The div wrapper might seem to be unnecessary; but in practice, I think you will have the "extra stuff" part in your template, and angular template has the single root restriction, so you will eventually end up having a wrapper as the root element of you template.


text:
Q: C Type Data Manipulation I'm new to C as a language, and I'm trying to do an XOR operation on two different data types, then store the result in a byte array at offset 1. The array is fixed, and will always be 8 bytes. I'd like to just check with all of you that I'm handling this correctly.
For background, I'd like buf to be the result as a uint8_t array, and my input data types are a char array and another byte array that will be constant in the application. I feel as though there's some casting that I'm missing, but I'm not sure where to look aside from asking:
#include <stdio.h>
#include <stdint.h>

int main()
{
    uint8_t HANDSHAKE_SN[8] = { 0x13, 0x81, 0x22, 0x13, 0xFA, 0x32, 0x65, 0xFA };
    uint8_t buf[8] = { 0x02, 0, 0, 0, 0, 0, 0, 0 };
    char sn[8] = "2345678";

    for(uint8_t i=1;i<9;i++)
    {
        buf[i] = sn[i-1] ^ HANDSHAKE_SN[i-1];
    }

    printf("%s",buf);
}

A: #include <stdio.h>
#include <stdint.h>

#define ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))

#define TEST_SIZE (8)

int main()
{
    uint8_t HANDSHAKE_SN[TEST_SIZE] = { 0x13, 0x81, 0x22, 0x13, 0xFA, 0x32, 0x65, 0xFA };
    uint8_t buf[TEST_SIZE] = { 0 };
    char sn[TEST_SIZE + 1] = "12345678";

    for (uint8_t i = 0; i < ARRAY_LENGTH(buf); ++i)
    {
        buf[i] = sn[i] ^ HANDSHAKE_SN[i];
        printf("0x%hhx\n", buf[i]);
    }
}


text:
Q: React Native - Build Offline Bundle on Debug Build Right now, I am used to using Debug Mode and React Native will open the app and the packager will package it on the spot. This is good for development.
And then I can switch to Release Mode (in Xcode) via my Scheme. The bundle will be prebundled. This is good because as soon as the app opens, the JS is loaded and there is no need to wait.
My problem is that I have a Xcode dependency that only works on Debug mode, but I need certain Bash script to run as soon as the app loads. But if I have to wait for the packager to bundle, my script timing is off.
So does anyone know a way to build main.jsbundle ahead of time, and still be in debug mode (Xcode scheme)?


text:
Q: I removed Python 3.4 physically, is there anything I can do to avoid having to reinstall system? While trying to install a python package I made a horrible mistake and removed Python 3.4 (if you are interested in how did I come up with it below is the link to my question on StackOverflow).
https://stackoverflow.com/questions/36426547/physically-uninstalled-python-3-4-to-make-pip3-install-requests-package-to-pyt/36426985?noredirect=1#comment60469836_36426985
Anyway, now I can't run sudo apt-get install --reinstall python3.4, which is pretty bad I guess. Is there any way I could make my ubuntu 14.04 work again without having to lose files on my computer?
EDIT: Btw. I still have Python 2.7 (which I thought was the one used by the system), perhaps there is some way to use it to recover the rest?


text:
Q: Adding Custom tab to product page dependant on category in Magento 2.2.1 I have used the following code

(https://www.cloudways.com/blog/add-custom-tab-product-page-magento-2/)

to create a module that adds a custom tab to our product pages. It works perfectly but I need to somehow change the module so that the custom tab only display on products in certain categories. Has anyone any suggestions on how to do this? Don't mind if the category numbers need to be hard coded as there won't be many! Please note we are using Magento 2.2.1
David

A: Try replacing code after <?php if ($_attributeValue): ?>, in attribute.phtml with following:
<?php if ($_attributeValue): ?>
<?php if ($_attributeType === 'your_type'):
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
    if (strtolower($category->getName()) === 'category_to_display'): ?>
        <?php /* @escapeNotVerified */ echo $_attributeValue; ?>
    <?php endif; ?>
<?php else: ?>
<div class="product attribute <?php /* @escapeNotVerified */ echo $_className?>">
    <?php if ($_attributeLabel != __('none')): ?><?php /* @escapeNotVerified */ echo $_attributeLabel?><?php endif; ?>
    <div class="value" <?php /* @escapeNotVerified */ echo $_attributeAddAttribute;?>><?php /* @escapeNotVerified */ echo $_attributeValue; ?>

<?php endif; ?>
<?php endif; ?>

change your_type to your declared attribute type, change category_to_display to your desired category name (chain || to add more categories to include tab). Add your code to add your tab logic here


text:
Q: RewriteRule with 2 request parameters in wordpress I'd like to rewrite URL using wordpress. like
/name/1/2/ to /name?last_name=1&first_name=2
I've tried few ways. i.e. following code. But it seems not working well.
Is there any way to do that ?
Thank you
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^name/(\d+)/(\d+)/ index.php?p=9&last_name=$1&first_name=$2 [QSA]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

A: try this
RewriteRule ^name/(\d+)/(\d+)/ index.php?p=9&last_name=$1&first_name=$2 [QSA, L]
You can refer to this post What is L in [QSA, L] in htaccess for understanding QSA and L flag.

QSA means that if there's a query string passed with the original URL,
  it will be appended to the rewrite (olle?p=1 will be rewritten as
  index.php?url=olle&p=1.
L means if the rule matches, don't process any more RewriteRules below
  this one.


text:
Q: Z-index with positioning not working with positioning & Alignment I am having problems with the z-index. I am trying to get the button link to display overtop of the image, but it just isn't seeming to work. The image below shows how I am wanting it to look.
Here is the HTML:

        Buy Now

Here is the CSS:
.featured img
{
    float: left;
    z-index: -1;
}
.button-2
{
    -moz-box-shadow:inset 0px 1px 0px 0px #940c00;
    -webkit-box-shadow:inset 0px 1px 0px 0px #940c00;
    box-shadow:inset 0px 1px 0px 0px #940c00;
    background-color:#8b0101;
    -webkit-border-top-left-radius:0px;
    -moz-border-radius-topleft:0px;
    border-top-left-radius:0px;
    -webkit-border-top-right-radius:0px;
    -moz-border-radius-topright:0px;
    border-top-right-radius:0px;
    -webkit-border-bottom-right-radius:0px;
    -moz-border-radius-bottomright:0px;
    border-bottom-right-radius:0px;
    -webkit-border-bottom-left-radius:0px;
    -moz-border-radius-bottomleft:0px;
    border-bottom-left-radius:0px;
    text-indent:0px;
    display:inline-block;
    color:#ffffff;
    font-family:Arial;
    font-size:15px;
    font-weight:bold;
    font-style:normal;
    height:43px;
    line-height:43px;
    width:135px;
    text-decoration:none;
    text-align:center;
    text-shadow:1px 1px 0px #810e05;
    float: left;
}
.button-2 a
{
    color: #fff;
    font-size: 20px;
    letter-spacing: 2px;
}
.button-2:hover
{
    background-color:#6c0301;
}
.button-2:active
{
    position:relative;
    top: 1px;
}

This is what is displaying: http://imgur.com/XungDOU
This is what I want it to do: http://imgur.com/XHXTKae

A: Try this:
.button-2{
position: absolute;
left:50%;
top:50%;
z-index:99}


text: Q: Is it possible to iterate a set of feature file lines based on the arraylist returned by a step definition Scenario: one step definition returns an ArrayList and I want to run the next lines in the feature file n number of times depending on the size of the ArrayList with a course of actions being performed on each element from the list.


text:
Q: Combine two arrays and downcast elements I have two arrays with 2 UIView elements each and I want to combine them into 1 array while downcasting the elements to UIImageView.
Is there a better way to do this than adding flapMapped arrays?
let topViews = [UIView(), UIView()]
let bottomViews = [UIView(), UIView()]

let imageViews = topViews.flatMap { $0 as? UIImageView } + bottomViews.flatMap { $0 as? UIImageView }

*My use case is putting arrangedSubviews of 2 different stack views in one array (in case topViews and bottomViews look stupid, it's just for simplicity).

A: It's a nice solution and only slightly better way is, as @zgorawski mentioned,
let imageViews = (topViews + bottomViews).flatMap { $0 as? UIImageView }`

since now if you would want to add another array to the equation, you just have to add + anotherOne instead of + anotherOne.flatMap { $0 as? UIImageView }.


text:
Q: Selecting and displaying MS Access query results from sorted column based on other column I have a StudentID column, a column on passing 030 class level by a certain date, and a column on passing 040 class level by a certain date.
Can't get the two results on the same line with the ID because these refer to different classes taken at different times (some students completed 030 or 040 in a different semester so there are N / Y and Y / N results for some of the IDs.
Desired outcome: StudentID has unique values, 030 and 040 is either Y or N. All on one line for each StudentID.
Here is a screen shot of my query setup.

Here is a screenshot of the current output. If an ID number has two Ys, I want them to show on the same line.

A: From your 'Query Setup' screenshot, I can't see the foreign key that you are using with the LEFT JOIN from the StudentID field in your 152_Entrants table, but assuming that this foreign key is also called StudentID, then I would suggest the following (untested) code:
SELECT
    [152_Entrants].StudentID,
    Nz(P030.PassOrFail,"N") AS 030pass,
    Nz(P040.PassOrFail,"N") AS 040pass
FROM
(
    152_Entrants
    LEFT JOIN
    (
        SELECT DISTINCT StudentID, PassOrFail FROM FinalMark
        WHERE
            SemesterNumber <= 162 AND
            CourseType = "040" AND
            PassOrFail = "P"
    )  AS P040 ON [152_Entrants].StudentID = P040.StudentID
)
LEFT JOIN
(
    SELECT DISTINCT StudentID, PassOrFail FROM FinalMark
    WHERE
        SemesterNumber <= 162 AND
        CourseType = "030" AND
        PassOrFail = "P"
) AS P030 ON [152_Entrants].StudentID = P030.StudentID;

Here, each of the subqueries is returning the unique set of StudentID values for which PassOrFail is "P" for records with SemesterNumber <= 162 for each CourseType.
Your table 152_Extrants is then LEFT JOINed to each subquery such that if a matching StudentID is found in the subquery, the student has passed (based on your criteria), else the student has failed and so the Nz function will return "N".

EDIT
On viewing the composition of your 152_Entrants query, the complete query could become:
SELECT
    E152.StudentID,
    Nz(P030.PassOrFail,"N") AS 030pass,
    Nz(P040.PassOrFail,"N") AS 040pass
FROM
(
    (
        SELECT StudentID FROM FinalMark
        WHERE SemesterNumber = 152
        GROUP BY StudentID
    ) AS E152
    LEFT JOIN
    (
        SELECT DISTINCT StudentID, PassOrFail FROM FinalMark
        WHERE
            SemesterNumber <= 162 AND
            CourseType = "040" AND
            PassOrFail = "P"
    ) AS P040 ON E152.StudentID = P040.StudentID
)
LEFT JOIN
(
    SELECT DISTINCT StudentID, PassOrFail FROM FinalMark
    WHERE
        SemesterNumber <= 162 AND
        CourseType = "030" AND
        PassOrFail = "P"
) AS P030 ON E152.StudentID = P030.StudentID;

Without the need for a separate 152_Entrants query.


text:
Q: Firebase Cloud Messaging - Django - how do I service worker? Update from a place of mild understanding:
I have read much about Service Workers and advanced the project I'm working on far past where it was when I wrote this.
The main issue I was exploring here (getting firebase-messaging-sw.js served from the root of the domain) was solved by the ServiceWorkerView below.
Fun fact: turns out that the reason to have firebase-messaging-sw.js served from the root of the domain is that the scope of a Service Worker's control is defined by the URL. So, while:
http://whatever.com/firebase-messaging-sw.js has control over everything,
http://whatever.com/static/firebase-messaging-sw.js only has control over everything under /static/ (in this case, only the static resources served by Django). Even though the JS file is static, it needs to control pages outside that path.
A good starting point for learning about Service Workers
Original Question:
How do I get the FCM service worker (firebase-messaging-sw.js) to work in Django?
I'm using django with fcm-django.
How do I serve firebase-messaging-sw.js at the root?
Django serves static assets by default under the path "/static/". Changing the STATIC_URL to "/" makes firebase-messaging-sw.js available but nothing else is..
I tried a suggestion to put the following in my urls.py:
url(r'^(?!/static/.*)(?P<path>.*\..*)$', RedirectView.as_view(url='/static/%(path)s'))
While clearly a glorious use of regex magic, it turns out that the service worker can't be behind a redirect. (I guess this also has to do with the fun fact)
I wrote a view pointed to by an explicit URL in the urlconf. that works.
class ServiceWorkerView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'fcmtest/firebase-messaging-sw.js')

urls.py:
path('firebase-messaging-sw.js', views.ServiceWorkerView.as_view(), name='service_worker')
Now the url http://localhost:8000/firebase-messaging-sw.js serves up the javascript; however, Firebase complains that the content-type is text/plain
So I changed the view to:
class ServiceWorkerView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'fcmtest/firebase-messaging-sw.js', content_type="application/x-javascript")

And the error I get is:

Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A
  bad HTTP response code (404) was received when fetching the script.

My firebase-messaging-sw.js (note none of the console.log statements print):
importScripts("https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/5.2.0/firebase-messaging.js");
importScripts("https://www.gstatic.com/firebasejs/5.2.0/init.js");

// Initialize Firebase
var config = {
    apiKey: "AIzaSyBOb5gh1Lry84116M1uvAS_xnKtcWUoNlA",
    authDomain: "pyfcm-5f794.firebaseapp.com",
    databaseURL: "https://pyfcm-5f794.firebaseio.com",
    projectId: "pyfcm-5f794",
    storageBucket: "pyfcm-5f794.appspot.com",
    messagingSenderId: "813943398064"
};
console.log('in service worker - before initializeApp')
firebase.initializeApp(config);
console.log('in service worker - after initializeApp')

const messaging = firebase.messaging();
console.log('in service worker - after firebase.messaging')

// if the app is in the background (user not on page)
messaging.setBackgroundMessageHandler(function(payload) {
    console.log('in service worker - in setBackgroundMessageHandler')
    const title = "Hello World";
    const options = {
        body: payload.data.status
    }
    return self.registration.showNotification(title, options);
});

and finally, my device registration page (I'm not sure how to run the javascript and then submit. form.submit() didn't work but that might be because of other things not working..?
(fcm/fcmtest/templates/fcmtest/device_registration.html):

    {% load static %}
    <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>FCM Device Registration</title>

{% if error_message %}
{{ error_message }}
{% endif %}

<form id="registration_form" method="post">{% csrf_token %}
    <input id="name" type="text" />
    <input id="type" type="hidden" />
    <input id="user" type="hidden" value="{{ user.id }}" />
    <input id="registration_id" type="hidden" />
    <input id="btn_register" type="button" value="Register" onclick="deviceRegistration();" />
</form>

I tried adding a manifest.json as per instructions on
https://firebase.google.com/docs/cloud-messaging/js/client
It is currently served from my static files and is linked in the registration and send pages
The errors in my console:

Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A
  bad HTTP response code (404) was received when fetching the script.
A bad HTTP response code (404) was received when fetching the script.
Failed to load resource: net::ERR_INVALID_RESPONSE
firebase-messaging-sw.js:3 Uncaught

(anonymous) @ firebase-messaging-sw.js:3

index.esm.js:1945 Uncaught (in promise)

Object

browserErrorMessage:

"Failed to register a ServiceWorker: ServiceWorker script evaluation failed"

code:

"messaging/failed-serviceworker-registration"

message:

"Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration)."

stack:

"FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration).↵    at https://www.gstatic.com/firebasejs/5.2.0/firebase-messaging.js:1:34104"

A: The issue of not being able to serve firebase-messaging-sw.js can be solved by creating a ServiceWorkerView to GET the file directly and hardcoding the URLconf.
fcm/fcmtest/views.py:
class ServiceWorkerView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'fcmtest/firebase-messaging-sw.js', content_type="application/x-javascript")

fcm/fcmtest/urls.py
app_name = 'fcmtest'
urlpatterns = [
    ...
    path('firebase-messaging-sw.js', views.ServiceWorkerView.as_view(), name='service_worker')
]

The reason to serve firebase-messaging-sw.js from the root of the domain is that the scope of a Service Worker's control is defined by the URL path. Everything under the path the Service Worker is available at is under its control.

The 404 might be due to a javascript error in device_registration.html. config is referenced but has not been assigned to.
function deviceRegistration() {
    firebase.initializeApp(config);

Also, it is not necessary (maybe even problematic) to do this with Firebase Cloud Messaging:
navigator.serviceWorker.register("/firebase-messaging-sw.js")
.then((registration) => {
    messaging.useServiceWorker(registration);
})

Instead, use firebase.initializeApp(config);

It might be a good idea to serve manifest.json at the root.

The issue with form.submit() is that the code to alter the elements in the form from the promise is incomplete. After debugging that it will work great.

A: I like what Inversus has done because it will work in dev/test/prod. That being said, in production I have elected to let nginx serve the firebase-messaging-sw.js file . . .
    # Firebase Cloud Messaging (FCM) requires this file to be served from
    # your root directory
    location =/firebase-messaging-sw.js {
        root /home/ubuntu/yourpath/yourproject/FCM/;
    }


text:
Q: FK Constraint error Headache - SQL Server For a project I am trying to migrate an Access database to an SQL database.
To do this I created a linked server with the Access database and created a script that inserts the data from the Access into the SQL database. The created script is made with a try catch for each insert so that the ordering of the tables doesnt matter. To give an idea, below the script for 2 tables (total of 130 tables) that insert the data into SQl:
SET NOCOUNT ON

DECLARE @Rows AS INT

-- ****************************************************************************
-- ID = 1
IF NOT EXISTS (select * from TableInserted where ID = 1)
BEGIN
    PRINT '~UpdateDB:'
    BEGIN TRY
        BEGIN TRANSACTION

            INSERT INTO [~UpdateDB](
            --   [SSMA_TimeStamp],

                [StepID],
                [SQLInstruction],
                [Description],
                [Customer],
                [InsertDateTime],
                [InsertUserID],
                [ExecutedateTime]
            )
            SELECT
                [StepID],
                [SQLInstruction],
                [Description],
                [Customer],
                [InsertDateTime],
                [InsertUserID],
                [ExecutedateTime]
            FROM [OPS_VSS_LINKED]...[~UpdateDB]

            SELECT @Rows = @@ROWCOUNT
            PRINT CAST(@Rows as NVARCHAR(10)) + ' Inserted'
        COMMIT TRANSACTION
        INSERT INTO TableInserted( ID, TableName, RowsInserted) VALUES  (1,'~UpdateDB', @Rows)
    END TRY
    BEGIN CATCH
            PRINT ERROR_MESSAGE()
        ROLLBACK TRANSACTION
    END CATCH
END

-- ****************************************************************************
-- ID = 2
IF NOT EXISTS (select * from TableInserted where ID = 2)
BEGIN
    PRINT '~VAN SLUISVELD Origineel:'

    SET IDENTITY_INSERT dbo.[~VAN SLUISVELD Origineel] ON

    BEGIN TRY
        BEGIN TRANSACTION

            INSERT INTO [~VAN SLUISVELD Origineel](

                [ID],
                [a]
            )
            SELECT
                [ID],
                [a]
            FROM [OPS_VSS_LINKED]...[~VAN SLUISVELD Origineel]

            SELECT @Rows = @@ROWCOUNT
            PRINT CAST(@Rows as NVARCHAR(10)) + ' Inserted'
        COMMIT TRANSACTION
        INSERT INTO TableInserted( ID, TableName, RowsInserted) VALUES  (2,'~VAN SLUISVELD Origineel', @Rows)
    END TRY
    BEGIN CATCH
            PRINT ERROR_MESSAGE()
        ROLLBACK TRANSACTION
    END CATCH

    SET IDENTITY_INSERT dbo.[~VAN SLUISVELD Origineel] OFF

END

So this script will only insert data if it hasn't been done yet (check in the TableInserted). If the insert generates error then it will rollback on the specific table.
This all works great but the access database is prety corrupted (cause of bad desingnin).
I am getting 50+ FK errors and I get stuck on this one in particular:
Relaties:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Relaties_Tariefnummers". The conflict occurred in database "OPS-VSS", table "dbo.Tariefnummers", column 'Tariefnummer'.
Tariefnummers:
The INSERT statement conflicted with the FOREIGN KEY constraint "Tariefnummers$RelatiesTariefnummers". The conflict occurred in database "OPS-VSS", table "dbo.Relaties", column 'RelatieNummer'.

Multiple FK errors are with the Relaties table so I thought lets fix that one first.
Above you can see the Relaties table fails inserting because of a FK error on the TariefNummers table, this is not strange since that specific table hasn't got it's data in it since that table also has a FK error.
So the next logical thing for me was to fix the FK error on the TariefNummers table. Though the FK error on the TariefNummers is linked to the Relaties table... So they are diabling each other.. Any clue how to fix this? Should I just delete 1 FK (on the TariefNummers) which isn't preferred.
I might be way off though, but some pointers would be appreciated!

A: There can be valid reasons to want to have two tables with foreign keys to each other, but how will you ever be able to put data in them in the first place?
To populate the tables, you will have to drop or ignore one of those foreign keys, at least temporarily, until both tables are populated.


text:
Q: Make Fivestar 7.x-2.2 mobile-friendly I am using the Fivestar 2.2 module. Everything works fine, but voting on a touch screen doesn't: It is impossible to give 5 stars on a 5 star widget, even though it works perfectly on the desktop. Unfortunately I'm not allowed to provide a link.
Is there someone who already solved this? Drupal.org is not a help.
/**
* @file
*
* Fivestar JavaScript behaviors integration.
*/

/**
* Create a degradeable star rating interface out of a simple form structure.
*
* Originally based on the Star Rating jQuery plugin by Wil Stuckey:
* http://sandbox.wilstuckey.com/jquery-ratings/
*/
(function($){ // Create local scope.

Drupal.behaviors.fivestar = {
attach: function (context) {
$(context).find('div.fivestar-form-item').once('fivestar', function() {
  var $this = $(this);
  var $container = $('

');
  var $select = $('select', $this);

  // Setup the cancel button
  var $cancel = $('option[value="0"]', $this);
  if ($cancel.length) {
    $('
' + $cancel.text() + '
')
      .appendTo($container);
  }

  // Setup the rating buttons
  var $options = $('option', $this).not('[value="-"], [value="0"]');
  var index = -1;
  $options.each(function(i, element) {
    var classes = 'star-' + (i+1);
    classes += (i + 1) % 2 == 0 ? ' even' : ' odd';
    classes += i == 0 ? ' star-first' : '';
    classes += i + 1 == $options.length ? ' star-last' : '';
    $('
' + element.text + '
')
      .addClass(classes)
      .appendTo($container);
    if (element.value == $select.val()) {
      index = i + 1;
    }
  });

  if (index != -1) {
    $container.find('.star').slice(0, index).addClass('on');
  }
  $container.addClass('fivestar-widget-' + ($options.length));
  $container.find('a')
    .bind('click', $this, Drupal.behaviors.fivestar.rate)
    .bind('mouseover', $this, Drupal.behaviors.fivestar.hover);

  $container.bind('mouseover mouseout', $this, Drupal.behaviors.fivestar.hover);

  // Attach the new widget and hide the existing widget.
  $select.after($container).css('display', 'none');

  // Allow other modules to modify the widget.
  Drupal.attachBehaviors($this);
});
},
rate: function(event) {
var $this = $(this);
var $widget = event.data;
var value = this.hash.replace('#', '');
$('select', $widget).val(value).change();
var $this_star = (value == 0) ? $this.parent().parent().find('.star') :
$this.closest('.star');
$this_star.prevAll('.star').andSelf().addClass('on');
$this_star.nextAll('.star').removeClass('on');
if(value==0){
  $this_star.removeClass('on');
}

event.preventDefault();
},
hover: function(event) {
var $this = $(this);
var $widget = event.data;
var $target = $(event.target);
var $stars = $('.star', $this);

if (event.type == 'mouseover') {
  var index = $stars.index($target.parent());
  $stars.each(function(i, element) {
    if (i <= index) {
      $(element).addClass('hover');
    } else {
      $(element).removeClass('hover');
    }
  });
} else {
  $stars.removeClass('hover');
}
}
};
})(jQuery);

A: Sorry if it's not what you asked but I'll try to help. Don't use fivestar, I've been in the same situation. I suggest you to try the rate module (https://www.drupal.org/project/rate) which is in my opinion a more complete solution.
I have a responsive website which of course works with mobile devices and you can vote without problem, although I can't assure it was mobile ready.