if statement is true but doesnt go into the block - coffeescript

This is my coffe script:
jQuery ->
if $('#infinite-scrolling').size() > 0
$(window).on 'scroll', ->
window_top = $(window).scrollTop()
doc_height = $(document).height()
window_height = $(window).height()
window_bottom = window_top + window_height
scroll = window_bottom / doc_height > 0.9
next_page = $('.next_page').attr('href')
console.log(next_page)
console.log($('#infinite-scrolling').size() > 0)
if next_page && scroll
$.getScript next_page
return
return
It doesnt get into the if block allthough the statement in the if should be true because when I remove the if then I can see in the console that its true through this line:
console.log($('#infinite-scrolling').size() > 0)
Anyone any idea what I am doing wrong?

The if statement looks fine.
The code works for me once I fix the indentation, except that .size() is deprecated in the latest jquery (3.3.1). I replaced it with .length.
But I can't test the second if block without your HTML.
Are you sure there are no errors thrown?
Here is my version:
jQuery ->
if $('#infinite-scrolling').length > 0
$(window).on 'scroll', ->
window_top = $(window).scrollTop()
doc_height = $(document).height()
window_height = $(window).height()
window_bottom = window_top + window_height
scroll = window_bottom / doc_height > 0.9
next_page = $('.next_page').attr('href')
console.log(next_page)
console.log($('#infinite-scrolling').length > 0)
if next_page && scroll
$.getScript next_page
return
return
And here as a codepen

Related

How to write this piece of code in function?

