How to extract element from html in Racket?

Question: I want to extract the urls in reddit, my code is
#lang racket

(require net/url)
(require html)

(define reddit (string->url "http://www.reddit.com/r/programming/search?q=racket&sort=relevance&restrict_sr=on&t=all"))
(define in (get-pure-port reddit #:redirections 5))

(define response-html (read-html-as-xml in))
(define content-0 (list-ref response-html 0))

(close-input-port in)

The content-0 above is
(element
 (location 0 0 15)
 (location 0 0 82)
...

I'm wondering how to extract specific content from it.
Answer:
Usually it's more convenient to deal with HTML as x-expressions instead of the html module's structs.
Also you should probably use call/input-url to handle closing the port automatically.

You can combine both of these ideas by defining a read-html-as-xexpr function and using it like this:
#lang racket/base

(require html
         net/url
         xml)

(define (read-html-as-xexpr in) ;; input-port? -> xexpr?
  (caddr
   (xml->xexpr
    (element #f #f 'root '()
             (read-html-as-xml in)))))

(define reddit (string->url "http://www.reddit.com/r/programming/search?q=racket&sort=relevance&restrict_sr=on&t=all"))

(call/input-url reddit
                get-pure-port
                read-html-as-xexpr)

That will return a big x-expression like:
'(html
  ((lang "en") (xml:lang "en") (xmlns "http://www.w3.org/1999/xhtml"))
  (head
   ()
   (title () "programming: search results")
   (meta
    ((content " reddit, reddit.com, vote, comment, submit ")
     (name "keywords")))
   (meta
    ((content "reddit: the front page of the internet") (name "description")))
   (meta ((content "origin") (name "referrer")))
   (meta ((content "text/html; charset=UTF-8") (http-equiv "Content-Type")))
... snip ...

How to extract specific pieces of that?

For simple HTML where I don't expect the overall structure to change, I will often just use match.
However a more correct and robust way to go about it is to use the xml/path module.

UPDATE: I noticed your question started by asking about extracting URLs. Here's the example updated to use se-path*/list to get all the href attributes of all the  elements:
#lang racket/base

(require html
         net/url
         xml
         xml/path)

(define (read-html-as-xexprs in) ;; (-> input-port? xexpr?)
  (caddr
   (xml->xexpr
    (element #f #f 'root '()
             (read-html-as-xml in)))))

(define reddit (string->url "http://www.reddit.com/r/programming/search?q=racket&sort=relevance&restrict_sr=on&t=all"))

(define xe (call/input-url reddit
                           get-pure-port
                           read-html-as-xexprs))

(se-path*/list '(a #:href) xe)

Result:
'("#content"
  "http://www.reddit.com/r/announcements/"
  "http://www.reddit.com/r/Art/"
  "http://www.reddit.com/r/AskReddit/"
  "http://www.reddit.com/r/askscience/"
  "http://www.reddit.com/r/aww/"
  "http://www.reddit.com/r/blog/"
  "http://www.reddit.com/r/books/"
  "http://www.reddit.com/r/creepy/"
  "http://www.reddit.com/r/dataisbeautiful/"
  "http://www.reddit.com/r/DIY/"
  "http://www.reddit.com/r/Documentaries/"
  "http://www.reddit.com/r/EarthPorn/"
  "http://www.reddit.com/r/explainlikeimfive/"
  "http://www.reddit.com/r/Fitness/"
  "http://www.reddit.com/r/food/"
  ... snip ...


Excel Process Still Running After Quitting Application in VBScript

Question: I have a VBScript that runs every day to sort out an Excel file that is uploaded every night to a shared drive. The issue I am running into is that even after I quit the Excel application, the Excel process is still running in the task manager. I want to make sure that Excel is terminated fully every time the VBScript is run.
Interestingly, I have also tried to close Excel from within the VBA in the macro and it still does not terminate the process but if I run the macro directly (by opening Excel and running the macro from there) the process does terminate properly.
The code I use is below:
Dim xlApp
Dim xlBook

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("\\File\Path\XL.xlsm", 0, True)

xlApp.Visible = False

xlApp.Run "SortData"

xlApp.ActiveWorkbook.Close false

xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

Edit:
Below is the code run in the Excel macro "SortData":
Public Sub SortData()

Dim Dummy As String
Dim MyPath As String
Dim FilesInPath As String
Dim MyFiles() As String
Dim CheckFile As String
Dim Conc(100000) As String
Dim TheSelection As String
Dim TS As String
Dim TheDate As Date
Dim CheckDate As Date
Dim Newest As Date
Dim TheFile As Object
Dim i, n, j As Long
Dim Count As Long
Dim FNum As Long

Dim YearC(), Model(), SupNum(), SupName(), B5(), BPN(), MBPN(), PartName(), PackType(), QTY(), Rank(), PackWeight(), PartWeight(), Dunnage() As Variant
Dim Updated As Variant

Application.ScreenUpdating = False

MyPath = "\\File\Path\Sorted Parts Lists\"
TheDate = Date

FilesInPath = Dir(MyPath & "*.xl*")

If FilesInPath = "" Then GoTo Good

FNum = 0

Do While FilesInPath <> ""
    FNum = FNum + 1
    ReDim Preserve MyFiles(1 To FNum)
    MyFiles(FNum) = MyPath & FilesInPath
    FilesInPath = Dir()
Loop

Newest = "1/1/2000" 'Arbitrary start date
Set TheFile = CreateObject("Scripting.FileSystemObject")
For FNum = LBound(MyFiles) To UBound(MyFiles)
    CheckFile = MyFiles(FNum)
    Updated = TheFile.Getfile(CheckFile).DateLastModified
    If Updated > Newest Then 'Find the newest file in the folder
        Newest = Updated
    End If
Next FNum

If Newest >= TheDate - 7 Then GoTo TheEnd

Good:

Dim FilePath As String
FilePath = "\\File\Path\Parts List.xls"
Workbooks.Open Filename:=FilePath
ActiveWorkbook.Sheets(1).Select

ReDim YearC(100000)
ReDim Model(100000)
ReDim SupNum(100000)
ReDim SupName(100000)
ReDim B5(100000)
ReDim BPN(100000)
ReDim MBPN(100000)
ReDim PartName(100000)
ReDim PackType(100000)
ReDim QTY(100000)
ReDim Rank(100000)
ReDim PackWeight(100000)
ReDim PartWeight(100000)
ReDim Dunnage(100000)

Range("BB:HJ,Y:AZ,V:V,T:T,S:S,J:O,E:E").Select
Selection.Delete Shift:=xlToLeft

Range("K:K").Select
Selection.Delete Shift:=xlToLeft

i = 0
Count = 0
Range("D1").Select
TheSelection = Trim(Selection.Value)

Do While TheSelection <> ""
    Select Case TheSelection
        Case "AE", "HCM ST+ENG", "SIOO"
            GoTo NextRow
        Case Else
    End Select

    'Check for duplicates
    Dummy = TheSelection & Trim(Selection.Offset(0, 3).Value)
    For n = 0 To i
        If Conc(n) = Dummy Then
            GoTo NextRow
        End If
    Next n

    If i <> 0 Then Conc(i) = Dummy

    YearC(i) = Selection.Offset(0, -3).Value
    Model(i) = Selection.Offset(0, -2).Value
    SupNum(i) = Selection.Offset(0, -1).Value
    SupName(i) = Selection.Value
    B5(i) = Selection.Offset(0, 1).Value
    BPN(i) = Selection.Offset(0, 2).Value
    MBPN(i) = Selection.Offset(0, 3).Value
    PartName(i) = Selection.Offset(0, 4).Value
    PackType(i) = Selection.Offset(0, 5).Value
    QTY(i) = Selection.Offset(0, 6).Value
    Rank(i) = Selection.Offset(0, 7).Value
    PackWeight(i) = Selection.Offset(0, 8).Value
    PartWeight(i) = Selection.Offset(0, 9).Value
    Dunnage(i) = Selection.Offset(0, 10).Value

    i = i + 1
NextRow:

Count = Count + 1
Selection.Offset(1, 0).Select
TheSelection = Trim(Selection.Value)

If Count > 100000 Then
    Debug.Print "Escaped"
    Exit Sub
End If

Loop
ReDim Preserve YearC(i)
ReDim Preserve Model(i)
ReDim Preserve SupNum(i)
ReDim Preserve SupName(i)
ReDim Preserve B5(i)
ReDim Preserve BPN(i)
ReDim Preserve MBPN(i)
ReDim Preserve PartName(i)
ReDim Preserve PackType(i)
ReDim Preserve QTY(i)
ReDim Preserve Rank(i)
ReDim Preserve PackWeight(i)
ReDim Preserve PartWeight(i)
ReDim Preserve Dunnage(i)

'Range("A1:N" & Count).ClearContents

Sheets.Add After:=Worksheets(Worksheets.Count)
Sheets(Worksheets.Count).Name = "Sorted Data"
Sheets(Worksheets.Count).Select

ActiveSheet.Range("A1:A" & i).Value = WorksheetFunction.Transpose(YearC)
ActiveSheet.Range("B1:B" & i).Value = WorksheetFunction.Transpose(Model)
ActiveSheet.Range("C1:C" & i).Value = WorksheetFunction.Transpose(SupNum)
ActiveSheet.Range("D1:D" & i).Value = WorksheetFunction.Transpose(SupName)
ActiveSheet.Range("E1:E" & i).Value = WorksheetFunction.Transpose(B5)
ActiveSheet.Range("F1:F" & i).Value = WorksheetFunction.Transpose(BPN)
ActiveSheet.Range("G1:G" & i).Value = WorksheetFunction.Transpose(MBPN)
ActiveSheet.Range("H1:H" & i).Value = WorksheetFunction.Transpose(PartName)
ActiveSheet.Range("I1:I" & i).Value = WorksheetFunction.Transpose(PackType)
ActiveSheet.Range("J1:J" & i).Value = WorksheetFunction.Transpose(QTY)
ActiveSheet.Range("K1:K" & i).Value = WorksheetFunction.Transpose(Rank)
ActiveSheet.Range("L1:L" & i).Value = WorksheetFunction.Transpose(PackWeight)
ActiveSheet.Range("M1:M" & i).Value = WorksheetFunction.Transpose(PartWeight)
ActiveSheet.Range("N1:N" & i).Value = WorksheetFunction.Transpose(Dunnage)

ActiveSheet.Range("A1:N1").AutoFilter
ActiveSheet.Columns.AutoFit

TS = TheDate
j = Len(TS)
Dummy = ""
For i = 1 To j
    If Mid(TheDate, i, 1) = "/" Then
        Dummy = Dummy & "-"
    Else: Dummy = Dummy & Mid(TS, i, 1)
    End If
Next i

Application.DisplayAlerts = False
ActiveWorkbook.SaveAs MyPath & "Sorted DC Parts List " & Dummy & ".xlsx", 51
Application.DisplayAlerts = True
Application.ScreenUpdating = True

Exit Sub

TheEnd:

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

Comment: Instead of 'xlApp.ActiveWorkbook.Close' try 'xlBook.Close' as ActiveWorkbook might not be set if run from scheduler.
Comment: although using a different file and macro, this code works for me and closes properly. is it possible something in `SortData` is causing the problem? maybe post that as well...
Comment: Set `xlApp.Visible = True` and see what's happening. Make sure the lingering process is actually from the script and not an artifact from something else.
Comment: @Fink - Changing `xlApp.ActiveWorkbook.Close` to `xlBook.Close` makes no difference.
@AnsgarWiechers - Everything appears to close at the end of the macro. No errors or message boxes appear while it runs or during closing.
Answer: Try this out and see if it helps:
Dim xlApp
Dim xlBook
'Create a shell
Dim WsShell
Set WsShell = CreateObject("WScript.Shell")

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("\\File\Path\XL.xlsm", 0, True)

xlApp.Visible = False

xlApp.Run "SortData"

'Close the workbook, may want to save
xlApp.ActiveWorkbook.Close true

Set xlBook = Nothing
Set xlApp = Nothing
Set WsShell = Nothing
'Close the script
WScript.Quit

Comment: Tried this code out and it's still leaving the process running.
Answer: Try to add the following to the beginning of "SortData" or somewhere after opening this workbook:
If ActiveWorkbook.Close then
    Exit Sub
End If

Comment: This throws a compile error: "Expected Function or variable"
Comment: refering to an older thread on another Homepage: http://www.mrexcel.com/forum/excel-questions/395568-excel-visual-basic-applications-how-exit-all-macros.html   try to add "End" in the Document_close()-Sub
Comment: I tried adding`End` to `Private Sub Workbook_BeforeClose(Cancel As Boolean)` in the excel book but the process still shows that it's open. I also confirmed that the macro was running so I know that's not an issue.


Future LTS upgrade from 22.10

Question: I already upgraded to 22.10 What do I need to do to pickup the next LTS track?
I was on 22.04 LTS
Comment: Ubuntu 22.10 is the first release in the Ubuntu 24.04 LTS *development* cycle.  There are three non-LTS releases released in the two year full development cycle; ie. 22.10, 23.04, 23.10 before the final 24.04 LTS is released. You're already on the 24.04 release cycle, but need to *release-upgrade* through each release as only users of the last LTS cycle can *release-upgrade* directly to 24.04 (after 24.04.1 LTS has been released)
Answer: The next LTS will be 24.04, to be released on April 2024.
You can upgrade from 22.10->23.04->23.10->24.04 (each of the interim releases will be supported for nine months).
If you don't want to upgrade so many times and want to keep using the same operating system, then reinstall Ubuntu 22.04 (it will be supported until 2027, and you can directly upgrade 22.04 -> 24.04 when it will be released).
Comment: There will be no upgrade path from 23.04 to 24.04.
Comment: Thanks, so I need to do a 9 month update until I get back on 24.04 LTS. What if I go 12 months, can I still upgrade? Say I do a  22.10->23.04-->24.04 LTS. What happens?
Comment: However, you can always fresh install any version of Ubuntu.
Comment: @daniel451 24.04 will be released in April 2024. If you want to use LTS, use 22.04. Otherwise, use 23.04.

Future LTS upgrade from 22.10


transform each row to several columns dataframe Pandas DataFrame

Question: I have a Pandas dataframe,whose every row consists of a list of indexes (one column named "Indexes" which has a comma separated string of value):
'Indexes'
'1,4,6,3,2,5,6,8'
'1,7,5,10,23,50'
I want to use apply in order to create a new matrix (DataFrame?), whose every row, has 1s at the values listed in the respective row in the original dataframe, and 0 elsewhere.  Assume that i know the number of new columns, as i have the min and max indexes (say 0 and 10). I can do it using iterrows/itertuples and construct a new matrix, but is there a more efficient way of doing that? I have a matrix of 1Million rows, but even at 100k this quite a long time.
[EXAMPLE]:
i'll an example and desired output for ease of understanding:
assume MAX_INDEX = 4 and MIN_INDEX=0:
for input:
'1,3,2,4'
'0,1'
the output will be 5-column matrix with two rows as follows:
0 1 1 1 1
1 1 0 0 0
[EDIT]
question remains - although i figured out it was very slow just because i created the new matrix using append, instead of allocating the memory a-priori and only inserting new rows. so one solution is:
m=np.empty(shape=[df.shape[0],numFeatures])
i=0
for row in df.itertuples():
    idxs = row[4] # column of peattributes
    idxs = map(lambda(x):int(x),idxs.split(','))
    r=np.zeros(numFeatures)
    r[idxs] = 1
    m[i,]=r
    i+=1

thanks,
Dan
Comment: Can you show us your desired output, based on the example you provided?
Comment: Thanks. Please update the original question.
Comment: Can you put this information in the original question? There is an edit button under it. It will be easier to read.
Comment: yes, sry about that. editted.
Comment: I'd be curious to see speed comparisons with your solution (I couldn't make your code work to do it myself...).
Answer: Edit: It is much faster (four times) to check whether a string representing the integer is in the original string:
rng_str = [str(i) for i in range(MIN_INDEX, MAX_INDEX+1)]
s = df['Indexes'].apply(lambda row: [int(i in row) for i in rng_str])
pd.DataFrame(s.tolist())

Note: the last step converts from a Series of lists to a dataframe. It is faster to do it at the end rather than inside apply.

Original answer below:
I have a solution, I'd be curious to know if it performs faster than yours. The first step is to convert the string to list:
df['Indexes'] = df['Indexes'].apply(lambda s: [int(x) for x in s.split(',')])

I can then use the apply function to generate your output row by row:
rng = range(MIN_INDEX, MAX_INDEX+1)
df.apply(lambda row: [int(i in row['Indexes']) for i in rng], axis=1)

Output:
0    [0, 1, 1, 1, 1]
1    [1, 1, 0, 0, 0]


Access value of PHP variable in smarty template

Question: How can the value of a variable that has been set in PHP be accessed in smarty? My example PHP code is:
function searchTwitter() {
    global $smarty;

    $test1 = 'Sometext';
    $smarty->assign("test1", $test1);
    ...
}

My .tpl file will have this section:
test={$test1}

I expect this to display the following in my browser:
test=Sometext

but it doesn't. Could you please advise how I can achieve this? Thanks.
Comment: Seems okay. What is the output?
Comment: Have you included "include('Smarty.class.php');" ?
Comment: You are using function .You need to return a value in php
Comment: Please reffer this sites. http://www.smarty.net/quick_install and http://www.smarty.net/crash_course
Comment: @sroes The output is `test=`
Comment: It should work. Maybe $smarty is redeclared later in the code or the variable gets overwriten somewhere else or you've already executed $smarty->display before calling the function
Answer: Actually smarty template engine is use for separate php variable and smarty variable. If you want to use php variable in smarty template you need to assign php variable to smarty through $smarty->assign('smarty variable',php variable);
In smarty there is utility is assign which assign smarty variable to another smarty variable at run time.
or
{assign varname=varname value=$test1}
now print $varname will print $test1 value
Answer: You must use double brackets so try this, it should work:
{{$variable}}

Hope i was helpfull


JQuery in HTML doesn't do anything

Question: So, i've been trying to get this JQuery code to run in my HTML code, but it just won't. I have been looking the site over for ages, and still can't find a solution. (I found similar problems, but the fixes doesn't work.)
HTML:
<!DOCTYPE html>

    <link href="../CSS/stylesheet.css" rel="stylesheet" type="text/css">

Add me on Facebook!

So this is the whole thing. I removed the data itself, but I don't see it should be a problem.
JS:
$(document).ready(function() {
$('.box').mouseenter(function() {
    $('.box').fadeTo('fast', 1);
});
$('.box').mouseleave(function() {
    $('.box').fadeTo('fast', 0.5);
});
});

My guess is that I don't link to the JQuery script properly, but I can't find the answer. I simply want the ".box" to go from opacity 0.5 (which it is in my CSS file aswell) to 1 when hovering the mouse over it, and then go back to 0.5 when I remove te cursor again.
Comment: Where is your JavaScript, within the script.js file?  If so, the script.js file needs to be placed after the jquery library script.
Comment: Check browser console for any errors. Like Sean said, you need to load jquery library before your `script.js`, if that depends on jQuery.
Comment: try puting your script tags at the bottom
Comment: Well I switched the jquery library and my script around. Still doesn't react.
What do you mean with JavaScript within the script.js file?
Should I try to link to another library?
Comment: @JensDissingPoulsen, it works here. http://codepen.io/anon/pen/KVpbbg. Initially it doesn't show faded, the effect only works after hover over and off it.
Comment: Chris, that's EXCATLY how it should run! How in hell can't it run on with my own files?
Comment: Jens, where ***is*** the **JS:** you show, starting `$(document).ready(function() {` — is that code in your `src="script.js"` file, or is it in `` tags somewhere in the html file? Where it is _matters_, and that is what Seano666 was asking. You should update your question and state where that JS is.
Answer: You need to run the js script AFTER the jquery call in your header like so:

<title></title>
<link href="../CSS/stylesheet.css" rel="stylesheet" type="text/css">

Chrome does have a switch to enable this, it's quite easy to turn on. You'll need to make sure Chrome is closed completely, and run chrome with the '–allow-file-access-from-files' flag. Ie:
C:\Users\\AppData\Local\Google\Chrome\Application>
chrome --allow-file-access-from-files
To see if the flag is set, you can visit:  chrome://version/ and look at the Command Line section and you should see –allow-file-access-from-files
You'll most likely need to run this with at least admin access, and I would caution visiting unknown sites with this setting on, as they could capitalize on your setting and potentially read local files.
Comment: please list your entire HTML page. I cannot assist further without it. Edit your original post with that data.
Comment: Still won't do..

Is what it looks like now, and it won't change a thing... Do I link to a working JQuery, or does that even matter?

Thanks for the quick reply btw, much appreciated!

Didn't know how to make code block in comment apparently..
Comment: I've done that. Still seems to have no effect though. Should I try linking to another library?
Comment: right click your page and click inspect element. Click console tab and then reload the page with that open. Post the error message
Comment: "Not allowed to load local recouce"

All files is from my own PC except from the JQuery library.
Comment: ah! You are developing locally I assume? You are using Chrome as well?
Comment: Indeed I am. I just read about the problem where I have to give access to local files, which would in the end result in lack of security..
Should I just switch over to Firefox when doing it locally then?
Comment: You can do that. it should work. Not guaranteeing it. Or you can enable it and disable it as soon as you know it works.
Comment: Out of curiosity, are you developing without a server @JensDissingPoulsen?
Comment: Switching seems to be more of a real solution, until they fix it, if they do.
Last question. Would I have to do same procedure in FF and if so how?

Thank you very much for your help so far!

Noah, as of now yes. It is my plan to have a server running in 2-3 days. But I didn't even think to run into a problem like this. At the moment it is only a hobby. It would be necessary to do it off a server, you think?
Comment: Not necessary, but I'm pretty sure that this problem is because you're running your HTML without one. I did a little research, and came up with a stack overflow link that should answer your question. It's right below @JensDissingPoulsen.
Answer: I am not sure that you're running a local server and if you are, then this answer is completely incorrect. However, I am guessing that you are not. Therefore, in Chrome, you can either enable the –allow-file-access-from-files flag, or you can use the file:/// protocol like so. The link below should address your question.
How can I create a link to a local file on a locally-run web page?
Personally, I would suggest running files from a server - if you aren't already -  as I have never run into this problem using one. Wamp (Windows), Mamp (OSX) are ones that I've found reliable.
Comment: Allright, seems I might as well set it up through the server then. It should fix all my heartaches!
Thank you very much for your help!

JQuery in HTML doesn't do anything


CHKCONFIG NOT working on UBUNTU 12.04.4

Question: I am trying to install chkconfig in Ubuntu 12.04.4 but it is not installing.
I have tried most of the solutions available like
apt-get install sysv-rc-conf
update-rc.d

All of the above is giving the below error

"Package is not available, but is referred to by another package... E:
  Package 'chkconfig' has no installation candidate".

I am clueless now what to do as I have to install and enable the ssh ....
any other solution to enable and start the SSH...???
Comment: Oh yes that was the problem as soon as enabled Software sources everything worked fine......
Comment: I am writing it as an answer, mark it accepted if it solved your problem.
Answer: As you can see here http://packages.ubuntu.com/lucid/sysv-rc-conf that package is in the universe repository.
Make sure you have a line in your /etc/apt/sources.list that looks like this:
deb http://en.archive.ubuntu.com/ubuntu/ lucid universe

Then run apt-get update to update your package list.
The package should then be installable.
Answer: Packages you are trying to install (i.e chkconfig and sysv-rc-conf ) are in Universe Repository ( chkconfig, sysv-rc-conf ).
So you have to enable the Universe Repository so that you install software from it.
To enable it

Open Software Sources
Under Ubunut software tab ,check the option "Community-maintained free and open-source software (universe).

Now Run sudo apt-get update.

CHKCONFIG NOT working on UBUNTU 12.04.4


Quiz maker for revision based on user's needs

Question: I'm looking for WP plugin or any external toll. I have a LMS webpage with several courses. I would like to have a chance for my users to create quiz with questions for revision. In this quiz generator, users should be able to choose questions from different categories, choose number of questions and do this quiz as many times as they want.
For example:
My user wants to generate quiz which includes questions from Geography, Math and Science. He wants 100 questions in total. I will have a database of my questions. This toll should generate a quiz based on user needs (categories, number of questions).
I was looking for more than 2 hours and I did not find anything that suits my needs. Does anyone know anything that can help me?
Thanks a lot in advance
Answer: try these Plugins for WordPress 1)LearnDash, 2)WP Quiz .https://wordpress.org/plugins/wp-quiz/
Answer: Also looking for a similar plugin, came across a couple of interesting ones. Maybe they'll suit you too - Quiz Maker, Riddle Quiz https://wordpress.org/plugins/quiz-maker/
Comment: This is a link-only answer. Please don't post under questions asking for tool recomendations.


Count and name content from a SQL Server table

Question: I have a table which is structured like this:
+-----+-------------+-------------------------+
| id  |    name     |        timestamp        |
+-----+-------------+-------------------------+
| 1   | someName    | 2016-04-20 09:41:41.213 |
| 2   | someName    | 2016-04-20 09:42:41.213 |
| 3   | anotherName | 2016-04-20 09:43:41.213 |
| ... | ...         | ...                     |
+-----+-------------+-------------------------+

Now, I am trying to create a query, which selects all timestamps since time x and count the amount of times the same name occurs in the result.
As an example, if we would apply this query to the table above, with 2016-04-20 09:40:41.213 as the date from which on it should be counted, the result should look like this:
+-------------+-------+
|    name     | count |
+-------------+-------+
| someName    |     2 |
| anotherName |     1 |
+-------------+-------+

What I have accomplished so far is the following query, which gives me the the names, but not their count:
WITH screenshots AS
(
    SELECT * FROM SavedScreenshotsLog
    WHERE timestamp > '2016-04-20 09:40:241.213'
)
SELECT s.name
FROM SavedScreenshotsLog s
INNER JOIN screenshots sc ON sc.name = s.name AND sc.timestamp = s.timestamp
ORDER BY s.name

I have browsed through stackoverflow but was not able to find a solution which fits my needs and as I am not very experienced with SQL, I am out of ideas.
Answer: You mention one table in your question, and then show a query with two tables.  That makes it hard to follow the question.
What you are asking for is a simple aggregation:
SELECT name, COUNT(*)
FROM SavedScreenshotsLog
WHERE timestamp > '2016-04-20 09:40:241.213'
GROUP BY name
ORDER BY COUNT(*) DESC;

EDIT:
If you want "0" values, you can use conditional aggregation:
SELECT name,
       SUM(CASE WHEN timestamp > '2016-04-20 09:40:241.213' THEN 1 ELSE 0 END) as cnt
FROM SavedScreenshotsLog
GROUP BY name
ORDER BY cnt DESC;

Note that this will run slower because there is no filter on the dates prior to aggregation.
Comment: I had the same idea, but was also thrown off by the wording of the question.
Comment: Wow, way easier than I expected it to be. Guess I overthought it a bit, thank you!
Comment: Is there an easy way to include `0` values of `COUNT` in the result?
Answer: CREATE TABLE #TEST (name varchar(100), dt datetime)

INSERT INTO #TEST VALUES ('someName','2016-04-20 09:41:41.213')
INSERT INTO #TEST VALUES ('someName','2016-04-20 09:41:41.213')
INSERT INTO #TEST VALUES ('anotherName','2016-04-20 09:43:41.213')

declare @YourDatetime datetime = '2016-04-20 09:41:41.213'
SELECT name, count(dt)
FROM #TEST
WHERE dt >= @YourDatetime
GROUP BY name

I've posted the answer, because using the above query can generate errors in converting the string in where clause into a datetime, it depends on the format of the datetime.
Comment: apart from table variable this query is lifted from gordon linoff Answer
Comment: Try to change your default datetime format and apply the query it won't work. I added the reason I've posted the answer. Of course it's almost the same as the answer above, it's a very simple query you can't have many best practice answers.


Verify a bare Git repository has data

Question: How does one verify that files were pushed to a bare repository correctly? Since bare repositories have no working tree, you obviously can't do a simple git log because it isn't picked up as a git repo.
I realize there are solutions like suggested here, but I'd like to know how to do it using the command line.
Comment: Note that I'm not looking to see *what* is in it; simply that there *is* something in it (i.e. not an empty bare repo)
Comment: `git log` doesn't even look at the workspace, it should work just fine in a bare repository.
Answer: git log works just fine.  Bare repositories are still recognized as repositories.  Obviously.  :)
git@koiru /var/git/repositories/sanpera.git $ ls
total 37k
-rw-r--r--   1 git nogroup 1.2k Mar  1 06:00 FETCH_HEAD
-rw-r--r--   1 git nogroup   23 Sep 14  2011 HEAD
drwxr-xr-x   2 git nogroup 4.1k Sep 14  2011 branches/
-rw-------   1 git nogroup  236 Jun 12  2012 config
-rw-r--r--   1 git nogroup   34 Jun 12  2012 description
drwxr-xr-x   2 git nogroup 4.1k Jun 12  2012 hooks/
drwxr-xr-x   2 git nogroup 4.1k Sep 14  2011 info/
drwxr-xr-x 222 git nogroup 4.1k Sep  9 06:00 objects/
drwxr-xr-x   5 git nogroup 4.1k Oct 18  2011 refs/

