Coffescript not compiling in rails app. Says syntax error - unexpected indentation - coffeescript

I'm new to coffeescript and I'm not sure what is wrong with my syntax. I want to add an error message if either the date or time field is empty upon clicking the update button. Here is my code.
$.add_error = (field, message) ->
unless field.hasClass('input-error')
field.after('<span class="input-error-message">' + message + '</span>')
field.addClass('input-error')
$.remove_error = (field) ->
field.removeClass('input-error')
field.parent().find('.input-error-message').remove()
$('.btn.update_schedule').click ->
date = $('#date')
time = $('#time')
if (date.val() && !time.val()) || (!date.val() && time.val())
if !time.val()
$.add_error(repeat_count, 'Please select both a date and time')
false
else !date.val()
$.add_error(repeat_date, 'Please select both a date and time')
false
else
$.remove_error(time) || $.remove_error(date)
I'm unable to compile this code because it says there's an unexpected indentation but I don't see it. Any advice would be greatly appreciated.

In the last block $('.btn.update_schedule').click ->, there is an
if ... else ... else ...
that is basically non-sense.
It seems that should be instead an
if ... else if ... else ...
This seems the correct version:
$('.btn.update_schedule').click ->
date = $('#date')
time = $('#time')
if (date.val() && !time.val()) || (!date.val() && time.val())
if !time.val()
$.add_error(repeat_count, 'Please select both a date and time')
false
else if !date.val()
$.add_error(repeat_date, 'Please select both a date and time')
false
else
$.remove_error(time) || $.remove_error(date)

Related

Adding strings from python to text file and then verify lines in while loop

I'm new to coding and still learning about Python.
I have a task where I have to upload lines from Python to a text file and then verify the lines later in the code e.g. I have to input user names and user passwords and add to the text file as [user_name, user_pass].
My problem is that when I try to verify the line one of 2 things happen. After I added a split function for the line e.g. verified_user, verified_password = line.split(", ") it runs into an error stating that I do not have enough values for the request made e.g 2 expected, 1 made. If I change the split input and it does run, the verification loop states that my inputs does not match any lines in the string.
Every thing works if I add the information to the text file only. But the moment I add via the appendix action in Python it no longer works.
this is what I have so far:
user_list = []
all_names_entered = "no"
while all_names_entered == "no":
user_name = input("Enter user name: ")
user_pass = input("Enter password: ")
user_list.append(user_name + ", " + user_pass)
while True:
all_names_entered = input("All users entered?: ")
if all_names_entered in ['yes','no']:
break
else:
print( 'please answer with yes or no' )
for items in user_list:
with open('user.txt', 'a') as file:
file.write(f"{user_name}, {user_pass}\n")
print (user_list)
file.close()
the next block reads as follow:
user_file = open("user.txt", "r+")
login = False
while login == False:
username = input("Enter user name: ")
password = input("Enter user password: ")
for line in user_file:
other = line.strip()
valid_user, valid_password = line.split(", ")
if username == valid_user and password == valid_password:
login = True
print ("You have successfully logged in")
break
else:
print("You have entered incorrect detail. Please try again")
user_file.seek(0)
user_file.close()
Firstly, indentation is important in Python.
Secondly, you're supposed to loop if user enters 'no'.
Utilize the item that's initialized in each for loop.
You initialized other but it was never consumed.
Following is code for writing into file:
user_list = []
all_names_entered = "no"
while all_names_entered == "no":
user_name = input("Enter user name: ")
user_pass = input("Enter password: ")
user_list.append(user_name + ", " + user_pass)
query_all_names_entered = True
while query_all_names_entered:
all_names_entered = input("All users entered?: ")
if all_names_entered == 'yes':
query_all_names_entered = False
break
elif all_names_entered == 'no':
query_all_names_entered = False
continue
else:
print('Please answer with yes or no')
all_names_entered = "no"
with open('user.txt', 'a') as file:
for item in user_list:
file.write(f"{item}\n")
print (user_list)
file.close()
And following is for reading file to log in:
user_file = open("user.txt", "r+")
login = False
lines = user_file.readlines()
while login == False:
username = input("Enter user name: ")
password = input("Enter user password: ")
for line in lines:
valid_user, valid_password = line.strip().split(", ")
if username == valid_user and password == valid_password:
login = True
print ("You have successfully logged in")
break
if login == False: print ("You have entered incorrect detail. Please try again")
user_file.close()