I am using the "Divergence Indicator" script written by Tradingview with Macd, stoch and rsi at the same time.
I use the code below duplicate 3 times (for Macd, stoch and rsi)
plFound = na(ta.pivotlow(rsi, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(rsi, lbL, lbR)) ? false : true
// Regular Bullish
oscHL = rsi[lbR] > ta.valuewhen(plFound, rsi[lbR], 1) and _inRange(plFound[1])
priceLL = close[lbR] < ta.valuewhen(plFound, close[lbR], 1)
bullCond = priceLL and oscHL and plFound
// Regular Bearish
oscLH = rsi[lbR] < ta.valuewhen(phFound, rsi[lbR], 1) and _inRange(phFound[1])
priceHH = close[lbR] > ta.valuewhen(phFound, close[lbR], 1)
bear = priceHH and oscLH and phFound
Is it possible to use a function to avoid duplicating the same code 3 times?
Very simple
f_divergences(_src) =>
plFound = na(ta.pivotlow(_src, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(_src, lbL, lbR)) ? false : true
// Regular Bullish
oscHL = _src[lbR] > ta.valuewhen(plFound, _src[lbR], 1) and _inRange(plFound[1])
priceLL = close[lbR] < ta.valuewhen(plFound, close[lbR], 1)
bullCond = priceLL and oscHL and plFound
// Regular Bearish
oscLH = _src[lbR] < ta.valuewhen(phFound, _src[lbR], 1) and
_inRange(phFound[1])
priceHH = close[lbR] > ta.valuewhen(phFound, close[lbR], 1)
bear = priceHH and oscLH and phFound
[bullCond, bear]
// Calling the function three times
[rsi_bull, rsi_bear] = f_divergences(rsi)
[stoch_bull, stoch_bear] = f_divergences(stoch)
[macd_bull, macd_bear] = f_divergences(macd)

Protractor need to break from For LOOP when if is executed

Can anyone Please Help me in this in the below code, my requirement is once If is true, I should come out from For loop
===================================================
for (i = 0; i < 50; i++) {
element(By.xpath("//*[text() = '" + InvoiceREFnumberCompany + "']")).isPresent().then(function(result) {
if (result )
{
element(By.xpath("//*[text() = '" + InvoiceREFnumberCompany + "']")).click();
break;
}
else
{
obj1.ClickOnRefreshButton.click();
}
});
}
Output
Failures:
NPOInvoice-Fire -- NPO Fire Collabrate with PTC user
Message:
[31m Failed: Illegal break statement[0m
Stack:
SyntaxError: Illegal break statement

running file diff on two files on Mac

Im comparing to files, but my understanding is that + signifies addition and - symbols deletion. The new file has a typo:
if (KEY_STATUS.spacr) {
The why is it represented by -. It should be +, right ? When I run diff -u game_new.js game_old.js:
--- game_new.js 2018-06-12 02:03:32.000000000 -0700
+++ game_old.js 2018-06-12 02:03:22.000000000 -0700
## -4,9 +4,9 ##
//
KEY_CODES = {
- 13: 'enter',
32: 'space',
37: 'left',
+ 38: 'up',
39: 'right',
40: 'down',
70: 'f',
## -392,7 +392,7 ##
this.vel.rot = 0;
}
- if (KEY_STATUS.spacr) {
+ if (KEY_STATUS.up) {
var rad = ((this.rot-90) * Math.PI)/180;
this.acc.x = 0.5 * Math.cos(rad);
this.acc.y = 0.5 * Math.sin(rad);
## -406,7 +406,7 ##
if (this.delayBeforeBullet > 0) {
this.delayBeforeBullet -= delta;
}
- if (KEY_STATUS.enter) {
+ if (KEY_STATUS.space) {
if (this.delayBeforeBullet <= 0) {
this.delayBeforeBullet = 10;
for (var i = 0; i < this.bullets.length; i++) {
## -919,7 +919,7 ##
waiting: function () {
Text.renderText(ipad ? 'Touch Sreen to Start' : 'Press Space to Start', 36, Game.canvasWidth/2 - 270, Game.canvasHeight/2);
if (KEY_STATUS.space || window.gameStart) {
- KEY_STATUS.space = false; // hack so we don't move right away
+ KEY_STATUS.space = false; // hack so we don't shoot right away
window.gameStart = false;
this.state = 'start';
}
I believe that when you run:
diff -u game_new.js game_old.js
The changes coming from the file on the left are interpreted as being the source, and marked with a minus, while the changes coming from the file on the right are treated as the destination, and marked with a plus.
If you want the - and + labels to appear as you want, then run diff with the files in the reverse order:
diff -u game_old.js game_new.js

Class Methods not linking to Tkinter GUI

it seems my Tkinter GUI is fine however when loaded the buttons which should activate the class methods do nadda.
I was originally trying to initiate a class instance within the main:
if_name_== "main":
ed.EditorUI()
Where 'self' is used below 'ed' was in its place.. it said ed was undefined which prompted me to try this way.
As you can probably tell its been a few years since I've coded.
Your help is much appreciated!
import CU_picture
import filters
import Tkinter
root = Tk()
root.title('Photo Editor Version 1.10')
#root.iconbitmap(bitmap = '12.ico')
#img = PhotoImage(file='12.ico')
#root.tk.call('wm', 'iconphoto', root._w, img)
#Adding File Menu
menubar = Tkinter.Menu(root)
filemenu = Tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
#Display above menus
root.config(menu=menubar)
class EditorUI(object):
def __init__(self):
self.name = "EditorUI"
self.pic = 0
self.pix = CU_picture.Picture()
self.filters = "No Current Filters Applied"
self.special = "cake"
def get_specific_color(color):
if color == "red":
return CU_picture.Color(255, 0, 0)
elif color == "aqua":
return CU_picture.Color(0, 255, 255)
elif color == "fuschia":
return CU_picture.Color(255, 0, 255)
elif color == "lime":
return CU_picture.Color(0, 255, 0)
elif color == "yellow":
return CU_picture.Color(255, 255, 0)
def load():
self.pix = get_picture()
self.pix.show()
self.pic = 1
error.set("Pic Loaded: "+self.filters)
outtext.set("New Picture - Not Saved.")
self.filters = "No Current Filters Applied"
self.special = "cake"
para.set("")
def save():
if self.pic == 0:
error.set("No Pic Loaded")
else:
name = intext.get() + ".jpg"
self.pix.write_to(name)
outtext.set("Saved To Given Filename.")
para.set("")
def negative():
if self.pic == 0:
error.set("No Pic Loaded")
else:
n = filters.NegativeFilter()
n.apply(ed.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Negative-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Negative-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def grayscale():
if self.pic == 0:
error.set("No Pic Loaded")
else:
g = filters.GrayScaleFilter()
g.apply(self.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Grayscale-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Grayscale-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def posterize():
if self.pic == 0:
error.set("No Pic Loaded")
else:
p = filters.PosterizeFilter()
p.apply(self.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Posterize-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Posterize-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def highlight():
if self.pic == 0:
error.set("No Pic Loaded")
else:
if intext.get() == "":
para.set("Input Highlight distance/Colour and try again(one at a time).")
elif self.special == "cake" and intext.get() != "":
self.special = intext.get()
outtext.set("Highlight distance: " + self.special)
para.set("Input Highlight colour(red, blue, aqua, fuschia, lime, yellow) for the final step.")
elif self.special != "cake" and intext.get() != "":
color = get_specific_color(intext.get())
h = filters.HighlightFilter()
h.set_distance(float(self.special))
h.set_color(color)
outtext.set("Highlight colour: " + intext.get())
h.apply(self.pix)
self.pix.show()
if self.filters == "No Current Filters Applied":
self.filters = "Highlight-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Highlight-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def edge():
if self.pic == 0:
error.set("No Pic Loaded")
else:
para.set("Threshold?")
if intext.get() == "":
para.set("Input Threshold value and try again.")
else:
para.set("Threshold: " + intext.get())
e = filters.EdgeFilter()
e.set_threshold(float(intext.get()))
e.apply(self.pix)
self.pix.show()
if self.filters == "No Current Filters Applied":
self.filters = "Edge-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Edge-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def get_picture():
"""
Interactively select a picture file and return it.
"""
# Pop up a dialogue box to select a file
file = CU_picture.pick_a_file()
# Open the file containing the picture and load it
pict = CU_picture.load_picture(file)
return pict
if __name__ == "__main__":
EditorUI()
intext = Tkinter.StringVar()
outtext = Tkinter.StringVar()
error = Tkinter.StringVar()
para = Tkinter.StringVar()
inp = Tkinter.Entry(root, textvariable=intext)
out = Tkinter.Label(root, textvariable=outtext)
ER = Tkinter.Label(root, textvariable=error)
P = Tkinter.Label(root, textvariable=para)
load = Tkinter.Button(root, text="Load", height=2, width=20, command=load)
save = Tkinter.Button(root, text="Save", height=2, width=20, command=save)
negative = Tkinter.Button(root, text="Negative-F", height=1, width=20, command=negative)
grayscale = Tkinter.Button(root, text="Grayscale-F", height=1, width=20, command=grayscale)
posterize = Tkinter.Button(root, text="Posterize-F", height=1, width=20, command=posterize)
highlight = Tkinter.Button(root, text="Highlight-F", height=1, width=20, command=highlight)
edge = Tkinter.Button(root, text="Edge-F", height=1, width=20, command=edge)
inp.grid(row=1, column=7)
ER.grid(row=0, column= 0, columnspan=5, rowspan=2)
out.grid(row=1, column= 0, columnspan=5, rowspan=2)
P.grid(row=2, column= 0, columnspan=5, rowspan=2)
load.grid(row=0, column=6)
save.grid(row=0, column=7)
negative.grid(row=1, column=6)
grayscale.grid(row=3, column=7)
posterize.grid(row=3, column=6)
highlight.grid(row=2, column=6)
edge.grid(row=2, column=7)
root.mainloop()
One of the main problems that I see (other than what #A.Rodas mentioned above) that would prevent the buttons from doing anything is that your button commands are not actually targeting the class methods. They're looking for root-level callables named "load", "save", etc. Because these don't exist, you should be getting errors, and yet you say the interface works fine aside from the buttons not cooperating, which doesn't make sense to me.
To call the class methods, you must create an instance of the class. First fix the self issue mentioned by #A.Rodas above, then replace the __main__ check with this:
editor = EditorUI()
Then modify the button commands to call the methods on the editor instance:
load = Tkinter.Button(root, text="Load", height=2, width=20, command=editor.load)
save = Tkinter.Button(root, text="Save", height=2, width=20, command=editor.save)
negative = Tkinter.Button(root, text="Negative-F", height=1, width=20, command=editor.negative)
grayscale = Tkinter.Button(root, text="Grayscale-F", height=1, width=20, command=editor.grayscale)
posterize = Tkinter.Button(root, text="Posterize-F", height=1, width=20, command=editor.posterize)
highlight = Tkinter.Button(root, text="Highlight-F", height=1, width=20, command=editor.highlight)
edge = Tkinter.Button(root, text="Edge-F", height=1, width=20, command=editor.edge)
You may also consider moving all the interface creation stuff inside the EditorUI class, unless you have some other reason for keeping it separate.

Save a <canvas> as a file in a form

Using Canvas method toDataURL, I would like to be able to save the image on the server side (using Rails).
With toDataURL string, how to use it in a form that can be seen as a file attachment in a HTML form ?
Solution using jQuery, Paperclip, datafy.rb
http://gist.github.com/397615
Here is my solution:
The problem: Compact uploaded images of any size before sending it to the server, which will save the image.
Files involved: 2 ASP pages: one that will act client-side and another server-side.
The Presentation page:
<html>
<!-- by arturmariojr#gmail.com - on december/2012 -->
<script language='javaScript'>
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('Este Browser não suporte a API Files');
}
function Compactar(Elemento) {
var file = document.getElementById(Elemento),
reader = new FileReader(), // métodos assíncronos, por isso os eventos!
form = document.getElementById('frmFotos');
//alert(file.id);
reader.readAsDataURL(file.files[0]); // aqui a abertura do arquivo, que irá disparar a função acima
reader.onloadend = function() { // aqui um evento, que será disparado na primeira linha abaixo da função chamada
var image = new Image();
image.src = reader.result; // vai disparar o tratamento do evento abaixo
image.onload = function() {
var maxWidth = 800,
maxHeight = 600,
width = image.width,
height = image.height;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > maxWidth) {
//height *= max_width / width;
height = Math.round(height *= maxWidth / width);
width = maxWidth;
}
} else {
if (height > maxHeight) {
//width *= max_height / height;
width = Math.round(width *= maxHeight / height);
height = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, maxWidth, maxHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL("image/jpeg",0.8); //a 80% de qualidade
// aqui cria-se novo input comun!
/*var newinput = document.createElement("input");
newinput.type = 'text';
newinput.name = "edt" & Elemento;
newinput.value = finalFile; // put result from canvas into new hidden input
form.appendChild(newinput);*/
document.getElementById("edtArq_1").value = finalFile;
var preview = document.getElementById('preview');
//alert(preview.id);
preview.appendChild(canvas); // do the actual resized preview
}
}
}
</script>
<html>
<form id="form" action="submit" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<!-- this will be left behind - we don't want to upload Mbytes of information -->
<input type='file' name='Arq_1' id='Arq_1' size='50' onchange='Compactar("Arq_1");'>
<form method="POST" id='frmFotos' action='SalvaArquivo.asp'>
<!-- this could be a hidden element -->
<input name='edtArq_1' id='edtArq_1'><br>
<input type='submit' name ='cmdEnviar' id='cmdEnviar' value='Enviar' >
</form>
<!-- just for you see the new resized image - no upload too -->
<div id="preview"></div>
</html>
The page that will reveive the request from the first page and save the image:
<html>
<!-- by arturmariojr#gmail.com - on december/2012 -->
<!-- this script could be avoided if I had put the img element in the page directly
. By the way, actualyy there's no necessity of showing nothing to user
-->
<script language='JavaScript'>
var newImg = document.createElement("img");
newImg.src = '<%=request.form("edtArq_1")%>';
document.body.appendChild(newImg);
</script>
<body>
<input name='edtOriginal' value='<%=request.form("edtArq_1")%>'>
<%
' the data is encoded, so, we will need to deencode it ...
Function Base64Decode(ByVal base64String)
'rfc1521
'1999 Antonin Foller, Motobit Software, http://Motobit.cz
Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Dim dataLength, sOut, groupBegin
'remove white spaces, If any
base64String = Replace(base64String, vbCrLf, "")
base64String = Replace(base64String, vbTab, "")
base64String = Replace(base64String, " ", "")
'The source must consists from groups with Len of 4 chars
dataLength = Len(base64String)
If dataLength Mod 4 <> 0 Then
Err.Raise 1, "Base64Decode", "Bad Base64 string."
Exit Function
End If
' Now decode each group:
For groupBegin = 1 To dataLength Step 4
Dim numDataBytes, CharCounter, thisChar, thisData, nGroup, pOut
' Each data group encodes up To 3 actual bytes.
numDataBytes = 3
nGroup = 0
For CharCounter = 0 To 3
' Convert each character into 6 bits of data, And add it To
' an integer For temporary storage. If a character is a '=', there
' is one fewer data byte. (There can only be a maximum of 2 '=' In
' the whole string.)
thisChar = Mid(base64String, groupBegin + CharCounter, 1)
If thisChar = "=" Then
numDataBytes = numDataBytes - 1
thisData = 0
Else
thisData = InStr(1, Base64, thisChar, vbBinaryCompare) - 1
End If
If thisData = -1 Then
Err.Raise 2, "Base64Decode", "Bad character In Base64 string."
Exit Function
End If
nGroup = 64 * nGroup + thisData
Next
'Hex splits the long To 6 groups with 4 bits
nGroup = Hex(nGroup)
'Add leading zeros
nGroup = String(6 - Len(nGroup), "0") & nGroup
'Convert the 3 byte hex integer (6 chars) To 3 characters
pOut = Chr(CByte("&H" & Mid(nGroup, 1, 2))) + _
Chr(CByte("&H" & Mid(nGroup, 3, 2))) + _
Chr(CByte("&H" & Mid(nGroup, 5, 2)))
'add numDataBytes characters To out string
sOut = sOut & Left(pOut, numDataBytes)
Next
Base64Decode = sOut
End Function
' now, we will save the data (new image) using the old FileSystemObject !!!
Set fso = Server.CreateObject ("Scripting.FileSystemObject")
If Err.Number <> 0 Then
Response.write "Não foi possível instanciar objeto fso!<br>" & Err.description
response.end
End if
dim Caminho, objArq
Caminho = Server.MapPath("./images") 'where I saved the new image
response.write Caminho
If Err.Number <> 0 Then
Response.write "Não foi possível localizar caminho! " & Caminho & "<br>" & Err.description & "<br>"
else
Set oFile = fso.CreateTextFile(Caminho & "\Teste.jpg", true)
oFile.Write Base64Decode(replace(request.form("edtArq_1"), "data:image/jpeg;base64,", "")) 'BinaryToString(request.from("edtArq_1"))
If Err.Number <> 0 Then
Response.write "Não foi possível localizar thum(s)!" & Caminho & "<br>" & Err.description & "<br>"
end if
oFile.close
end if
%>
</body>
</html>