Django Python shell indentation error - django

when i paste the below code in my python shell. I get an Indentation error.
... print "this is an ideal answer for both" File "", line
2
print "this is an ideal answer for both"
^ IndentationError: expected an indented block
def get_match(user_a, user_b):
user_a_answers = UserAnswer.objects.filter(user=user_a)[0]
user_b_answers = UserAnswer.objects.filter(user=user_b)[0]
if user_a_answers.question.id == user_b_answers.question.id:
user_a_answer = user_a_answers.my_answer
user_a_pref = user_a_answers.their_answer
user_b_answer = user_b_answers.my_answer
user_b_pref = user_b_answers.their_answer
if user_a_answer == user_b_pref:
print "%s fits with %s's preference" %(user_a_answers.user.username, user_b_answers.user.username)
if user_a_pref == user_b_answer:
print "%s fits with %s's preference" %(user_a_answers.user.username, user_b_answers.user.username)
if user_a_answer == user_b_pref and user_a_pref == user_b_answer:
print "this is an ideal answer for both"
get_match(mohit, saraswati)
get_match(saraswati, userc)
get_match(mohit, userc)
i get an indentation error , when i run this from the shell , why?`

It is hard to determine your indentation error. Because Python supports one-way indentation. You may be used Tab and spaces at a time. Please check by yourself and use only one at a time. Spaces are recommended.

Related

How to add a string to a file with the execution of a regular expression?

import re
import logging
x = input("enter number of bad car")
if re.match('/^[A-ZА-Я]{1}[0-9]{3}[A-ZА-Я]{2}([0-9]{0,3})?$/', x):
logging.debug("found match" + x)
with open("some.txt" , 'w') as f:
f.write(x + '\n')
else:
logging.debug("does not match")
However, nothing is written in the file some.txt
I got a logging file which wrote away 'does not match' with the following changes:
import re
import logging
logging.basicConfig(filename = ( "loggingfile.log"), level = logging.DEBUG, format = '%(message)s')
x = input("enter number of bad car")
if re.match('/^[A-ZА-Я]{1}[0-9]{3}[A-ZА-Я]{2}([0-9]{0,3})?$/', x):
logging.debug("found match" + x)
with open("some.txt" , 'w') as f:
needed = str(x + '\n')
logging.info(needed)
else:
logging.info("does not match")
So, I added:
logging.basicConfig, which set some basic configuration stuff
for your logging file (name, path, format...)
I created needed up front, which has all the needed data in it, and then wrote it away to the logging file using logging.info()
I think that that is all that I changed, hope I helped out!
I got output like this from 'logging.log' with input (the random number) 56184615:
does not match
Your regex cannot match. `/^' means a slash, followed by the start of the string. Try to remove the two slashes in the regex.

How to run a Powershell function through a Python script

I am trying to create a translator-type program in Python (this is 2.7, if that is important). I want to receive user input, translate it, and then print their output to the screen. That part is not difficult, but I also want to export it to a text file. I am using Powershell for that, with the subprocess module. The Powershell script is very short, and all it does is asks for the user to copy and paste the Python translation into an input. It then calls New-Item to create a file and gives it the value option as the Python translation.
Python code:
def translator:
inquiry = raw_input("Leetspeak trans query: ") #Enter query
inquiry = inquiry.lower() #Change all to lowercase, so that everything gets translated
newPrint1 = "" #The new string that gets returned to them at the end
level = raw_input("What type of 1337 do you want? 1 for basic, 2 for intermediate, \
3 for intermediate-advanced, and 4 for ultimate.")
if level == "1":
from b4s1c_l33t import leetkey
elif level == "2":
from In73rm3d1473_1337 import leetkey
elif level == "3":
from In7_4DV import leetkey
from In7_4DV import combokey
elif level == "4":
from U17IM473_1337 import leetkey
from U17IM473_1337 import combokey
for char in inquiry:
if char in leetkey:
newPrint1 += leetkey[char]
else:
newPrint1 += char #Checks to see if the char is in the single-char list, then appends it accordingly
if int(level) >= 3:
for item in combokey:
if item in newPrint1:
newPrint1 = newPrint1.replace(item, combokey[item])
print newPrint1 #Print answer
question = raw_input(r"Do you want to translate some more? Type Y or N ") #Asks if they want to do more
question = question.lower() #Changes it to lowercase, for sending through the if loop
if question == "y" or question == "Y":
translator() #If answer is yes, program calls the entire function again
elif question != "y" and question != "n" and question != "Y" and question != "N":
print "I didn't quite catch that."
ps = raw_input("Would you like to export your leetness to a file? Type Y or N ")
if ps == "Y" or ps == "y":
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./1337Export.ps1\";", "&export"])
else:
print r"0|<. 600|)|3`/3!"
translator() #calls the function once
Powershell script:
Function export(){
$param = Read-Host("Copy-paste the translation from above here! ")
New-Item C:\Scripts\1337\1337ness.txt -type file -value $param
}
But I also know that the script was working perfectly up until I added the Powershell to it, so the problem is either in my usage of the subprocess module or in the Powershell script itself. I am a somewhat-medium-beginner at using Powershell, so any help will be greatly appreciated. Either that, or if there is a way to create the new file and write data to it in Python itself, that would be greatly appreciated.
Thanks,
Prem
Note: in the Python script, the leetkey and combokey are in separate files that are imported based on the value of the variable level.
UPDATE: I looked at the page here, and the subprocess code in the Python script is what I found in that page. It did not work, but instead threw an error saying that the export function does not exist, which it obviously does... in Powershell. Thanks again!
Your parameter construction is off. You want to run the following commandline in PowerShell:
. "./1337Export.ps1"; & export
which basically means "dot-source (IOW import) the script 1337Export.ps1 from the current working directory, then call (&) the function export".
The cleanest way to do this is to put the statement in a scriptblock:
&{. "./1337Export.ps1"; & export}
and pass that scriptblock as a single argument, so your Python statement should look like this:
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", '-Command', '&{. "./1337Export.ps1"; & export}'])
Of course you need to make sure that 1337Export.ps1 actually exists in the current working directory when you execute the Python script.
You have to do two things:
1) dot source the script (which is similar to python's import), and
2) subprocess.call.
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePS\";", "&export"])
Note: I have assumed that both the .py and .ps1 are residing in the same directory and the name of the powershell script is "SamplePS" and from that script I am using the function "export"
Hope it helps