git@koiru /var/git/repositories/sanpera.git $ git log
commit a60f2ad3cc118eb7fd290be56448bcef82fe8252
Author: Eevee <email@example.com>
Date:   Sun Sep 2 18:22:50 2012 -0700

    Stub a few more tests.

...

Comment: I'm getting a `fatal: bad default revision 'HEAD'`
Comment: And yea, the "obviously" bit was a bit snarky. I should have worded that better ;)
Comment: having no `HEAD` sounds like a pretty good indication that you _don't_ have any data.  check the `refs/heads` directory; that lists all the branches.  if it's empty, you got nothin'.
Comment: VonC's answer *did* show there was a correct branch. I had forgotten to pull all of the branches before I pushed back to another remote.
Answer: You could try and use git ls-remote:
 git ls-remote http://www.kernel.org/pub/scm/git/git.git

 # or, also a bare repo
 git ls-remote https://github.com/git/git

As long as it doesn't return just the emtpy tree SHA1, that should mean there are commits in that upstream repo.
Comment: Perfect! This worked perfectly. Note that this also works with `ssh://` protocol URLs.

Verify a bare Git repository has data


Norm of an operator in $\ell^p$

Question: We define the operator: $l^p$ to $l^p$ with the $p$-norm
$T( (a_{n} ))= a_{n+1}-a_{n}$ So its like:
$(a_1,a_2,a_3.....)$ goes to $(a_2-a_1,a_3-a_2....)$
They re asking me about the norm of the operator, first I see that $|| (1,0,0,0...) ||_p=1$ and $|| T((1,0,0..)=1 ||_p$ so the norm is more or equal than 1. But for proving that the norm is less or equal than 1 I have a problem, because $|| a_{n+1}-a_{n} ||_p$ I can see for triangle inequality that is less or equal than 2 but not that 1. Thank you
Comment: Think about the sequence $x_1=(1,0,0,\ldots), x_{2} =(1,-1,0,0,\ldots), x_{3}=(1,-1,1,0,0,\ldots),\ldots$. What do you get?
Comment: This sequence doesnt have norm less or equal than 1 for every n, for n=2 the norm is 2^(1/p)
Comment: Dear user Energy, the norm of an operator is $\sup ||Tx||/||x||$, there is no problem if the norm of the elements in the sequence is greater than 1, you can always divide by $||x||$.
Comment: Thanks, I was using another definition of norm, I know both are equivalent, but for proving that it could be more complicated, with this definition it everything correct now :)
Answer: Define $a_n:=c^n$ where $\left|c\right|\lt 1$. Then $\left|a_{n+1}-a_n\right|^p=c^{np}\left|c-1\right|^p=a_n^p\left|c-1\right|^p$, which gives that $\left\lVert T\left(\left(a_n\right)_{n\geqslant 1}\right)\right\rVert =\left|c-1\right|\left\lVert\left(a_n\right)_{n\geqslant 1}\right\rVert  $. We thus obtain that $\lVert T\rVert\geqslant\left|c-1\right| $ for each $c\in (-1,1)$. Now let $c\to -1$ to get the result.

