python - latexmk: error: no such option: -d - python

I am getting an error when I want to run a python script:
The error is following one:
The code is given below:
#!/usr/bin/python
import subprocess
code_dir = "code"
title = "Stanford ACM-ICPC Team Notebook"
def get_sections():
sections = []
section_name = None
with open('contents.txt', 'r') as f:
for line in f:
if '#' in line: line = line[:line.find('#')]
line = line.strip()
if len(line) == 0: continue
if line[0] == '[':
section_name = line[1:-1]
subsections = []
if section_name is not None:
sections.append((section_name, subsections))
else:
tmp = line.split('\t', 1)
if len(tmp) == 1:
raise ValueError('Subsection parse error: %s' % line)
filename = tmp[0]
subsection_name = tmp[1]
if subsection_name is None:
raise ValueError('Subsection given without section')
subsections.append((filename, subsection_name))
return sections
def get_style(filename):
ext = filename.lower().split('.')[-1]
if ext in ['c', 'cc', 'cpp']:
return 'cpp'
elif ext in ['java']:
return 'java'
elif ext in ['py']:
return 'py'
else:
return 'txt'
# TODO: check if this is everything we need
def texify(s):
#s = s.replace('\'', '\\\'')
#s = s.replace('\"', '\\\"')
return s
def get_tex(sections):
tex = ''
for (section_name, subsections) in sections:
tex += '\\section{%s}\n' % texify(section_name)
for (filename, subsection_name) in subsections:
tex += '\\subsection{%s}\n' % texify(subsection_name)
tex += '\\raggedbottom\\lstinputlisting[style=%s]{%s/%s}\n' % (get_style(filename), code_dir, filename)
tex += '\\hrulefill\n'
tex += '\n'
return tex
if __name__ == "__main__":
sections = get_sections()
tex = get_tex(sections)
with open('contents.tex', 'w') as f:
f.write(tex)
latexmk_options = ["latexmk", "-pdf", "notebook.tex"]
subprocess.call(latexmk_options)
I have already tried to install latexmk, But didn't succeed.
Can you help me about the detailed instruction of installation latexmk. I have already googled much. And for copyright thats not even my code. Its a code from stanford acm to make their own. Now I want to use to make my own.

Make sure that latexmk is accessible from your command line. You can check this by typing latexmk -version from your command line. If it is not accessible from command line then you need to add the latexmk path to environment variable.
If latexmk is not installed follow this link to properly install the latexmk.
I think following these steps might fix your problem.

Related

Simplified grep in python

I need to create a simplified version of grep in python which will print a line when a keyword is used such as using this command "python mygrep.py duck animals.txt" and getting the output, "The duck goes quack". I have a file where it contains different outputs but I'm not sure how to get it to print the line that contains the "keyword" such as the line with "duck" in it. Im suppose to only use "import sys" and not "re" since its suppose to be a simple version.
import sys
def main():
if len(sys.argv) != 3:
exit('Please pass 2 arguments.')
search_text = sys.argv[1]
filename = sys.argv[2]
with open("animals.txt", 'r') as f:
text = f.read()
for line in text:
print(line)
if __name__ == '__main__':
main()
The operator 'in' should be sufficient.
for line in text:
if search_text in line:
print(line)
Here is a an implementation of grep in python with after/before feature:
def _fetch_logs(self, data, log_file, max_result_size, current_result_size):
after = data.get("after", 0)
before = data.get("before", 0)
exceeded_max = False
result = []
before_counter = 0
frame = []
found = False
for line in log_file:
frame.append(line)
match_patterns = all(self._search_in(data, pattern, line) for pattern in data["patterns"])
if match_patterns:
before_counter = len(frame)
found = True
if not found and len(frame) > before:
frame.pop(0)
if found and len(frame) >= before_counter + after:
found = False
before_counter = 0
result += frame
frame = []
if current_result_size + len(result) >= max_result_size:
exceeded_max = True
break
if found:
result += frame
return exceeded_max, result

Update-alternatives Module Ansible

