def read_pdns_conf(path='/etc/powerdns/pdns.conf'):
global api_host
global api_port
global api_key
try:
for line in fileinput.input([path]):
if line[0] == '#' or line[0] == '\n':
continue
try:
(key, val) = line.rstrip().split('=')
if key == 'webserver-address':
api_host = val
elif key == 'webserver-port':
api_port = int(val)
elif key == 'experimental-api-key':
api_key = val
except:
pass
except:
raise
python类input()的实例源码
def replacestrs(filename):
"replace a certain type of string occurances in all files in a directory"
files = glob.glob(filename)
#print 'files in files:', files
stext = '-d0'
rtext = '-r0'
for line in fileinput.input(files,inplace=1):
lineno = 0
lineno = string.find(line, stext)
if lineno >0:
line =line.replace(stext, rtext)
sys.stdout.write(line)
def set_robotframework_vars(cls, odlusername="admin", odlpassword="admin"):
"""Set credentials in csit/variables/Variables.robot.
Returns:
True if credentials are set.
False otherwise.
"""
try:
for line in fileinput.input(cls.odl_variables_file,
inplace=True):
print(re.sub("@{AUTH}.*",
"@{{AUTH}} {} {}".format(
odlusername, odlpassword),
line.rstrip()))
return True
except Exception: # pylint: disable=broad-except
cls.__logger.exception("Cannot set ODL creds:")
return False
def linkedin_search():
linkedin_login()
time.sleep(2)
x = driver.find_element_by_class_name('type-ahead-input')
search = x.find_element_by_tag_name('input')
search.send_keys('harvard')
search.send_keys(Keys.ENTER)
time.sleep(8)
new_url = (driver.current_url).replace('index', 'schools')
new_url = new_url.replace('GLOBAL_SEARCH_HEADER', 'SWITCH_SEARCH_VERTICAL')
driver.get(new_url)
time.sleep(5)
driver.find_element_by_css_selector('#ember1790').click()
time.sleep(5)
x = driver.find_element_by_class_name('company-actions-bar')
x.find_element_by_tag_name('a').click()
time.sleep(5)
start_year = driver.find_element_by_id('alumni-search-year-start')
end_year = driver.find_element_by_id('alumni-search-year-end')
start_year.send_keys('2014')
start_year.send_keys(Keys.ENTER)
time.sleep(3)
list_of_people = driver.find_elements_by_class_name('org-alumni-profiles-module__profiles-list-item')
for i in list_of_people:
print(i.text)
def start_cracking_engine(self):
print "[+] Loading Zipfile... ",
fileload=zipfile.ZipFile(self.filename)
print "OK"
if self.dictionery:
print "[+] Using Dictonery Option.... OK"
print "[+] Loading Dictonery File... OK"
print "[+] Brute Force Started ..."
for i in fileinput.input(self.dictionery):
pwd=i.strip('\n')
self.extracting_engine(fileload,pwd)
if self.crunch:
print "[+] Connection Stablished as Pipe... OK"
print "[+] Brute Force Started ..."
for i in sys.stdin:
pwd=i.strip('\n')
self.extracting_engine(fileload,pwd)
self.show_info_message()
return
def lastvm(name, delete=False):
configdir = "%s/.kcli/" % os.environ.get('HOME')
vmfile = "%s/vm" % configdir
if not os.path.exists(configdir):
os.mkdir(configdir)
if delete:
if not os.path.exists(vmfile):
return
else:
os.system("sed -i '/%s/d' %s/vm" % (name, configdir))
return
if not os.path.exists(vmfile) or os.stat(vmfile).st_size == 0:
with open(vmfile, 'w') as f:
f.write(name)
return
firstline = True
for line in fileinput.input(vmfile, inplace=True):
line = "%s\n%s" % (name, line) if firstline else line
print line,
firstline = False
def _set_x0(self, x0):
if x0 == str(x0):
x0 = eval(x0)
self.x0 = array(x0) # should not have column or row, is just 1-D
if self.x0.ndim == 2:
if self.opts.eval('verbose') >= 0:
_print_warning('input x0 should be a list or 1-D array, trying to flatten ' +
str(self.x0.shape) + '-array')
if self.x0.shape[0] == 1:
self.x0 = self.x0[0]
elif self.x0.shape[1] == 1:
self.x0 = array([x[0] for x in self.x0])
if self.x0.ndim != 1:
raise _Error('x0 must be 1-D array')
if len(self.x0) <= 1:
raise _Error('optimization in 1-D is not supported (code was never tested)')
self.x0.resize(self.x0.shape[0]) # 1-D array, not really necessary?!
# ____________________________________________________________
# ____________________________________________________________
def __call__(self, x, inverse=False): # function when calling an object
"""Rotates the input array `x` with a fixed rotation matrix
(``self.dicMatrices['str(len(x))']``)
"""
x = np.array(x, copy=False)
N = x.shape[0] # can be an array or matrix, TODO: accept also a list of arrays?
if str(N) not in self.dicMatrices: # create new N-basis for once and all
rstate = np.random.get_state()
np.random.seed(self.seed) if self.seed else np.random.seed()
B = np.random.randn(N, N)
for i in range(N):
for j in range(0, i):
B[i] -= np.dot(B[i], B[j]) * B[j]
B[i] /= sum(B[i]**2)**0.5
self.dicMatrices[str(N)] = B
np.random.set_state(rstate)
if inverse:
return np.dot(self.dicMatrices[str(N)].T, x) # compute rotation
else:
return np.dot(self.dicMatrices[str(N)], x) # compute rotation
# Use rotate(x) to rotate x
def main():
"""
Parse arguments and start the program
"""
# Iterate over all lines in all files
# listed in sys.argv[1:]
# or stdin if no args given.
try:
for line in fileinput.input():
# Look for an INSERT statement and parse it.
if is_insert(line):
values = get_values(line)
if values_sanity_check(values):
parse_values(values, sys.stdout)
except KeyboardInterrupt:
sys.exit(0)
def _create_combined_bundle_file(self):
leap_ca_bundle = ca_bundle.where()
if self._ca_cert_path == leap_ca_bundle:
return self._ca_cert_path # don't merge file with itself
elif not self._ca_cert_path:
return leap_ca_bundle
tmp_file = tempfile.NamedTemporaryFile(delete=False)
with open(tmp_file.name, 'w') as fout:
fin = fileinput.input(files=(leap_ca_bundle, self._ca_cert_path))
for line in fin:
fout.write(line)
fin.close()
return tmp_file.name
def __init__(self):
super(SessionStdIn, self).__init__()
for current_string in fileinput.input("-"):
read_lines = 0
current_line = [x.strip() for x in current_string.split(options.cfg.input_separator)]
if current_line:
if options.cfg.file_has_headers and not self.header:
self.header = current_line
else:
if read_lines >= options.cfg.skip_lines:
query_string = current_line.pop(options.cfg.query_column_number - 1)
new_query = self.query_type(query_string, self)
self.query_list.append(new_query)
self.max_number_of_input_columns = max(len(current_line), self.max_number_of_input_columns)
read_lines += 1
logger.info("Reading standard input ({} {})".format(len(self.query_list), "query" if len(self.query_list) == 1 else "queries"))
if options.cfg.skip_lines:
logger.info("Skipping first %s %s." % (options.cfg.skip_lines, "query" if options.cfg.skip_lines == 1 else "queries"))
def _set_x0(self, x0):
if x0 == str(x0):
x0 = eval(x0)
self.x0 = array(x0) # should not have column or row, is just 1-D
if self.x0.ndim == 2:
if self.opts.eval('verbose') >= 0:
_print_warning('input x0 should be a list or 1-D array, trying to flatten ' +
str(self.x0.shape) + '-array')
if self.x0.shape[0] == 1:
self.x0 = self.x0[0]
elif self.x0.shape[1] == 1:
self.x0 = array([x[0] for x in self.x0])
if self.x0.ndim != 1:
raise _Error('x0 must be 1-D array')
if len(self.x0) <= 1:
raise _Error('optimization in 1-D is not supported (code was never tested)')
self.x0.resize(self.x0.shape[0]) # 1-D array, not really necessary?!
# ____________________________________________________________
# ____________________________________________________________
def __call__(self, x, inverse=False): # function when calling an object
"""Rotates the input array `x` with a fixed rotation matrix
(``self.dicMatrices['str(len(x))']``)
"""
x = np.array(x, copy=False)
N = x.shape[0] # can be an array or matrix, TODO: accept also a list of arrays?
if str(N) not in self.dicMatrices: # create new N-basis for once and all
rstate = np.random.get_state()
np.random.seed(self.seed) if self.seed else np.random.seed()
B = np.random.randn(N, N)
for i in range(N):
for j in range(0, i):
B[i] -= np.dot(B[i], B[j]) * B[j]
B[i] /= sum(B[i]**2)**0.5
self.dicMatrices[str(N)] = B
np.random.set_state(rstate)
if inverse:
return np.dot(self.dicMatrices[str(N)].T, x) # compute rotation
else:
return np.dot(self.dicMatrices[str(N)], x) # compute rotation
# Use rotate(x) to rotate x
def REPIC(obToPrint):
'''REPIC stands for Read, Evaluate, Print In Comment. Call this function with an object obToPrint and it will rewrite the current file with the output in the comment in a line after this was called.'''
cf = inspect.currentframe()
callingFile = inspect.getfile(cf.f_back)
callingLine = cf.f_back.f_lineno
# print 'Line I am calling REPIC from:', callingLine
for line in fileinput.input(callingFile, inplace=1):
if callingLine == fileinput.filelineno():
# Make results, but get rid of newlines in output since that will break the comment:
resultString = '#OUTPUT: ' + str(obToPrint).replace('\n','\\n') +'\n'
writeIndex = line.rfind('\n')
# Watch out for last line without newlines, there the end is just the line length.
if '\n' not in line:
writeIndex = len(line)
# Replace old output and/or any comments:
if '#' in line:
writeIndex = line.rfind('#')
output = line[0:writeIndex] + resultString
else:
output = line # If no REPIC, then don't change the line.
sys.stdout.write(output)
def patch_step(self):
"""Patch Boost source code before building."""
super(EB_Boost, self).patch_step()
# TIME_UTC is also defined in recent glibc versions, so we need to rename it for old Boost versions (<= 1.49)
glibc_version = get_glibc_version()
old_glibc = glibc_version is not UNKNOWN and LooseVersion(glibc_version) > LooseVersion("2.15")
if old_glibc and LooseVersion(self.version) <= LooseVersion("1.49.0"):
self.log.info("Patching because the glibc version is too new")
files_to_patch = ["boost/thread/xtime.hpp"] + glob.glob("libs/interprocess/test/*.hpp")
files_to_patch += glob.glob("libs/spirit/classic/test/*.cpp") + glob.glob("libs/spirit/classic/test/*.inl")
for patchfile in files_to_patch:
try:
for line in fileinput.input("%s" % patchfile, inplace=1, backup='.orig'):
line = re.sub(r"TIME_UTC", r"TIME_UTC_", line)
sys.stdout.write(line)
except IOError, err:
raise EasyBuildError("Failed to patch %s: %s", patchfile, err)
def post_install_step(self):
"""Custom post install step for IMPI, fix broken env scripts after moving installed files."""
super(EB_impi, self).post_install_step()
impiver = LooseVersion(self.version)
if impiver == LooseVersion('4.1.1.036') or impiver >= LooseVersion('5.0.1.035'):
if impiver >= LooseVersion('2018.0.128'):
script_paths = [os.path.join('intel64', 'bin')]
else:
script_paths = [os.path.join('intel64', 'bin'), os.path.join('mic', 'bin')]
# fix broken env scripts after the move
for script in [os.path.join(script_path,'mpivars.csh') for script_path in script_paths]:
for line in fileinput.input(os.path.join(self.installdir, script), inplace=1, backup='.orig.easybuild'):
line = re.sub(r"^setenv I_MPI_ROOT.*", "setenv I_MPI_ROOT %s" % self.installdir, line)
sys.stdout.write(line)
for script in [os.path.join(script_path,'mpivars.sh') for script_path in script_paths]:
for line in fileinput.input(os.path.join(self.installdir, script), inplace=1, backup='.orig.easybuild'):
line = re.sub(r"^I_MPI_ROOT=.*", "I_MPI_ROOT=%s; export I_MPI_ROOT" % self.installdir, line)
sys.stdout.write(line)
def patch_step(self):
"""Patch Boost source code before building."""
super(boostcray, self).patch_step()
# TIME_UTC is also defined in recent glibc versions, so we need to rename it for old Boost versions (<= 1.47)
glibc_version = get_glibc_version()
old_glibc = glibc_version is not UNKNOWN and LooseVersion(glibc_version) > LooseVersion("2.15")
if old_glibc and LooseVersion(self.version) <= LooseVersion("1.47.0"):
self.log.info("Patching because the glibc version is too new")
files_to_patch = ["boost/thread/xtime.hpp"] + glob.glob("libs/interprocess/test/*.hpp")
files_to_patch += glob.glob("libs/spirit/classic/test/*.cpp") + glob.glob("libs/spirit/classic/test/*.inl")
for patchfile in files_to_patch:
try:
for line in fileinput.input("%s" % patchfile, inplace=1, backup='.orig'):
line = re.sub(r"TIME_UTC", r"TIME_UTC_", line)
sys.stdout.write(line)
except IOError, err:
raise EasyBuildError("Failed to patch %s: %s", patchfile, err)
def patch_step(self):
"""Patch Boost source code before building."""
super(EB_Boost, self).patch_step()
# TIME_UTC is also defined in recent glibc versions, so we need to rename it for old Boost versions (<= 1.47)
glibc_version = get_glibc_version()
old_glibc = glibc_version is not UNKNOWN and LooseVersion(glibc_version) > LooseVersion("2.15")
if old_glibc and LooseVersion(self.version) <= LooseVersion("1.47.0"):
self.log.info("Patching because the glibc version is too new")
files_to_patch = ["boost/thread/xtime.hpp"] + glob.glob("libs/interprocess/test/*.hpp")
files_to_patch += glob.glob("libs/spirit/classic/test/*.cpp") + glob.glob("libs/spirit/classic/test/*.inl")
for patchfile in files_to_patch:
try:
for line in fileinput.input("%s" % patchfile, inplace=1, backup='.orig'):
line = re.sub(r"TIME_UTC", r"TIME_UTC_", line)
sys.stdout.write(line)
except IOError, err:
raise EasyBuildError("Failed to patch %s: %s", patchfile, err)
def _set_x0(self, x0):
if (isinstance(x0, str) and x0 == str(x0)):
x0 = eval(x0)
self.x0 = array(x0) # should not have column or row, is just 1-D
if self.x0.ndim == 2:
if self.opts.eval('verbose') >= 0:
_print_warning('input x0 should be a list or 1-D array, trying to flatten ' +
str(self.x0.shape) + '-array')
if self.x0.shape[0] == 1:
self.x0 = self.x0[0]
elif self.x0.shape[1] == 1:
self.x0 = array([x[0] for x in self.x0])
if self.x0.ndim != 1:
raise _Error('x0 must be 1-D array')
if len(self.x0) <= 1:
raise _Error('optimization in 1-D is not supported (code was never tested)')
self.x0.resize(self.x0.shape[0]) # 1-D array, not really necessary?!
# ____________________________________________________________
# ____________________________________________________________
def __call__(self, x, inverse=False): # function when calling an object
"""Rotates the input array `x` with a fixed rotation matrix
(``self.dicMatrices['str(len(x))']``)
"""
x = np.array(x, copy=False)
N = x.shape[0] # can be an array or matrix, TODO: accept also a list of arrays?
if str(N) not in self.dicMatrices: # create new N-basis for once and all
rstate = np.random.get_state()
np.random.seed(self.seed) if self.seed else np.random.seed()
B = np.random.randn(N, N)
for i in xrange(N):
for j in xrange(0, i):
B[i] -= np.dot(B[i], B[j]) * B[j]
B[i] /= sum(B[i]**2)**0.5
self.dicMatrices[str(N)] = B
np.random.set_state(rstate)
if inverse:
return np.dot(self.dicMatrices[str(N)].T, x) # compute rotation
else:
return np.dot(self.dicMatrices[str(N)], x) # compute rotation
# Use rotate(x) to rotate x
def print_help():
print "Usage:\n"
print "\tpython SameFileFinder.python [arg0] [arg1]\n"
print "Args:\n"
print "\t[arg0] - Target Directory of files should be scan"
print "\t[arg1] - Doc Suffix of files should be scan, eg"
print "\t\t .m - Object-C file"
print "\t\t .swift - Swift file"
print "\t\t .java - Java file\n"
print "\t--max-distance=[input] - max hamming distance to keep, default is 20"
print "\t--min-linecount=[input] - for function scan, the function would be ignore if the total line count of the function less than min-linecount"
print "\t--functions - Use Functions as code scan standard"
print "\t Attention: The \"--functions\" support just Object-C and Java now"
print "\t--detail - Show the detail of process\n"
print "\t--output=[intput] - Customize the output file, default is \"out.txt\""
################ End Util Funcs ################
backport3to2.py 文件源码
项目:Django-Web-Development-with-Python
作者: PacktPublishing
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def show_warning():
print("""************** WARNING *********************8
backport3to2.py performs an in-place modification of the SuperBook
project so that it works in Python 2.7. Hence, it will NOT WORK
correctly for Python 3.4 anymore. Please note that this is one-way
conversion and cannot be reversed.
Please confirm by pressing 'y' or 'Y' if you are sure that you would
like to continue with this conversion to Python 2.7. Press any other
key to abort: """, end="")
real_raw_input = vars(__builtins__).get('raw_input', input)
choice = real_raw_input().lower()
if choice != 'y':
sys.exit(-1)
if 'raw_input' not in vars(__builtins__):
print("""\nLooks like your are already on Python 3. This script
is for Python 2 users. Are you sure you want to continue?
(Y/N): """, end="")
choice = real_raw_input().lower()
if choice != 'y':
sys.exit(-1)
return
def main(argv):
state = 0
for line in fileinput.input():
line = line.strip()
if not line or line.startswith('#'):
if state == 1:
state = 2
print ('}\n')
print (line)
continue
if state == 0:
print ('\nglyphname2unicode = {')
state = 1
(name,x) = line.split(';')
codes = x.split(' ')
print (' %r: u\'%s\',' % (name, ''.join( '\\u%s' % code for code in codes )))
def main(argv):
import getopt, fileinput
def usage():
print ('usage: %s [-c codec] file ...' % argv[0])
return 100
try:
(opts, args) = getopt.getopt(argv[1:], 'c')
except getopt.GetoptError:
return usage()
if not args: return usage()
codec = 'utf-8'
for (k, v) in opts:
if k == '-c': codec = v
for line in fileinput.input(args):
line = latin2ascii(unicode(line, codec, 'ignore'))
sys.stdout.write(line.encode('ascii', 'replace'))
return
def run(self, stdin):
'''
Run the hooks as specified in the given configuration file.
Report messages and status.
'''
hooks = self.hooks
permit = True
# Read in each ref that the user is trying to update
for line in fileinput.input(stdin):
old_sha, new_sha, branch = line.strip().split(' ')
for hook in hooks:
status, messages = hook.check(branch, old_sha, new_sha)
for message in messages:
print "[%s @ %s]: %s" % (branch, message['at'][:7], message['text'])
permit = permit and status
if not permit:
sys.exit(1)
sys.exit(0)
def parse_spec(file):
classes = {}
cur = None
for line in fileinput.input(file):
if line.strip().startswith('#'):
continue
mo = rx_init.search(line)
if mo is None:
if cur is None:
# a normal entry
try:
name, args = line.split(':')
except ValueError:
continue
classes[name] = NodeInfo(name, args)
cur = None
else:
# some code for the __init__ method
cur.init.append(line)
else:
# some extra code for a Node's __init__ method
name = mo.group(1)
cur = classes[name]
return sorted(list(classes.values()), key=lambda n: n.name)
def parse_spec(file):
classes = {}
cur = None
for line in fileinput.input(file):
if line.strip().startswith('#'):
continue
mo = rx_init.search(line)
if mo is None:
if cur is None:
# a normal entry
try:
name, args = line.split(':')
except ValueError:
continue
classes[name] = NodeInfo(name, args)
cur = None
else:
# some code for the __init__ method
cur.init.append(line)
else:
# some extra code for a Node's __init__ method
name = mo.group(1)
cur = classes[name]
return sorted(classes.values(), key=lambda n: n.name)
def train(solver_prototxt_filename, init, init_type):
for line in fileinput.input('train_net.sh', inplace=True):
if '-solver' in line:
tmp = line.split('-solver')
if init==None:
print tmp[0]+" -solver "+ solver_prototxt_filename
elif init_type == 'fin':
print tmp[0]+" -solver "+ solver_prototxt_filename +" -weights " + init # .caffemodel file requiered for finetuning
elif init_type == 'res':
print tmp[0]+" -solver "+ solver_prototxt_filename +" -snapshot " + init # .solverstate file requiered for resuming training
else:
raise ValueError("No specific init_type defined for pre-trained network "+init)
else:
print line,
os.system("chmod +x train_net.sh")
os.system('./train_net.sh')
def connection_db(self,db_name):
'''
?????
:param db_name: ??????
:return: ???????
'''
##????
conf = {}
for line in fileinput.input(self.MYSQL_CONF):
lines = line.replace(' ', '').replace('\n', '').replace('\r', '').split("=")
conf[lines[0]] = lines[1]
try:
conn = MySQLdb.connect(host=conf["IP"], port=int(conf["PORT"]), user=conf["USER_NAME"], passwd=conf["PWD"],
db=db_name, charset='utf8')
return conn
except Exception,e:
print "???????!Error:",e
##?????
def replaceInFile(_fil, patternToFind='', strToReplace=None, byOccurStr=''):
"""
In file '_fil', on lines matching 'patternToFind' : string 'strToReplace' will be replaced by 'byOccurStr'
:param str patternToFind: lines matching the patternToFind will be selected for change. regex compliant
if empty string, all lines will be selected
:param str strToReplace: the string to be modified on the line selected . regex compliant.
strToReplace=None means strToReplace = patternToFind
:param str byOccurStr: string 'strToReplace' will be replaced by string 'byOccur'
"""
if strToReplace is None:
strToReplace = patternToFind
# fileinput allows to replace "in-place" directly into the file
for lin in fileinput.input(_fil, inplace=1):
if re.search(patternToFind, lin):
lin = re.sub(strToReplace, byOccurStr, lin.rstrip())
print(lin)