Norm of an operator in $\ell^p$


Ubuntu 12.04 using UEFI

Question: I want to upgrade my machine with a new Motherboard, RAM and Processor.
I am planning on doing a clean install of Ubuntu 12.04.
The Motherboard I want to use is an
Asrock 970 Extreme4 which uses an AMI 32 MBit UEFI BIOS.
My Question is, is there anything I have to watch out for during the installation process? Cause I have read that some people have trouble booting into ubuntu using a UEFI BIOS. Any advice? I don't want to spend all that money for the different parts only to find out that I can only use windows properly.
Thanks in advance
Answer: IMHO, Ubuntu creates an EFI System Partition (ESP) that's a fraction of its proper size. I recommend creating an ESP in the range of 100-500 MiB, depending on various factors; but Ubuntu tends to make them under 50 MiB, IIRC. Ubuntu also creates FAT-16 ESPs, but the Windows installer flakes out when presented with FAT-16 ESPs -- it wants to see a FAT-32 ESP. These problems can be overcome by pre-partitioning (or at least creating the ESP ahead of time). Be aware, though, that Ubuntu 11.10 and earlier always erase the ESP, which wipes out other OSes' boot loaders. This problem has been fixed with Ubuntu 12.04. Thus, for an EFI install, I strongly recommend Ubuntu 12.04 over earlier versions.
Answer: None that I ran into.  The only issue I had was when I first installed, it crapped out because the uefi system picked up the dvdrw that it booted off of.  Once I went in and told it that it was the main boot device, it worked fine.
Comment: I have mostly the same experience with 11.10. One may probably watch out to boot the live CD in uefi mode, apart from that there should be nothing to worry about.
Answer: I just got an ASUS K55a laptop with win7 home premium on it.
I unplugged the hard drive, plugged in a flash drive and proceeded to install Linux Mint (Ubuntu Derivative).
The flash drive worked.
I plugged the HD back in and started the computer.
Windows crashed and forced me to reformat and reinstall, leaving linux inoperable.
The laptop has uefi on it.
I wanted to select which drive I wanted to boot from during computer startup but apparently this only works with an older computer.
I don't want or need a boot manager when I can select which to boot from on my own.
Is there a way for me to do this without windows crashing?
I have to keep win7 until the warranty runs out in a year. But I can run Linux all I want as long as I don't fool with the hard drive.
I don't want to run from CD/DD as it is too slow.
And I am scared to access the hard drive from Linux let alone try to save anything to it.
I suggest that you Pull the windows drive out and put in an ssd drive for linux. Switch when needed.
A hassle yes, but at least you don't have to worry about windows getting sick.