I'm trying to update 'alternatives' module for Ansible.
The default module can be found here : https://github.com/ansible/ansible-modules-extras/blob/devel/system/alternatives.py
I'm trying to add the remove arg for update-alternatives command.
My updated code is the following :
DEFAULT_LINK_PRIORITY = 50
def main():
module = AnsibleModule(
argument_spec = dict(
name = dict(required=True),
path = dict(required=True),
link = dict(required=False),
### Mode Added by isador999 ###
mode = dict(required=False),
)
)
params = module.params
name = params['name']
path = params['path']
link = params['link']
### Mode Added by isador999 ###
mode = params['mode']
UPDATE_ALTERNATIVES = module.get_bin_path('update-alternatives',True)
current_path = None
all_alternatives = []
(rc, query_output, query_error) = module.run_command(
[UPDATE_ALTERNATIVES, '--query', name]
)
if rc == 0:
for line in query_output.splitlines():
split_line = line.split(':')
if len(split_line) == 2:
key = split_line[0]
value = split_line[1].strip()
if key == 'Value':
current_path = value
elif key == 'Alternative':
all_alternatives.append(value)
elif key == 'Link' and not link:
link = value
if not mode or mode == "install":
if current_path != path:
try:
# install the requested path if necessary
if path not in all_alternatives:
module.run_command(
[UPDATE_ALTERNATIVES, '--install', link, name, path, str(DEFAULT_LINK_PRIORITY)],
check_rc=True
)
# select the requested path
module.run_command(
[UPDATE_ALTERNATIVES, '--set', name, path],
check_rc=True
)
module.exit_json(changed=True)
except subprocess.CalledProcessError, cpe:
module.fail_json(msg=str(dir(cpe)))
else:
module.exit_json(changed=False)
elif mode == "remove":
if current_path == path:
module.run_command(
[UPDATE_ALTERNATIVES, '--remove', name, path],
check_rc=True
from ansible.module_utils.basic import *
main()
When I use this new module, with install or remove mode, Ansible returns to me :
failed: [HOST] => {"failed": true, "parsed": false}
invalid output was:
* keychain 2.7.1 ~ http://www.funtoo.org
* Found existing ssh-agent: 2352
* Known ssh key: /path/id_rsa
FATAL: all hosts have already failed -- aborting
With remove mode, the script seems to be working, my Java links are correctly deleted, but I don't understand what Ansible is searching to have no error ...
Have you any idea ?
If your code above is copy-pasted as-is, then one problem is that you are importing from ansible.module_utils.basic after the main() function.
main() needs the definition of AnsibleModule to be available when parsed. You can see the imports happening at the very top of the original file, in comparison.
HTH

Print text between two separators?

I have config file:
$ cat ../secure/test.property
#<TITLE>Connection setting
#MAIN DEV
jdbc.main.url=
jdbc.main.username=
jdbc.main.password=
#<TITLE>Mail settings
mail.smtp.host=127.0.0.1
mail.smtp.port=25
mail.smtp.on=false
email.subject.prefix=[DEV]
#<TITLE>Batch size for package processing
exposureImportService.batchSize=10
exposureImportService.waitTimeInSecs=10
ImportService.batchSize=400
ImportService.waitTimeInSecs=10
#<TITLE>Other settings
usePrecalculatedAggregation=true
###################### Datasource wrappers, which allow to log additional information
bean.datasource.query_log_wrapper=mainDataSourceWrapper
bean.gpc_datasource.query_log_wrapper=gpcDataSourceWrapper
time.to.keep.domain=7*12
time.to.keep.uncompress=1
#oracle max batch size
dao.batch.size.max=30
And function, which return line "#<TITLE>Other settings" (for example), to select "config section".
Next, need to print all lines between selected "section", and next line, startwith #<TITLE>.
How it can be realized?
P.S.
def select_section(property_file):
while True:
with open(os.path.join(CONF_DIR, property_file), 'r+') as file:
text = file.readlines()
list = []
print()
for i in text:
if '<TITLE>' in i:
line = i.lstrip('#<TITLE>').rstrip('\n')
list.append(line)
print((list.index(line)), line)
res_section = int(raw_input('\nPlease, select section to edit: '))
print('You selected: %s' % list[res_section])
if answer('Is it OK? '):
return(list[res_section])
break
And it's work like:
...
0 Connection setting
1 Mail settings
2 Batch size for package processing
3 Other settings
Please, select section to edit:
...
And expected output, if select Connection setting:
...
0 jdbc.main.url
1 jdbc.main.username
2 jdbc.main.password
Please, select line to edit:
...
If I understand the problem correctly, here's a solution that assembles the requested section as it reads the file:
def get_section(section):
marker_line = '#<TITLE>{}'.format(section)
in_section = False
section_lines = []
with open('test.property') as f:
while True:
line = f.readline()
if not line:
break
line = line.rstrip()
if line == marker_line:
in_section = True
elif in_section and line.startswith('#<TITLE>'):
break
if in_section:
if not line or line.startswith('#'):
continue
section_lines.append(line)
return '\n'.join(['{} {}'.format(i, line)
for i, line in enumerate(section_lines)])
print get_section('Connection setting')
Output:
0 jdbc.main.url=
1 jdbc.main.username=
2 jdbc.main.password=
Perhaps this will get you started.
Here's a quick solution:
def get_section(section):
results = ''
with open('../secure/test.property') as f:
lines = [l.strip() for l in f.readlines()]
indices = [i for i in range(len(lines)) if lines[i].startswith('#<TITLE>')]
for i in xrange(len(indices)):
if lines[indices[i]] == '#<TITLE>' + section:
for j in xrange(indices[i], indices[i+1] if i < len(indices)-1 else len(lines) - 1):
results += lines[j] + '\n'
break
return results
You can use it like:
print get_section('Connection setting')
Not very elegant but it works!

Getting IO error in Python

When I try to execute one particular python file. I am getting
following errors
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
g.stem(u"തുറക്കുക")
File "/usr/local/lib/python2.7/dist-packages/indicstemmer-0.1-py2.7.egg/indicstemmer/core.py", line 48, in stem
self.rulesDict = self.LoadRules()
File "/usr/local/lib/python2.7/dist-packages/indicstemmer-0.1-py2.7.egg/indicstemmer/core.py", line 81, in LoadRules
errors='ignore')
File "/usr/lib/python2.7/codecs.py", line 881, in open
file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: '/usr/local/lib/python2.7/dist-packages/indicstemmer-0.1-py2.7.egg/indicstemmer/stemmer_ml.rules'
What is the problem here?
class Stemmer:
"""
Instantiate class to get the methods
"""
def __init__(self):
self.rules_file = os.path.join(os.path.dirname(__file__), \
'stemmer_ml.rules')
self.rulesDict = None
self.normalizer = normalizer.getInstance()
def stem(self, text):
"""
:param text: unicode encoded malayalam string
:returns: dictionary with words as the key and the stemmer result
as the values. stems all the words in the given text and
returns a dictionary
"""
text = self.normalizer.normalize(text)
if self.rulesDict is None:
self.rulesDict = self.LoadRules()
words = text.split(" ")
word_count = len(words)
result_dict = dict()
word_iter = 0
word = ""
while word_iter < word_count:
word = words[word_iter]
word = self.trim(word)
word = word.strip('!,.?:')
word_length = len(word)
suffix_pos_itr = 2
word_stemmed = ""
while suffix_pos_itr < word_length:
suffix = word[suffix_pos_itr:word_length]
if suffix in self.rulesDict:
word_stemmed = word[0:suffix_pos_itr] + \
self.rulesDict[suffix]
break
suffix_pos_itr = suffix_pos_itr+1
word_iter = word_iter+1
if(word_stemmed == ""):
word_stemmed = word
result_dict[ word ] = word_stemmed
print result_dict[2]
return result_dict
def LoadRules(self):
#print "Loading the rules..."
rules_dict = dict()
line = []
line_number = 0
rule_number = 0
rules_file = codecs.open(self.rules_file, encoding='utf-8', \
errors='ignore')
while 1:
line_number = line_number +1
text = unicode( rules_file.readline())
if text == "":
break
if text[0] == '#':
continue #this is a comment - ignore
text = text.split("#")[0] #remove the comment part of the line
line_number = line_number +1
line = text.strip() # remove unwanted space
if(line == ""):
continue
if(len(line.split("=")) != 2):
print "[Error] Syntax Error in the Rules. Line number: ", \
line_number
print "Line: "+ text
continue
lhs = line.split("=")[0].strip()
rhs = line.split("=")[1].strip()
if(len(rhs)>0):
if(lhs[0] == '"'):
lhs = lhs[1:len(lhs)] # if the string is "quoted"
if(lhs[len(lhs)-1] == '"'):
lhs = lhs[0:len(lhs)-1] # if the string is "quoted"
if(len(rhs)>0):
if(rhs[0] == '"'):
rhs = rhs[1:len(rhs)] # if the string is "quoted"
if(rhs[len(rhs)-1] == '"'):
rhs = rhs[0:len(rhs)-1] # if the string is "quoted"
rule_number = rule_number+1
rules_dict[lhs] = rhs
#print "[", rule_number ,"] " +lhs + " : " +rhs
#print "Found ",rule_number, " rules."
return rules_dict
setup file
from setuptools import setup, find_packages
name = "indicstemmer"
setup(
name=name,
version="0.1",
license="LGPL-3.0",
description="Malayalam word stemmer",
long_description="""This application helps you to stem the words
in the given text. Currently supports only
Note that this is very experimental and uses a rule based approach.
""",
packages=find_packages(),
include_package_data=True,
setup_requires=['setuptools-git'],
install_requires=['setuptools','normalizer'],
test_suite="tests",
zip_safe=False,
)
Test
import unittest
from indicstemmer import getInstance
class TestIndicStemmer(unittest.TestCase):
def setUp(self):
self.instance = getInstance()
def test_stemmer(self):
self.assertEqual(u"തുറക്കുക",self.instance.stem(u"തുറക്കുന്ന")[u"തുറക്കുന്ന"])
def main():
suite = unittest.TestLoader().loadTestsFromTestCase(TestIndicStemmer)
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == "__main__":
main()
I am using Ubuntu 12.04 desktop version
The significant line of the error message is
File "/usr/lib/python2.7/codecs.py", line 881, in open
file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: '/usr/local/lib/python2.7/dist-packages/indicstemmer-0.1-py2.7.egg/indicstemmer/stemmer_ml.rules'
This implies that the indicstemmer modules had not been installed properly because the required file stemmer_ml.rules could not be found.
check that you do not need to set up defaults before you call gstem() and that the permissions in the python library allow you to get to the rules. Other than that the library package my need to be reinstalled. I have noticed that if different versions of python exist, sometimes packages get installed in the wrong version. However, I doubt it in this case because it got all the way to the rules file before crashing.