Python script to convert adblock list in a forbidden file for Polipo proxy (regex)

On my system I currently running Polipo proxy, mainly for adblock purposes.
By a search on internet I've found many shell scripts to convert adblock plus lists in Polipo forbidden file format; most of these scripts rely on sed, ruby or python.
However none of them is able to generate a valid forbidden file: when I restart Polipo with the new generated forbidden file, in the Polipo's log file I see the message: "Couldn't compile regex: Unmatched ( or \("
The following python script which I attempt to use, is intended to convert an easylist file in a Polipo's forbidden file format:
#!/bin/python
# convert adblock ruleset into polipo-forbidden format
if __name__ == "__main__":
import os
import sys
import re
if len(sys.argv) == 1:
sys.exit("Usage: %s <adblockrules>" % os.path.basename(sys.argv[0]))
if not os.path.exists(sys.argv[1]):
sys.exit("The rules file (%s) doesn't exist" % sys.argv[1])
fhandle = file(sys.argv[1])
lines = fhandle.readlines()
fhandle.close()
dollar_re = re.compile("(.*?)\$.*")
for line in lines:
if line:
if (line[0] in ("[", "!", "~", "#", "#") or
line.startswith("/adverti") or
"##" in line):
continue
line = dollar_re.sub(r"\1", line)
# line = line.replace("|http://", "")
line = line.replace("|", "")
line = line.replace("||", "")
line = line.replace(".", r"\.")
line = line.replace("*", ".*")
line = line.replace("?", r"\?")
line = line.replace("^", r"[\/:\.=&\?\+\-\ ]+")
# line = line.replace("&", r"\&")
# line = line.replace("+", r"\+")
# line = line.replace("-", r"\-")
# line = line.replace(";", r"\;")
# line = line.replace("=", r"\=")
# line = line.replace("/", r"\/")
print(line.strip())
print("")
But as I've said, when I actualize this forbidden file, Polipo will claim "Couldn't compile regex: Unmatched ( or \("
This one is the forbidden file generated by the script
http://wikisend.com/download/494664/forbidden.conf
As I've said, online, there are many scripts like the one which I use, some of them also relies on sed, but no one seems able to generate a valid forbidden file (Polipo will always claims "Couldn't compile regex").
This is not a Polipo's fault, because if I made a clean forbidden file with some web url inside, Polipo will properly block these connections.
Can someone help me and explain how to modify/make a proper script to convert adblock lists in a valid regex forbidden file for Polipo?
Many thanks.
You can convert an Adblock rule to a Python regex using https://github.com/scrapinghub/adblockparser library:
>>> from adblockparser import AdblockRule
>>> rule = AdblockRule("/ad/loaders/*")
>>> print(rule.regex)
/ad/loaders/.*
I'm not sure Polipo suports the same regex format though; regexes can get pretty hairy:
>>> print(AdblockRule("||example.com$").regex)
^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?example\.com
Also take care of rules with options; it may be better to remove them because semantics is different.
Hope this helps.

error bash: syntax error near unexpected token `(' my code is correct

I am trying to implement a hash function and here is my code:
import BitVector
import glob
path = '/home/vguda/Desktop/.txt'
files=glob.glob(path)
hash = BitVector.BitVector(size = 32)
hash.reset(0)
i = 0
for file in files:
bv = BitVector.BitVector( filename = file )
while 1 :
bv1 = bv.read_bits_from_file(8)
if str(bv1) == "":
break
hash[0:8] = bv1 ^ hash[0:8]
hash >> 8
i = i+1
hash_str = ""
hash_str = str( hash )
text_file = open("/home/vguda/Desktop/result.txt ","w")
text_file.write("Hash Code is %s" %hash_str)
text_file.close()
print hash
print (i)
The displayed error is:
"bash: syntax error near unexpected token `('
First, perhaps this happened in copy and paste, but your indenting in your loop is all messed up, I'm not sure which blocks go where.
When you run things in the shell, you need to either tell python to run it:
python myscript.py
Or, put the following line as the first thing in your program to tell bash to run it as a python program:
#!/usr/bin/python
Currently, bash is trying to run your python program as a bash script, and obviously running into syntax errors.

c++ macro for saving enum element names and values to file

Normally I try to avoid the use of macros, so I actually don't know how to use them beyond the very most basic ones, but I'm trying to do some meta-manipulation so I assume macros are needed.
I have an enum listing various log entries and their respective id, e.g.
enum LogID
{
LOG_ID_ITEM1=0,
LOG_ID_ITEM2,
LOG_ID_ITEM3=10,
...
}
which is used within my program when writing data to the log file. Note that they will not, in general, be in any order.
I do most of my log file post-processing in Matlab so I'd like to write the same variable names and values to a file for Matlab to load in. e.g., a file looking like
LOG_ID_ITEM1=0;
LOG_ID_ITEM2=1;
LOG_ID_ITEM3=10;
...
I have no idea how to go about doing this, but it seems like it shouldn't be too complicated. If it helps, I am using c++11.
edit:
For clarification, I'm not looking for the macro itself to write the file. I want a way to store the enum element names and values as strings and ints somehow so I can then use a regular c++ function to write everything to file. I'm thinking the macro might then be used to build up the strings and values into vectors? Does that work? If so, how?
I agree with Adam Burry that a separate script is likely best for this. Not sure which languages you're familiar with, but here's a quick Python script that'll do the job:
#!/usr/bin/python
'''Makes a .m file from an enum in a C++ source file.'''
from __future__ import print_function
import sys
import re
def parse_cmd_line():
'''Gets a filename from the first command line argument.'''
if len(sys.argv) != 2:
sys.stderr.write('Usage: enummaker [cppfilename]\n')
sys.exit(1)
return sys.argv[1]
def make_m_file(cpp_file, m_file):
'''Makes an .m file from enumerations in a .cpp file.'''
in_enum = False
enum_val = 0
lines = cpp_file.readlines()
for line in lines:
if in_enum:
# Currently processing an enumeration
if '}' in line:
# Encountered a closing brace, so stop
# processing and reset value counter
in_enum = False
enum_val = 0
else:
# No closing brace, so process line
if '=' in line:
# If a value is supplied, use it
ev_string = re.match(r'[^=]*=(\d+)', line)
enum_val = int(ev_string.group(1))
# Write output line to file
e_out = re.match(r'[^=\n,]+', line)
m_file.write(e_out.group(0).strip() + '=' +
str(enum_val) + ';\n')
enum_val += 1
else:
# Not currently processing an enum,
# so check for an enum definition
enumstart = re.match(r'enum \w+ {', line)
if enumstart:
in_enum = True
def main():
'''Main function.'''
# Get file names
cpp_name = parse_cmd_line()
m_name = cpp_name.replace('cpp', 'm')
print('Converting ' + cpp_name + ' to ' + m_name + '...')
# Open the files
try:
cpp_file = open(cpp_name, 'r')
except IOError:
print("Couldn't open " + cpp_name + ' for reading.')
sys.exit(1)
try:
m_file = open(m_name, 'w')
except IOError:
print("Couldn't open " + m_name + ' for writing.')
sys.exit(1)
# Translate the cpp file
make_m_file(cpp_file, m_file)
# Finish
print("Done.")
cpp_file.close()
m_file.close()
if __name__ == '__main__':
main()
Running ./enummaker.py testenum.cpp on the following file of that name:
/* Random code here */
enum LogID {
LOG_ID_ITEM1=0,
LOG_ID_ITEM2,
LOG_ID_ITEM3=10,
LOG_ID_ITEM4
};
/* More random code here */
enum Stuff {
STUFF_ONE,
STUFF_TWO,
STUFF_THREE=99,
STUFF_FOUR,
STUFF_FIVE
};
/* Yet more random code here */
produces a file testenum.m containing the following:
LOG_ID_ITEM1=0;
LOG_ID_ITEM2=1;
LOG_ID_ITEM3=10;
LOG_ID_ITEM4=11;
STUFF_ONE=0;
STUFF_TWO=1;
STUFF_THREE=99;
STUFF_FOUR=100;
STUFF_FIVE=101;
This script assumes that the closing brace of an enum block is always on a separate line, that the first identifier is defined on the line following the opening brace, that there are no blank lines between the braces, that enum appears at the start of a line, and that there is no space following the = and the number. Easy enough to modify the script to overcome these limitations. You could have your makefile run this automatically.
Have you considered "going the other way"? It usually makes more sense to maintain your data definitions in a (text) file, then as part of your build process you can generate a C++ header and include it. Python and mako is a good tool for doing this.