Ubuntu 12.04 using UEFI


How to get scanner object to ask for more than 1 int?

Question: I am making a lottery game and I am trying to get the console to allow the user to enter 6 numbers but it only allows the user to enter 1 before it compares them to the random numbers.
Is there any way to allow the user to enter the 6 numbers without creating new int variables and than compare them to the random numbers generated?
I have the particular issue highlighted with a commented with a * icon.
Here is my code.
for (int i = 1; i <=6; i++) {
        Random run  = new Random();
        LottoNumbers.add(i);
        run.nextInt(49);
        //Get Users Lotto Picks
        //*Console will not ask for 6 numbers
        Scanner scan = new Scanner(System.in);
        int lottopick = scan.nextInt();

        //prevent user from picking number higher than 49
        if (lottopick > 49) {
            System.out.println("You canonl pick numbers between 1 and 49");
        }
        //Compare User selection to random numbers generated
        System.out.println("Enter Your Six Numbers between 1 and 49");
        if (lottopick == run.nextInt(49)) {
            System.out.println("Millionaire");
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));

        }
        else {
            System.out.println("You lose");
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
            System.out.println(run.nextInt(49));
        }
}

Please don't go ahead and make the full app because I will never learn otherwise. Thanks
Comment: "Is there any way to allow the user to enter the 6 numbers without creating new int variables" Is there a way to park 6 cars in one parking space?
Comment: @hexafraction I was looking for way to avoid creating too lines and making my code unreadable. Thanks
Answer: Since, every input asks the same question, you should use a for loop and an array of inputs:
Scanner scan = new Scanner(System.in);
int[] lottopick = new int[6];

for(int i = 0; i < lottopick.length; i++) {
  System.out.println("Enter next lottery number: ");
  lottopick[i] = scan.nextInt();
}

Comment: Thanks Manish. That was the kind of answer I was looking. My code was getting a bit long
Answer: There are several ways to do it, first you need to decide how will you take input from user, here are some ways of doing it:

Ask user to enter a single string of comma seperated values and then split this string to get all integers.
User input a number and press enter and do same for n number of times.

Cheers !!
Comment: Thank you very much for your help. It's good to see I was on the right track
Answer: Using scanner.nextInt() you can get only one number at time.

you need to give scanner how many times you want.

like
first = scanner.nextInt();
 second = scanner.nextInt();

you can give it in a For loop
for(int i=0;i<6;i++)
{
      array[i] =scanner.nextInt();
    }
you read string using Scanner
String s = scanner.next()

// String you can enter like 20,34,334,: After that you can split using ','
Comment: That seems pretty useful. Thanks
Answer: If you really want the input all on one line, you could get a string, split by the space and then parse the integers.
in psuedo-code:
Scanner scan = new Scanner(System.in);
string lottoNumbers;

lottoNumbers = scan.next();

stringChunks[] = lottoNumbers.Split(" ");

for(int x = 0; int < stringChunks.Size; x++){

    Integer.GetInt(stringChunks[x]);
}

emphasis on psuedo-code.
Comment: @new2code That's totally cool.  Do what you think is best.  I just wasn't sure if having the input be one line was more important than the input being integers.
Comment: @new2code I know the feeling. I'm sure the other posters in this thread would appreciate the up-votes as well, so I threw your question an upvote to get you to 15.  It might not be a "pearl" question, but it was clear, and contained what we needed to answer it, so I think it was a good question.
Comment: I am not aiming for using strings at the moment but thanks for showing me that technique. Always good to see more way to skin that cat. Thanks dckuehn.
Comment: at the moment, it is just integers until the game mechanics are right. I will refine it than after if I am feeling up for it. Thanks so much for your response. I would upvote you but alas Stack Overflow deems my reputation unworthy. Thanks again


CSS Transform conflict with fixed element

Question: Follow up on this topic
When I apply css transform to parent element, child element is not fixed anymore.
http://jsfiddle.net/z8fBD/7/
have tried using only one direction transform but no success.
when you remove transform: translate(0%,0px); everything works just fine, but as you will understand from previous topic, I need this for my animation
Answer: Do you mean the move 'button' should stay put? If so, you need to apply the transform to the container element since the body (you should consider renaming this div) will transform all its children. Here are the changes to do that:
JS:
jQuery(document).ready(function($){
    $('#move').click(function(){
        if(!$('#container').hasClass('move')){
            $('#container').addClass('move');
        } else {
            $('#container').removeClass('move');
        }
    })
})

CSS:
#body {
    position:absolute;
    left: 0;
    top:0;
    width: 200px;
}
#container {
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    -ms-transition: all 0.5s ease;
    transition: all 0.5s ease;
    -webkit-transform: translate(0%,0px);
    -moz-transform: translate(0%,0px);
    -ms-transform: translate(0%,0px);
    -o-transform: translate(0%,0px);
    transform: translate(0%,0px);
}
#container.move {
    -webkit-transform: translate(150%,0px);
    -moz-transform: translate(150%,0px);
    -ms-transform: translate(150%,0px);
    -o-transform: translate(150%,0px);
    transform: translate(150%,0px);

The rest of the CSS stays the same. Note how styles that were on the body were moved to #container.


Entity Framework always includes data that is in context even if I don't ask for it

Question: I am using MVC.NET web api, EF with DB first, and I have lazy loading turned off on my context. EF is returning way too much data, even with LazyLoading turned off.
For example, I have Users with one Role. When I query for Users and Include Role, the Role.Users property is automatically filled with data since Users have been loaded into the context.
Why can't I get EF to give me JUST what I request? Or am I missing something big here?
public partial class User
{
    public int UserID { get; set; }
    public string Title { get; set; }
    public string Email { get; set; }
    public int RoleID { get; set; }

    ....

    public virtual Role Role { get; set; }
}

public partial class Role
{
    public int RoleID { get; set; }
    public string RoleName { get; set; }

    ....

    public virtual ICollection<User> Users { get; set; }
}

return db.Users.Include(u => u.Role);
// ^^ user.Role.Users is filled with 1000s of users

TL;DR - I want EF to never load data into navigation properties/collections unless I .Include() it directly. When serializing to JSON I want just what I ask for explicitly. It seems that even with lazy loading off, navigation properties that are already in the context (ie usually "circular references") will be loaded and returned.
Comment: Just a small heads-up.  Lazy-loading means it will only load what it needs when it needs it... turning that off is counter-intuitive for what you're looking for.
Comment: `with LazyLoading turned off` -- erm, isn't that *eager loading*?
Comment: From what I understand and have tested - lazy loading means when you access a property on an entity that is a collection, it loads that collection. I have it off because I don't want it to load anything besides what I tell it to include. My issue is that even with this turned off, it still includes collections that have been loaded in the Context, so Users have one Role, and Roles have many users as a navigation property, and it is already loaded with 1000s of users even though I didn't tell EF to include it.
Comment: Can you post code - your model plus the data access code.
Comment: @chris1234p no you told it to not be lazy... being "not lazy" means that it should load all at once thus not waiting till it might be needed (on first access of the collection)... which in turn is "eager loading" (opposite of "lazy loading").
Comment: Wow, so with lazy loading off, you are saying that if I select one User without .Including anything, it is going to load the entire graph ? What kind of loading do I need where I just load what I explicitly tell it?
Comment: No it's not like this, lazy loading will load data whenever you access it, when eager load will load it straight away when you create your select command. Anyway, you are getting these data just because you accessing it, if you would not touch these properties EF will not load them from DB. You should play around with SQL profiler to take a look when and which queries are executed.
Comment: I have the same problem as @chris1234p. In my case, I'm trying to load a list of comments, and each comment has a parent comment. The parent comments are being populated (against my wishes), and it's as though EF has declared open season on that table as soon as I touch it for the first time. I do not experience the same problem with other relationships that are not yet "in scope", e.g. author.
Answer: The behaviour your are seeing is called Relationship Fixup and you cannot disable it.
If you are loading users with roles to serialize them and sent them to somewhere I guess that you don't want to track changes of entities in the context they have been loaded in. So, there is no need to attach them to the context and you can use:
return db.Users.Include(u => u.Role).AsNoTracking();

Or use a projection into an object specialized for serialization, as suggested by @STLRick.
Comment: For some reason when I tried AsNoTracking, I would get errors during serialization.
Comment: @chris1234p: Maybe ask a new question and describe those errors. I was focussing on your question how you can avoid that all navigation properties between entities are populated.
Answer: You can select only what you need by using Select().
var users = _db.Users.Select(x => new
{
    UserID = x.UserID,
    Title = x.Title,
    Email = x.Email,
    RoleID = x.RoleID
}).AsEnumerable();