Searching a file for matches between two values and outputting search hits in Python

I am (attempting) to write a program that searches through a hex file for instances of a hex string between two values, eg. Between D4135B and D414AC, incrementing between the first value until the second is reached- D4135B, D4135C, D4135D etc etc.
I have managed to get it to increment etc, but it’s the search part I am having trouble with.
This is the code I have so far, it's been cobbled together from other places and I need to make it somehow output all search hits into the output file (file_out)
I have exceeded the limit of my Python understanding and I'm sure there's probably a much easier way of doing this. I would be very grateful for any help.
def search_process(hx): # searching for two binary strings
global FLAG
while threeByteHexPlusOne != threeByteHex2: #Keep incrementing until second value reached
If Flag:
if hx.find(threeByteHex2) != -1:
FLAG = False #If threeByteHex = ThreeByteHexPlusOne, end search
Print (“Reached the end of the search”,hx.find(threeByteHexPlusOne))
Else:
If hx.find(threeByteHexPlusOne) != -1:
FLAG = True
Return -1 #If no results found
if __name__ == '__main__':
try:
file_in = open(FILE_IN, "r") #opening input file
file_out = open(FILE_OUT, 'w') #opening output file
hx_read = file_in.read #read from input file
tmp = ''
found = ''
while hx_read: #reading from file till file is empty
hx_read = tmp + hx_read
pos = search_process(hx_read)
while pos != -1:
hex_read = hx_read[pos:]
if FLAG:
found = found + hx_read
pos = search_process(hx_read)
tmp = bytes_read[]
hx_read = file_in.read
file_out.write(found) #writing to output file
except IOError:
print('FILE NOT FOUND!!! Check your filename or directory/PATH')
Here's a program that looks through a hex string from a file 3 bytes at a time and if the 3-byte hex string is between the given hex bounds, it writes it to another file. It makes use of generators to make getting the bytes from the hex string a little cleaner.
import base64
import sys
_usage_string = 'Usage: python {} <input_file> <output_file>'.format(sys.argv[0])
def _to_base_10_int(value):
return int(value, 16)
def get_bytes(hex_str):
# Two characters equals one byte
for i in range(0, len(hex_str), 2):
yield hex_str[i:i+2]
def get_three_byte_hexes(hex_str):
bytes = get_bytes(hex_str)
while True:
try:
three_byte_hex = next(bytes) + next(bytes) + next(bytes)
except StopIteration:
break
yield three_byte_hex
def find_hexes_in_range(hex_str, lower_bound_hex, upper_bound_hex):
lower_bound = _to_base_10_int(lower_bound_hex)
upper_bound = _to_base_10_int(upper_bound_hex)
found = []
for three_byte_hex in get_three_byte_hexes(hex_str):
hex_value = _to_base_10_int(three_byte_hex)
if lower_bound <= hex_value < upper_bound:
found.append(three_byte_hex)
return found
if __name__ == "__main__":
try:
assert(len(sys.argv) == 3)
except AssertionError:
print _usage_string
sys.exit(2)
file_contents = open(sys.argv[1], 'rb').read()
hex_str = base64.decodestring(file_contents).encode('hex')
found = find_hexes_in_range(hex_str, 'D4135B', 'D414AC')
print('Found:')
print(found)
if found:
with open(sys.argv[2], 'wb') as fout:
for _hex in found:
fout.write(_hex)
Check out some more info on generators here

Categories