TypeError: Cannot read property 'roles' of null

I tried to create a command of -clear (amount) and the coomand doing well but the permissions dont
this is what the error i get
TypeError: Cannot read property 'roles' of null
at Client.<anonymous> (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\main.js:448:23)
at Client.emit (events.js:327:22)
at MessageCreateAction.handle (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\ws\lib\websocket.js:825:20)
and here the code:
client.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
const deltef = args[1]
const amount = parseInt(args[1]);
if(message.member.roles.cache.has('715841880482512897')) {
if(args[0] == 'clear') {
if (isNaN(amount)) {
message.reply('that doesn\'t seem to be a valid number.');
} else if (amount < 2 || amount > 100) {
message.reply('you need to input a number between 2 and 100.');
}
else if (amount > 2 || amount < 100)
message.channel.bulkDelete(args[1]);
message.channel.send("deleted" + " " + deltef + " " + "messages" + ('✅'))
}
}
}
);
if you can help i will be happy
Are you trying to use this command in DM's? Because according to the Discord.JS documentation message.member is only available in guilds, what means if you try to use it in DM's it will be undefined.
https://discord.js.org/#/docs/main/master/class/Message?scrollTo=member
I recommend limiting commanmd usage only to guilds so things like this can't happen.
client.on('message', message => {
if (message.author.bot || message.channel.type === "dm") return;
// your code...
})

ORA-06550: PLS-00103: Encountered the symbol "" with mybatis TypeHandler

I am using Typehandler to map a List<Dep> to oracle array of ... here is the setPArameter method in the handler :
public void setParameter(PreparedStatement ps, int i, List<Dep> parameter, JdbcType jdbcType)
throws SQLException {
Connection connection = ps.getConnection();
// StructDescriptor structDescriptor = StructDescriptor.createDescriptor("MEMS_ARR", connection);
Struct[] structs = null;
if(parameter != null && parameter.size() >0) {
structs = new Struct[parameter.size()];
for (int index = 0; index < parameter.size(); index++)
{
Dep dep = parameter.get(index);
Object[] params = new Object[7];
params[0] = dep.getOrder();
params[1] = dep.getIdTp;
params[2] = dep.getId();
params[3] = " ";
params[4] = " ";
params[5] = " ";
params[6] = " ";
// STRUCT struct = new STRUCT(structDescriptor, ps.getConnection(), params);
structs[index] = connection.createStruct("MEMS", params);
}
// ArrayDescriptor desc = ArrayDescriptor.createDescriptor("MEMS_ARR", ps.getConnection());
// ARRAY oracleArray = new ARRAY(desc, ps.getConnection(), structs);
}else {
parameter = new ArrayList<DependentDTO>();
structs= new Struct[0];
}
this.parameter = parameter;
Array oracleArray = ((OracleConnection) connection).createOracleArray("MEMS_ARR", structs);
ps.setArray(i, oracleArray);
}
and here is the MEMS type :
create or replace TYPE MEMS AS OBJECT
( MEM1 NUMBER(2,0),
MEM2 VARCHAR2(1),
MEM3 VARCHAR2(15),
MEM4 VARCHAR2(60),
MEM5 VARCHAR2(1),
MEM6 VARCHAR2(40),
MEM7 VARCHAR2(10)
);
and here is the portion of the xml mapping file that uses the Typehandler :
#{nat,javaType=String,jdbcType=VARCHAR,mode=IN}, --nat
**#{deps,javaType=List,jdbcType=ARRAY,mode=IN,jdbcTypeName=MEMS_ARR,typeHandler=com.my.package.MyHandler}, --mems**
#{res,javaType=String,jdbcType=VARCHAR,mode=OUT} --res
the error log is as follows :
Error querying database. Cause: java.sql.SQLException: ORA-06550: line 31, column 5: PLS-00103: Encountered the symbol "" when expecting one of the following: . ( ) , * # % & = - + < / > at in is mod remainder not rem => <an exponent (**)> <> or != or ~= >= <= <> and or like like2 like4 likec between || indicator multiset member submultiset The symbol "(" was substituted for "" to continue. ORA-06550: line 44, column 4: PLS-00103: Encountered the symbol ";" when expecting one of the following: . ( ) , * % & = - + < / > at in is mod remainder not rem => <an exponent (**)> <> or != or ~= >= <= <> and or like like2 like4 likec between || multiset ### The error may exist in file [E:\path\to\mapper\ADao.xml] ### The error may involve my.package.ADao.mthodToCall -Inline ### The error occurred while setting parameters ### SQL: {call MY_PROC( ... , --nat?, **--mems? --res**)}
As you can see in the logs, the mems is replaced by empty string or is merged with the next arg res ... the comma is not there
Also kindly note that I already debugged inside the mybatis code and realized that the mapping setParameter method is called and the input List is mapped correctly to the oracle array ... the issue happens at the time of real calling
The issue actually was that I simply missed one comma between two previous parameters ... but the error pointed to the wrong parameter to look at