Answer: You are right that with lazy loading on, you will get back navigation properties because they are "touched" by the serializer which causes them to be loaded.  Lazy loading should be off if you want the properties to come back as null.  That said, it "seems" that once entities are loaded into the context (through other queries, for example), they will be processed by the serializer.  So the answer is to tell the serializer not to return the navigation properties. The best way I've been able to find to do this is to use DTOs (Data Transfer Objects).  This allows you to return exactly the data you want rather than your actual entities.
Your DTO might look something like this:
public partial class UserDto
{
    public UserDto(user User)
    {
        UserID = user.UserID;
        Title = user.Title;
        //... and so on
    }
    public int UserID { get; set; }
    public string Title { get; set; }
    public string Email { get; set; }
    public int RoleID { get; set; }

    //exclude the Role navigation property from your DTO
}

...and then you could do something like this:
return db.Users.Include(u => u.Role).Select(user => new UserDto(user));

Answer:
I don't want it to load anything besides what I tell it to include.

It looks like you need to use Explicit Loading. Basically, you could load the specific entities like this:
context.Include("Roles")

To my best knowledge that should not include related entities. Lazy loading should indeed be disabled and you could load navigational properties explicitly with Load.
Comment: Hello Serge, that is what I am doing, but it seems that in order for this to include only what I tell it to include, I need to use a brand new context. Otherwise if data is already in the context, it will be loaded in the data that is returned, even if I don't ask for it. It is like it is trying to "help" me by giving me stuff that I don't ask for.
Comment: If part of the requirement is wanting the objects to still be attached to the context and therefore updateable and such, then this is a better solution than mine below.  Make sure you always include the things you need; if you do, I agree with Serge, this will probably get you closer to what you want.
Answer: First: Turn Lazy Loading on.
Second: If you want to filter down what you retrieve and return, then do a custom return object or something.
from u in db.Users
join r in db.Roles
  on u.RoleID equals r.RoleID
select new { u.UserID, u.Title, u.Email, r.RoleName }

Or something like that.  You will have a minimal return object and your object graph will be tiny.
Comment: with lazy loading on you will get back navigation properties because they are touched by the serializer.


Next.js ISR pass additional data to getStaticProps from getStaticPaths

Question: In SingleBlogPost.jsx i have:
export async function getStaticPaths() {
  const res = await fetch("http://localhost:1337/api/posts");
  let { data } = await res.json();

  const paths = data.map((data) => ({
    params: { slug: data.attributes.slug },
  }));

  return {
    paths,
    fallback: "blocking",
  };
}

where I generate blog pages by their slug.
But then in getStaticProps I need to fetch single post by slug but I want to do it by id.
export async function getStaticProps(context) {
  console.log("context", context);

  const { slug } = context.params;

  console.log("slug is:", slug);
  const res = await fetch("http://localhost:1337/api/posts");
  const { data } = await res.json();

  return {
    props: {
      data,
    },

    revalidate: 10, // In seconds
  };
}

And I want to keep url like /blog/:slug  , I dont want to include id. in url .When I already fetch all posts in  getStaticPaths how I can access post id in getStaticProps to avoid fetching by slug?
Comment: Take a look at this thread, some useful answers are posted [here](https://github.com/vercel/next.js/discussions/11272)
Answer: It looks like recently released a workaround using a file system cache.
The crux of the solution is that they save the body object in memory, using something like this:
this.cache = Object.create(null)
and creating methods to update and fetch data from the cache.
Discussion here: https://github.com/vercel/next.js/discussions/11272#discussioncomment-2257876
Example code:
https://github.com/vercel/examples/blob/main/build-output-api/serverless-functions/.vercel/output/functions/index.func/node_modules/y18n/index.js#L139:10
Answer: You can filter your API response by your slug to get the same result
const res = await fetch(`http://localhost:1337/api/posts?filters[slug][$eq]${slug}`);

This will generate your desired result
Answer: I found a concise work around that uses the object-hash package. I basically create a hash of the params object and use that to create the tmp filename both on set and get. The tmp file contains a json with the data I want to pass between the two infamous static callbacks.
The gist of it:
function setParamsData({params, data}) {
  const hash = objectHash(params)
  const tmpFile = `/tmp/${hash}.json`

  fs.writeFileSync(tmpFile, JSON.stringify(data))
}

function getParamsData (context) {
  const hash = objectHash(context.params)
  const tmpFile = `/tmp/${hash}.json`

  context.data = JSON.parse(fs.readFileSync(tmpFile))

  return context
}

We can then use these helpers in the getStaticPaths and getStaticProps callbacks to pass data between them.
export function getStaticPaths(context) {
  setParamsData({...context, data: {some: 'extra data'})

  return {
    paths: [],
    fallback: false,
  }
}

export function getStaticProps(context) {
  context = getParamsData(context)

  context.data // => {some: 'extra data'}
}

I'm sure someone can think of a nicer API then re-assigning a argument variable.
The tmp file creation is likely not OS independent enough and could use some improvement.
Comment: It's nicer to use https://www.npmjs.com/package/node-fetch-cache if you are fetching data over HTTP.


Replacing attic light switch with Leviton combo

Question: I want to replace and old Leviton attic light switch with a Leviton combo switch/outlet. The junction box has two Romex cables in and one out to the current light.
The two in have each a black wire going into to the push-in terminals of the switch and one black one connected to a side screw going to the light. Why would there be two romex cables with two black wires going into the switch? How would I install the combo switch with this wire config? The grounds are just wire nutted together (all three). Thanks for the help.

UPDATE:
Here is a better shot of the back of the old switch with some labels:
CORRECTION... New diagram here:

Based on the updated diagram above... Romex 1 from bottom of box has the shepherd's hook and was attached to the screw... Romex 2 from bottom of box was pushed-in to the bottom of switch... Romex 3 goes to the light through the top of the box from the push-in connection at the top of the switch.
And here is the switch I'm needing to install:
https://www.homedepot.com/p/Leviton-15-Amp-Combination-Switch-Outlet-White-5225-WS/202077623?cm_mmc=Shopping%7CG%7CVF%7CD27E%7C27-2_WIRING_DEVICES%7CNA%7CPLA%7c71700000033102358%7c58700003867202208%7c92700031090651054&gclid=EAIaIQobChMI9taWn6eO4AIVQR-GCh1zkAC4EAQYAiABEgIIjvD_BwE&gclsrc=aw.ds
FINAL UPDATE... SUCCESS!!
Thanks to ThreePhaseEel (accepted answer) and Harper.
Comment: Then Romex 1 must be the line connection, and Romex 2 leads off to something else that is being turned on and off by this switch...can you figure out where that leads?
Comment: Can you post a better shot of the connections to the switch?
Comment: Just posted a new photo of the back of the switch with some labels... Thanks again
Comment: What does Romex 2 run off to?
Comment: There are 2 Romex running into the bottom of the box... One black going to push-in terminal 1 and the other Romex black going into push-in terminal 2... The 3rd Romex is going to the light... You can see the 2 Romex at the bottom in the photo https://i.stack.imgur.com/mtwPZ.jpg
Comment: No, I'm asking what's at the *other* end of Romex 2 here...
Comment: I'm not sure... This is an attic switch and the two Romex cables are coming in apparently from the main circuit box... The switch doesn't operate anything else but the single attic light.
Comment: That makes me think Romex 2 and 3 are the line connections, and romex 1 is the load...
Comment: Romex 3 with the shepherds hook definitely leads to the light... is it possible 1 or 2 don't do anything? how would you approach changing this out for the combo?
Comment: You were totally right... Based on the updated diagram above... Romex 1 from bottom of box has the shepherd's hook and was attached to the screw... Romex 2 from bottom of box was pushed-in to the bottom of switch... Romex 3 goes to the light through the top of the box from the push-in connection at the top of the switch.
Answer: Romex 1 and 2 are using backstabs, which is not a good idea for other reasons.
The backstab is simply connected to the screw nearest it, internal to the device.  It's supposed to be an "either-or", but some people like to use it to splice the 2 wires together.
It would be the same as if the two wires were joined at a wire nut, with a pigtail from there to the device screw.  That is exactly what you should change that to.
On a switch
One side is always-hot, and the other is switched hot to the lamp.  There would be no reason to have 2 cables feeding switched-hot.  Unless you had 2 lights.
It would be very common, however, to have multiple always-hot wires in a box; the second one would be going onward to other loads.
The grounds are nutted together ordinarily.  The neutrals likewise, you may be adding a wire to this neutral bundle to power the smart switch.
How I would hook it up.
First I would get some red electrical tape and mark the wire to the lamp with red tape.
A switch-outlet hooks up exactly like a smart switch, but without the convenient pigtails.   So I would make pigtails.
Get about 7" of 12/3 cable.  14/3 will work if you are sure all the wires in the box are #14. Tear off the sheath to salvage the wires.  Then:

bare wire to the green screw
white wire to the silver screw
red wire to the brass screw right next to the silver screw
black wire to one of the black screws on the other side

Then I'd join all the wires color to color, remembering you marked the lamp black wire red.  Normally you can't count on wire color codes, but I made it work here.
There are more efficient ways to do this, but they are not as clear.
Comment: /2 Doesn't have a red in it, but you can just use more of it and mark a black red.   Also if you use 14/ make sure your breaker is 15A.
Comment: How would you approach replacing it with this switch: https://www.homedepot.com/p/Leviton-15-Amp-Combination-Switch-Outlet-White-5225-WS/202077623?cm_mmc=Shopping%7CG%7CVF%7CD27E%7C27-2_WIRING_DEVICES%7CNA%7CPLA%7c71700000033102358%7c58700003867202208%7c92700031090651054&gclid=EAIaIQobChMI9taWn6eO4AIVQR-GCh1zkAC4EAQYAiABEgIIjvD_BwE&gclsrc=aw.ds
Comment: Would 14/2 cable work?
Answer: You're in luck!
The fact there are two cables here is a good thing, since it means neutral is available at this box.  The wiring here goes as follows:

The always-hot black wires get nutted together and with a black pigtail of appropriate gauge -- this pigtail then goes to a black screw on the switch/receptacle combo
The switched-hot black wire goes to the brass screw on the switch half of the combo
The neutral bundle gets a white pigtail nutted in with it, which goes to the silver screw on the receptacle half of the combo
The ground bundle gets a bare or green pigtail nutted in with it, which goes to the green grounding screw on the device

Once it's all wired up, you can then button things up, turn the power back on, and enjoy your new receptacle!
If you want a switched receptacle
If you want the receptacle to be controlled by the switch, the wiring is actually no harder than an always-hot receptacle.  Simply keep the neutral and ground wiring the same, but swap the always-hot and the switched hot so that the always-hot pigtail goes to the brass screw on the switch end and the switched hot goes to one of the black screws.
Comment: @mm-93 yes, you are correct
Comment: Is this describing a separate feed where the outlet is always on and the light switch controls the light independently? What if I want to have a common feed where the light switch controls the outlet?
Comment: @mm-93 -- this is describing a separate feed.  Why do you want a switched receptacle here? What are you planning to plug into it?
Comment: Just an extension cord for extra lights where I need it in the attic... I'm running CAT6 cable... I just need an outlet to be available in the attic (instead of always running an extension cord from the garage) and don't care if the switch operates it... in fact the switch will always be turned on when I go up there and turned off when I leave. Is it easier to wire a common feed? (I.e no pigtails needed?)
Comment: The common feed is easier to wire -- you'd need to break the tab and use a pigtailed jumper if you wanted the outlet to be switched
Comment: I thought common feed you keep the fin: https://www.doityourself.com/forum/attachments/electrical-ac-dc/8906d1360173837-new-receptacle-break-off-fin-leviton.jpg
Comment: Oh, *laughs* You can keep the fin in a common feed configuration -- I had my head turned around from the manufacturer wiring diagrams
Comment: Ha no sweat, I appreciate the assist today
Comment: In your description, "The switched-hot black wire" that's the black wire (with shepherds hook) that goes to the lamp right? From my diagram above https://i.stack.imgur.com/IuSYA.jpg Romex 1 and 2 would get nutted together with a pigtail that then goes to a black screw... Romex 3 would then go from the brass screw to the lamp?
Comment: One last thing, if I wanted it to be common feed (switch controls the lamp and the outlet), how would your instructions change?
Comment: Ah I see your additional instructions... So the "always-hot goes to the brass screw" is to the light right? And when you say "switched hot goes to one of the black screws." Is that combining Romex 1 and 2 and using a pigtail to a black screw? Do I need to combine those two?
Comment: @mm-93 -- switched-hot is still Romex 3, always-hot is still Romex 1 + 2
Comment: OK got it thanks... I'm making progress... I just pig-tailed the white bundle to the silver screw... And pig-tailed the ground bundle to the green screw... My last question is... You said "always-hot goes to the brass screw on the switch end and the switched hot goes to one of the black screws."... Since there are two "always hot" do I nut those together with a pig-tail with the pig-tail going to the brass screw? (i.e. do I nut Romex 1 and 2 together + pig-tail??)
Comment: @mm-93 -- yes :)
Comment: Success! Just updated the original post with a new image https://i.stack.imgur.com/IsAr4.jpg and accepted your answer. It's working great and thank you for your patience and expertise!


When do enemy armies get an extra turn?

Question: In the PC version of Romance of the Three Kingdoms XI, all enemy factions/armies get an entire extra turn at some point. This happens perhaps once per scenario/game. Enemy units can be observed to move and attack twice.
Why does this happen?
Can it be predicted?
Can it be avoided?
Comment: Can you claify?  The enemy side gets an entire extra turn (as in all their armies move), or are you asking of a particular unit gets an extra turn (or extra attack?).
Comment: I'll may dig up my copy of RoTKXI later to try to replicate.  I don't remember this happening but its been years since I played this game.
Comment: I can't seem to reproduce this.
Comment: Well, you have to play for hours, and it's not exactly announced to you. You're in a battle, planning your next move as the AI takes his turn(s), and suddenly they're moving again.
Comment: It may have to do with the number of action points (APs) you have remaining, or that you and the AI have relative to one another. That would make sense, wouldn't it?* But I see no mention of this behavior in the Help.

*If you end your turn with 0 points, then the AI takes a turn and has 100 points left, I can see the reasoning behind it. I have never gotten an extra turn, but sometimes my AP suddenly skyrockets.
Comment: I have played the PC version twice till the end and there no issue like that.
Comment: I just saw it again yesterday. I'm playing Ma Chao, and Cao Pi's armies froze in place while first Liu Bei and then I attacked. Nothing with a blue flag moved.

So it's pretty clear to me that this does in fact occur.
Answer: The double move is just due to the ordering of turns.  If you take your turn before the enemy, then they take their turn the next month before you, it will seem like they just got a double turn.  But everyone still moves just one turn per month.
Comment: Hmm. That's possible. But why would that happen at all? And that would mean that _I_ would then get a double turn, which does not seem to happen.

There's definitely something "off" about the way the game calculates points, especially when I hold a council. But while I might not notice if I were handed a new turn's set of action points, I would certainly notice if I had a new list of moveable units when I thought my turn was over.

But it could still be that I don't see the enemies' lack of movement because I'm looking elsewhere or I walked away.
Comment: @Alveric I did manage to reproduce this last night and that's what it seemed like to me, the enemy had 2 turns between my turns.
Comment: Aha! Well, thanks for confirming this behavior. I do suspect it has to do with under- or over-using your APs. Possibly it's meant to compensate the AI.

Do you ever see miscalculated points? (i.e., a long string of numerals instead of the actual remainder) after a council?
Comment: @Alveric nope, I've never seen that.  Though I tend to keep my APs under 100
Answer: AI does not get extra turn in ROTK XI, ever.  What you observed is an enemy unit movement followed by normal attack + another normal attack triggered by "Chain Attack" skill of the enemy officer.  Now, this double attack per turn does not trigger every time, but rather has about 50% chance to occur.
Also, some officers will assist other officers after they have already moved for that turn, which may seem like they are attacking twice, and even trice per turn.  Once again, both player and AI get to do stuff once per turn no matter what.
Comment: Thanks, but that is a different, individual event. As I said, ALL enemy factions/armies seem to get an ENTIRE extra turn in which they ALL move and attack. Or as restated, "the enemy side gets an entire extra turn (as in all their armies move)." See my last comment above for a likely explanation. It may have to do with conserved AI action points.

Note this is the same answer as below.
Answer: No they don't get an extra turn, but there are officers like "Bao Sanniang" if I remember correctly, that have an skill called "chain attack".
With these officers you have the probability of "attacking" twice in a single turn.
Regards
Comment: Right, but I'm talking about entire armies.

When do enemy armies get an extra turn?


Should auto.register.schemas create a new version in schema-registry on modifying .avsc?

Question: I've noticed a strange thing trying to follow a tutorial on Kafka schema-registry and a simple producer. It doesn't auto-generate new schema in schema-registry if I change the .avsc file. Steps I did:

Spin up a local schema-registry, Kafka and Zookeeper
Create .avsc file with 2 string fields
Create Java producer using KafkaProducer - I'm using avro-maven-plugin to generate a Java class out of the .avsc file.
Compile and run the producer - new Java class is generated and records are produced. Also, in the schema-registry a new entry appears.
Modify .avsc file - add a new field there
Compile - new Java class is generated with the new field. I add this field to the producer code.
Run the producer - no records are produced, no new version of the schema gets created in the schema registry but also I get no exception.

In the last step I expected the auto.register.schemas to create a new schema version, but it didn't. After I created it manually with curl in schema-registry, the records started to be produced correctly again.
I'm concerned that there was no Exception which made it hard to understand why the records are not produced.
Comment: Can you please share your producer code?
Answer: If you only called send method with one (or few) message, then that's not going to be immediately sent to the broker, you'll need to flush the producer to do that. Ideally, by adding a shutdown hook to the JVM
Schemas only need to be registered when records get sent and serialized
Comment: I send 10 records and flush, it flushes successfully without an Exception yet records don't appear.
Comment: So, if you run a consumer from the beginning of the topic, you see nothing? Maybe there is no exception logged because you dont have SLF4J setup?


How to activate auto indentation in Powershell ISE in windows?

Question: I am using Powershell ISE to write script in windows 7. While writing scripts I have to maintain indentation manually. I didn't find a way to auto indent the script.
Is there any way to perform/enable auto indentation in Powershell ISE or do we need to install any plugin for it?
Comment: If you don't mind spending a few bucks, ISESteroids will make you happy: http://www.powertheshell.com/isesteroids/
Comment: You could change Dan Ward's [PrettyPrinter Module](http://www.dtwconsulting.com/PS/Module_PrettyPrinterV1.htm) to edit and replace `$psISE.CurrentFile.Editor.SelectedText` instead of a file on disk
Answer: Vanilla PowerShell ISE doesn't support auto indentation, There are lots of 3rd party ISEs that support it.
Closest you will get in Vanilla PowerShell is the ability to indent multiple lines at once.
Put the caret where you want to indent Press Shift + Alt + Arrow Up or Down and it will create a line vertically across your rows of text. Press Tab and it will indent all those lines. This lets you indent whole code blocks and functions.
Comment: Ugh... What kind of IDE skips out on `source => format`?
Comment: The general excuse is that while the ISE has been getting trickles of features every release its not the focus of development and it will eventually be uplifted. There is a very good plugin for visual studio that adds PowerShell support that leverages all of the out of box VS features but I haven't used it. Maybe see if thats better.
Answer: Visual Studio Code is probably the best free editor (not only) for powershell scripts. Just open a .ps file with it and you will be suggested to install an appropriate powershell-extension. Then you have auto-format, instellisense, version-control-integration and you can run and debug the scripts from within the editor.
Comment: Doesn't seem to be any PowerShell formatting extension for VS Code. Have you found one?
Answer: Auto indentations in PowerShell ISE is not supported but if it's a one time formatting before you wrap up the script you can use an online solution like this one:
http://prettyprinter.de/
You just paste all of the code and click the "Pretty Print" button at the bottom.


Heroku Django app deployment fails after trying to install python requirement

Question: I installed django-user-visit with  pip install django-user-visit , tested it in my local environment and everything seems to work fine, but when i try to deploy my app to production with Heroku i get the following error :
remote:        Collecting django-cors-headers==3.6.0
remote:          Downloading django_cors_headers-3.6.0-py3-none-any.whl (12 kB)
remote:        ERROR: Could not find a version that satisfies the requirement django-user-visit==0.4.1 (from -r /tmp/build_940d12d0/requirements.txt (line 4)) (from versions: none)
remote:        ERROR: _No matching distribution_ found for django-user-visit==0.4.1 (from -r /tmp/build_940d12d0/requirements.txt (line 4))
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed

Does anyone know why Heroku can't find the package and if i can fix this ?
My packages are being installed by running the libraries indicated in my requirements.txt file:
asgiref==3.3.1
Django==3.1.5
django-cors-headers==3.6.0
django-user-visit==0.4.1
djangorestframework==3.12.2
gunicorn==20.0.4
psycopg2==2.8.6
pytz==2020.5
sqlparse==0.4.1
ua-parser==0.10.0
user-agents==2.2.0
whitenoise==5.2.0

What i've tried so far is to change the version to 0.4 and to not specify a version at all
Comment: What version of Python are you using? Do you have a `runtime.txt`?
Comment: https://pypi.org/project/django-user-visit/ requires Python >= 3.7. You need to use Python 3.7+ at Heroku.
Comment: Thank you Chris and phd, i guess that is my problem, Heroku is running 3.6.12 while my localhost 3.9, i will specify version 3.7 in my runtime.txt file
Answer: From the documentation: https://devcenter.heroku.com/articles/python-runtimes
If you're running a Python application that requires a different supported runtime, or if you simply want to lock your project against patch updates until you're ready to upgrade, you can specify which runtime to use for your app.
To specify a Python runtime, add a runtime.txt file to your app's root directory that declares the exact version number to use.
after that
pip freeze > requirements.txt


How to get a list of strings for a pandas dataframe?

Question: I have a dataframe which I obtain after doing certain operations. This is how my dataframe looks like
        date metric  stat         val       device
0 2018-03-21    cpu  mean   76.724406  10.41.100.1
3 2018-03-21    cpu   std  124.285789  10.41.100.1

Now I want to convert it to a list of strings stored inside a list, something like below
lis = [["2018-03-21", "cpu", "mean", "76.724406", "10.41.100.1"],
["2018-03-21", "cpu", "mean", "124.285789", "10.41.100.1"]]

I did something like this
for i in df:
    print(df[i].tolist())

But I get something like this
[Timestamp('2018-03-21 00:00:00'), Timestamp('2018-03-21 00:00:00')]
['cpu', 'cpu']
['mean', 'std']
[76.72440613174048, 124.28578926665278]
['10.41.100.1', '10.41.100.1']

But I want the format to be like mentioned above. How can I do this?
Answer: I think need astype for strings first, then convert DataFrame to numpy array by values and last for list call numpy.ndarray.tolist:
lis = df.astype(str).values.tolist()
print (lis)
[['2018-03-21', 'cpu', 'mean', '76.724406', '10.41.100.1'],
 ['2018-03-21', 'cpu', 'std', '124.285789', '10.41.100.1']]

Comment: @SouvikRay - First I dont read question carefully :) Glad can help!
Answer: The accepted solution by jezrael works.
However, I would suggest you take advantage of the numpy representation directly, since this is a more efficient way of storing and manipulating data.
It is rarely the case that a list is more useful than the numpy representation when dealing with structured data.
You can do this via:
res = df.values.astype(str)