Handling a unique key Constraint Violation with powershell and SQL

I'm writing a script to insert a GUID into a SQL table. In order to stop duplicates, I have made the table GUID column unique.
So now I need to catch the violation and ignore if its a duplicate and continue the script. So write the new GUIDS but ignore the duplicates.
What would be the best way to catch and deal with the violation?
I've seen a few options on this site, but none work for me, most fail with The Catch block is missing its statement block. or other errors.
Example of the catch block I've been trying
catch(SqlException ex)
{
sqlException = ex.InnerException as System.Data.SqlClient.SqlException;
if (sqlException.Number == 2601 || sqlException.Number == 2627)
{
ErrorMessage = "Cannot insert duplicate values.";
}
else
{
ErrorMessage = "Error while saving data.";
}
}
and the errors:
At D:\Software Approval Requests\GetApprovalRequestsNew2.ps1:15 char:6
+ catch (UpdateException ex)
+ ~
The Catch block is missing its statement block.
At D:\Software Approval Requests\GetApprovalRequestsNew2.ps1:18 char:32
+ if (innerException != null && innerException.Number == 2627 || innerExceptio ...
+ ~~
The token '&&' is not a valid statement separator in this version.
At D:\Software Approval Requests\GetApprovalRequestsNew2.ps1:18 char:65
+ if (innerException != null && innerException.Number == 2627 || innerExceptio ...
+ ~~
The token '||' is not a valid statement separator in this version.
At D:\Software Approval Requests\GetApprovalRequestsNew2.ps1:23 char:28
+ if (innerException != null && (innerException.Number == 2627 || innerException.N ...

Switch 'non-else' case?

Is it possible to get rid of useless ok variable in this code?
cond1 = true
cond2 = true
cond3 = true
switch
when !cond1
console.log "cond1 failed"
when !cond2
console.log "cond2 failed"
when !cond3
console.log "cond3 failed"
else
ok = true
if !ok then process.exit(1)
console.log "good"
You may change your code to
cond1 = true
cond2 = true
cond3 = true
switch
when !cond1
console.log "cond1 failed"
when !cond2
console.log "cond2 failed"
when !cond3
console.log "cond3 failed"
process.exit(1) if !(cond1 && cond2 && cond3)
console.log "good"
with the disadvantage of duplicating the condition checking.
I guess that you want to show all unmet conditions (because you put the process.exit call after the switch statement). If so, your code has the problem that it does only shows the first unfulfilled condition. So I would just use if statements
cond1 = false
cond2 = false
cond3 = true
if !cond1
console.log "cond1 failed"
if !cond2
console.log "cond2 failed"
if !cond3
console.log "cond3 failed"
process.exit(1) if !(cond1 && cond2 && cond3)
console.log "good"
All over all you'll have to decide if the double checking of your conditions or one setting and checking of a variable is more expensive in comparison with the readability of your code.
I would give readability a higher priority if not realy dealing with performance or memory problems an use something like:
cond1 = false
cond2 = false
cond3 = true
error={"success":true,"msg":"good"}
addError=(msg)->
error.msg="" if error.success
error.success=false
error.msg+=msg+"\n"
checkForErrors=(e)->
console.log e.msg
if !e.success
process.exit(1)
addError "cond1 failed" if !cond1
addError "cond2 failed" if !cond2
addError "cond3 failed" if !cond3
checkForErrors error
If you should write the condition checking before or after the addError call depends of the length of your condition code.