This returns dtype <U11, while df.astype(str).values returns dtype Object. This is a significant difference in how the data is stored internally.


Error: Content-Type is not allowed by Access-Control-Allow-Headers

Question: I am getting this error in Chrome when trying to send an ajax request:
Content-Type is not allowed by Access-Control-Allow-Headers

Everything works fine in Firefox.
Can anyone help me to resolve this issue?
Answer: I solved the problem adding to Apache Web Server virtual host configuration the following settings
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"

Comment: I had the same problem. If you are using Django , use CORS HEADERS module, Check this CORS_ALLOW_HEADERS - https://github.com/ottoyiu/django-cors-headers/
Comment: @GiulioRoggero : I know I should not ask this here, but still after adding header to response, I am getting the same issue.
Comment: Can u please which file i should add these 2 lines? i had set this in .htaccess file og Magento and still i get preflight error msg!!
Comment: @SachinS this is apache.conf file
Answer: Solution for PHP:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST,GET,OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

(Need to send that before any other content)
Comment: This information was spot on, below is my 'complete' code for the solution.

`header('Access-Control-Allow-Origin: http://example.com');
header('Access-Control-Allow-Methods: GET,OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

echo $_GET['callback'].json_encode($data);`
Answer: Set up CORS (Cross-site HTTP Requests) in node. For me it looks like the following:
app.use('/api', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  next();
});

Comment: Could you please suggest on how to fix this issue in Angular 2: After following all the posts i still face: Response for preflight has invalid HTTP status code 400
Answer: for nginx
location / {
    proxy_pass http://localhost:59100;
    proxy_http_version 1.1;
    # proxy_set_header Upgrade $http_upgrade;
    # proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

    # proxy_cache_bypass $http_upgrade;
    # add_header Access-Control-Allow-Origin *;
    # add_header Access-Control-Allow-Headers Content-Type;
}

see
https://distinctplace.com/2017/04/17/nginx-access-control-allow-origin-cors/
Answer: I had the same problem and I solved it by adding the following header:
Access-Control-Allow-Headers: content-type
Comment: To what did you add this header to? To the request that you originated in the client side?
Comment: Cant speak for @Van Coding, but to get this to work you should add this header to the http response.
Answer: To me with PHP, localy works even if i set only this header setting:
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');


Quadratic Simultaneous equation

Question: $$4x(x^2+y^2-1)=0$$
$$4y(x^2+y^2+1)=0$$
Solving Simultaneous equation
$(x,y)=(0,0) ,(1,0)$ or $, (-1,0)$
I try to use substitution but couldnt find $x$ and $y$ properly, and (0,0) always be one of the solutions?
Comment: What are you asking here? The real solutions are $(0,0)$, $(\pm1,0)$ as you say.
Comment: Im asking how to get the solutions. First $x=0$ and $x^2+y^2-1=0$ so $y^2=1$ is this true?
Comment: For real number, $a, b$. if $ab=0$, the conclusion is $a=0$ or $b=$ rather than $a=0$ and $b=0$.
Answer: From the second equation, since $x^2+y^2 +1 > 0$, we have $y=0$
Substitute $y=0$ into the first equation, we end up with
$$4x(x^2-1)=0$$
Now we can solve for $x$.
Comment: Starting from the first equation, Isn't that what dxiv is doing?
Comment: Hello thanks for the answer! $x^2+y^2+1=0$ is this become one of the solution(?)
Comment: For real number, $x^2+y^2+1 \geq 1$, so that equation never holds.
Comment: $4x(x^2+y^2-1)=0$ here as you said, $4x=0$ since $x^2+y^2-1>=0$ never holds, then i get $x=0$ then i put it in second equation, so i will get $y=0$ right?
Comment: hmmm $x^2+y^2+1 \geq 0$, $x^2+y^2-1$ might take value $0$. working from the second equation seems easier. You can conclude $y=0$ directly. Try substituting $y0$ into the first equation and solve for $x$.
Comment: ah yes but i mean from second equation, did you conclude $y=0$ because  $x^2+y^2+1>=0$ so it is not satisfied =0? after substituting to first equation, i got $x=0,x=-1,x=1$, so i already got all the solutions?
Comment: yup, that is correct.
Comment: is it possible to find the solutions using the first equation? $x=0$? then substitute to second equations. but i dont know how to find x=-1/1
Answer:
If $x=0$ then the second equation gives $4y(y^2+1)=0 \implies y=0\,$, thus the solution $\boxed{(0,0)}$.
Else if $x \ne0, y=0$ the first equation gives $4x(x^2-1)=0 \implies x=\pm1\,$, thus $\boxed{(\pm1, 0\,)}\,$.
Otherwise if $x,y \ne 0\,$, dividing the first equation by $4x \ne 0$, the second one by $4y \ne 0$ and adding the two gives ...  subtracting the two (@LordSharktheUnknown's comment) gives $2=0\,$, obviously impossible, so there are no further solutions in this case.
Comment: Or in the last case subtracting the equations you get gives $8=0$.
Comment: Hello thanks for the answer! Do you get $x=0$ from the first equation? Then put in in second equation? And $y=0$ from second equation and put it in first equation?
Comment: @LordSharktheUnknown Right, that's arguably an even better way to derive the contradiction.
Comment: @DevinaMuljono `Do you get x=0 from the first equation` No, I am just breaking it down by cases. If $x=0$ then the first equation is satisfied automatically, so I am only looking at the second one.
Comment: did you get $x=0$$y=0$ by assumption? but if $y=0$ and substitute to first equation i will get $x=1,x=-1,x=0$ too.. is this true?
Comment: @DevinaMuljono Not sure what you mean `by assumption`. You are solving a system for $x,y$. My answer simply broke it down into three mutually exclusive cases: either **(a)** $\,x=0\,$, or **(b)** $\,x \ne 0, y=0\,$, or **(c)** $x,y \ne 0\,$, and derived the solutions in each case. There was no other assumption introduced at any step.
Comment: @dxiv hmm okay thankyou so much for answering my question!!!

Quadratic Simultaneous equation


Linq with multiple contains

Question: In our UI the users can free text a search that is applied to a number of fields.
            q = q.Where(p => p.Account.Contains(query)
                             || p.AccountName.Contains(query)
                             || p.AccountAKA.Contains(query)
                             || p.AccountRef.Contains(query));

This translates into SQL. Is there a more optimal way to querying, as this is slow.
There are about 20,000 rows. Database disk size doesn't matter, memory usage does.
Comment: When the user type the query, does it queries the database synchronously or asynchronously? Because improving the speed of the query seems quite difficult. So, you may work on the user experience itself.
Comment: The problem is that `LIKE %query%` is not efficient enough. The problem can solve indexing: http://blogs.msdn.com/b/varund/archive/2009/11/30/index-usage-by-like-operator-query-tuning.aspx
Comment: The only solution I see to solve that is to create your own indexation table (indexing all p.Account[x..y] strings). But it requires a lot of memory.
How many rows do you have in the database?
Answer: Since all these are text fields each of the values translates to Account LIKE '%'+ query+ '%'. All queries with wildcards on both sides will be slow, unfortunately there is not too much that can be done.
Maybe it is possible to use StartsWith() instead of Contains()? This would translate to `LIKE query + '%' which is generally much faster?
Answer: A better solution would be to change your data model and use a Description column that has ALL the account name info in it so you can do your query against a single column.  Updates to the record result in an update to this Description column.
Comment: Oh, I agree. But sometimes constraints don't allow for it :(

Linq with multiple contains


Care and maintenance of deck in the garden

Question: I recently bought a house. There is a deck in the garden. It is about two or three years old. It does not seem to be in a great condition, but I have no experience with decks and find it hard to tell how bad it is and what I need to do in terms of care and maintenance.
Here is a photo of the deck:

You can see that there is a slightly darker shaded area right of the middle. When it rains, the water occasionally stands on it. Question 1: Is there anything I can do about that in terms of prevention or care?
Here is a close-up photo of the deck. Question 2: What care instructions will I need to follow? Is there some treatment or paint I need to apply to make it more waterproof or prevent further tearing and somehow make it more durable?

Here is another close-up photo. You can see both some chipping and some tearing, especially where knots occur in the wood. Question 3: Is this normal, what can I do to prevent it, and what did the previous owners do wrong for it to happen?

Question 4: How many summers will I be able to use it before I need to replace it? Thanks.
Answer: From what I can see, it looks to be in pretty good shape. You want to start out by getting a deck wash from your home store and applying it according to instructions. You usually spray it on with a garden sprayer and then pressure clean it off. Stick to setting the pressure cleaner at around 1800 PSI, 2000 max. More than that and you can damage the wood. Then you have to decide whether to use a stain sealer (which I prefer) or a deck paint. Depending on your use of the deck and your climate, you'll have to do this every couple of years.
The cracks in the knots are pretty common and the previous owners couldn't to much to prevent that. If they really bug you or get worse, you can replace the boards if you can find the same type at your home store or lumber yard. The boards were screwed in place so replacing a few won't be too hard. Hopefully, they used stainless screws.
This deck should last for years and will depend on how well it's cared for. Only time will tell but mine have lasted 15 to 20 years in hot, rainy south Florida
Comment: Thanks, that's reassuring. I am in England, so pretty damp all year round. How do I decide between stain sealer and deck paint?
Comment: @spacecowboy  That is a personal preference. Stain sealers will seal the wood and let you "see" the wood grains. They are colored  or clear. The paint sealers  are heavier and totally cover the wood. The paint can chip whereas the stains soak in and won't chip.
Comment: I have been looking around for products and am confused. Do I need a stainer, a deck protector, or decking oil? From what I read, people usually recommend decking oil, such as Ronseal Ultimate Protection Decking Oil Natural or similar products. Or will I need both, decking oil and a protector? Or will I also need to stain it? And in which order?
Comment: @spacecowboy You would normally only use one of those products. I started out using Thompson's deck clear protector but didn't like the way it allowed the deck to get that natural silvery look. I then used a sealer stain that had a rosewood color and that worked great. I haven't used the decking oil but it would look good on your deck if your happy with the natural color of the wood. This is a personal preference so you'll need to check what's available in your area.
Comment: @spacecowboy    Many home stores have their own brands so do a little research. You've got some time because what ever you use, you'll have to clean, pressure clean, and do any plank repairs before any treatment goes on.
Comment: Thanks. I'll give the oil a try then. If I'm unhappy for whatever reason, I'll follow your other recommendations. Will start with the cleaning ASAP tomorrow.


stroke-dasharray in polyline SVG

Question: I have a polyline attribute
 <polyline points="229.7610294117647,200.44669117647058
 293.93566176470586,148.9485294117647 325.6268382352941,95.8658088235294
 374.74816176470586,124.38786764705881 389.00919117647055,218.6691176470588
 346.22610294117646,305.02757352941177 263.8290441176471,311.3658088235294
 232.1378676470588,215.5 " id="myCanvas_bg_obj_kpts0_43390" fill="none"
 stroke-dasharray="5, 5" stroke-width="2" fill-opacity="0.5"></polyline>

The problem I am having is the dashed stroke is not showing up.
Could not find any resources on dashed stroke for polyline. What am i missing here or in my resource search. Please help me out on this.
Help much appreciated
Comment: You've not set a stroke e.g. stroke="red"
Answer: Added as advised Robert Longson stroke="red"

The file is opened in the vector editor Inkscape
The image shows that the svg figure appears in the visibility zone, it needs to be shifted to the left and up.
This can be done in two ways:

add viewport,  viewBox

and shift the image using the transformation command
transform="translate(-130 -50)"

<svg width="400" height="400" viewBox="0 0 400 400" >
 <g transform="translate(-130 -50)">
 <polyline points="229.7610294117647,200.44669117647058
 293.93566176470586,148.9485294117647 325.6268382352941,95.8658088235294
 374.74816176470586,124.38786764705881 389.00919117647055,218.6691176470588
 346.22610294117646,305.02757352941177 263.8290441176471,311.3658088235294
 232.1378676470588,215.5 " id="myCanvas_bg_obj_kpts0_43390" fill="none"
 stroke-dasharray="5, 5" stroke-width="2" fill-opacity="0.5" stroke="red"></polyline>
 </g>
 </svg>

Instead of the translate transformation command, use the attributes x-min=130, y-min=50

viewBox="130 50 400 400"

<svg width="400" height="400" viewBox="130 50 400 400" >

 <polyline points="229.7610294117647,200.44669117647058
 293.93566176470586,148.9485294117647 325.6268382352941,95.8658088235294
 374.74816176470586,124.38786764705881 389.00919117647055,218.6691176470588
 346.22610294117646,305.02757352941177 263.8290441176471,311.3658088235294
 232.1378676470588,215.5 " id="myCanvas_bg_obj_kpts0_43390" fill="none"
 stroke-dasharray="5, 5" stroke-width="2" fill-opacity="0.5" stroke="red"></polyline>

 </svg>

stroke-dasharray in polyline SVG


Installing Xubuntu on Asus Transformer T101HA-GR043T

Question: I have an Asus Transformer T101HA-GR043T, a netbook withous USB ports. I want to erase the Windows version installed on it (I think is either Windows 8.1 or Windows 10) and install Xubuntu as main and only operating system. I have tried using Unetbootin from the boot screen but it doesn't work, it gives me a console-like screen when I select Unetbootin and nothing more. There is another method that I can use in order to install Xubuntu?
Comment: does the efi firmware allow you to turn off secure boot and select OS to boot?
Comment: I wouldn't bother with installing any Linux distro in a T101HA-GR043T. It runs a very Linux-unfriendly CPU ("Bay Trail") for which a special ISO is needed (from Linuxium) and even so some hardware will not work, most notably the audio. @ravery Bay Trail/Cherry Trail firmware does not have the option to turn off Secure Boot (and has no CSM/Legacy mode either). Bottom line: This entry level products were designed to run Windows 8 or newer only.
Comment: @MichaelBay Well...that sucks...
Comment: "Linux on Asus T100" is an offshoot of a long-established forum that was on Google Groups until the latter closed down.  It is now a Facebook group at:  https://www.facebook.com/groups/381498159345464/.  It is quite likely that someone on that group will be using your specific model of the T100 and will be able to assist.
Answer: I have same model, I spend so much time with installing different linux versions and here are the results:
Ubuntu - 17.10 works great, also audio with newest kernel. Only bad is brightness (And card reader I think). Brightness can't set up (still max).
Lightweight desktop environments(XFCE-Xubuntu, Cinnamon-mint, LXDE, etc...) work with more mistakes(mainly rotation).
Android x86 - works very fast, smooth, great battery condition and it seems ideal for this tablet. But! I don't find any way how to make rotation and graphic card work :(.
It is easy to try. Create live USBe from ISO in Linux Mint with its default livelinux-create app (I don't remember the name). It will work.


goodman furnace /ac no y terminal on board (revisited)

Question: My son-in-law's Goodman B1809913S control board only has R, W and G terminals (no Y terminal). In order to make the AC compressor AND the furnace fan operate the Y and the G wires are jumpered together at the furnace end of the thermostat cable. In this configuration there is no way to control the fan independently of the AC compressor. Currently when the fan is set to "Manual" at the thermostat the AC compressor AND the fan run continuously. Not a good situation because it would cause the AC compressor to run continuously.
Is there a way to wire or configure the system that would allow the fan to run continuously without turning on the AC compressor?
Comment: Hello, and welcome to Home Improvement. When you say "furnace fan" do you mean the main air-handling fan? And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: That Y wire that the G is jumpered to has to go back to the compressor somewhere, somehow.  Instead of being jumpered to the green, it needs to go to the thermostat.  Are there any extra wires that are unused at the thermostat?
Comment: Did you ever get this resolved? If so, please give a check-mark to the answer provided, or write up your own answer explaining what you did to get it fixed and give yourself a check mark. That will help others with this kind of problem know that this has a resolution and is a good place to look for their answer.
Comment: The issue has been resolved. My son-in-law  was gifted one of those smart thermostats which replaced the mechanical thermostat. He had a local AC company to the install. All works well now. Thank you.
Comment: @BAH911 -- post that as an answer and I'll give you a +1 for it
Answer: Use a relay
You can wire a standard HVAC "blower relay" of the SPST-N/O type with its coil connected between Y and C  and its contact connected between G and R and mount it in the furnace's wiring compartment.  This allows the thermostat to energize G by itself to turn on the blower without energizing Y by accident, but also energizes G to turn the fan on when the thermostat applies power to Y to call for compressor.


Best fix for failing built-in storage cabinet base?

Question: So I have these built-in cabinets (particle board) that are probably 15 years old. They looked fine maybe 3 days ago. Yesterday I noticed fractures and cracks forming in the base on one side of a row of cabinets. There's a similar crack developing on another cabinet but it's not as bad. The large crack in the image has doubled in width in just 12 hours. I'm guessing that it's due to water damage from a nearby pet water bowl. Have never seen any thing more than 2 table spoons of water on the floor and that was rare. The bright splotches are because paint was added over the years. It blends to the naked eye.
I have a lot of canned food in this cabinet (not visible in images) but that's been true for years. Looks like weight is causing the fractures but I know the piece of wood on the side (with the huge crack) shouldn't even be load bearing. I had to take it out and put it back 2 years ago and there was no weight on it. There are support feet under the cabinets. The other strange thing is that I have similar cabinets in an uninsulated garage that show zero issues.
Do you think the cabinet is in danger of collapsing or is it just an optical illusion?
What's the best way to fix this? I don't want to do a fix that will quickly fail either.
Comment: The question is a bit vague. If there are legs under the cabinet this skirt is completely aesthetic, right? How would we know if that's not true based on what you've shown us? More photos would be great. As to the "best" way to fix it--that's subjective. I'd tear them off and throw them away and move on with my day.
Comment: FYI, MDF and particle board are two different things. You have particle board here.
Comment: @isherwood best as in not subject to failing soon as mentioned. Thanks for editing q.
Answer: I would say the best solution is one that gets the particle board monstrosities out of the house, but you probably want a best that's less extreme.
If this is just a trim board preventing stuff from rolling under the cabinet, replacing it with a trim board less subject to falling apart at any hint of moisture would be better. Vinyl trim boards would be arguably "most durable" in that sense, but painted solid wood (not particle board) will likely be fine if the water exposure is not extreme, and will be less expensive than vinyl trim (mostly intended for outdoor use) in my experience.
Comment: Might be time to look for some reclaimed or used cabinets. They can be had cheap.
Comment: I hate these cabinets. Hinges are prone to fail because the board isn't strong enough to handle the stresses for example. I do have a solid piece of wood a few inches out of the picture that holds up a bench and it has no sign of decay as you say.


How can I fuse galvanized sheet metal with a circular bottom together so that it is water tight?

Question: I want to make a large circular pot out of sheet metal that can hold water. How should I construct it so that it has a circular bottom and ensure it is leak-proof.
Boiling water will be poured into this pot.
Thank you
Answer: Soldering is the usual method, but without metal-forming equipment I'd guess you don't have, that's not going to be a likely (or affordable) road to success for someone with no experience, for any value of large.
Buy a galvanised washtub or trashcan is the direct, simple route to a watertight circular metal "pot" over a wide range of sizes. Move into "stock watering tanks" for a larger size, though most of those are more oval. Without exhaustive shopping around:
17 gallons, $30:

31 gallons, $19, with lid:

This one is 477 gallons, circular, and costs $219.

Now I've gone and started to think that would make a nice country-style hot tub, and the price is so right...
Comment: The is the best solution to me. I deleted my post.
Answer: I would think that soldering would make a good seal provided you could keep the 2 surfaces tight to one another. Perhaps pop rivet the sides and the bottom together at 2" intervals, and let the solder flow. Yes DO be careful of any fumes may arise, but the galvanized metal may not get that hot enough to fume to get the solder to flow. Still, something to be watchful of...
Back in the day they used to solder galvanized downspouts and gutters together. I seen this from all the houses I worked on over the years.
Comment: Then there are galvanized foot tubs
Answer: You can weld it but DO NOT breathe in the poisonous vapors produced when welding galvanized steel.
Comment: Thanks for your comment. Its quite thin material (22 gauge) so I want to avoid welding just because I'd likely pierce through the sheet and create holes. I want to make it waterproof and avoid any leakage