next string of a stream in VB.net - python

I have a some bunch of python files. I need to get all the classes from there and make a list.
its like I have to read with streamreader and then
Imports ActionBlock
I have to take the string ActionBlock and show it in a list. Listing and others hopefully I can do, but I am stuck in this point. Any suggestion please? Thank you.

You could use a regular expression to look for the parts you're interested in.
The following code
Dim path = "c:\path\to\your\file.py"
Dim content = File.ReadAllText(path)
Dim matchClass = "class (?<m>\w+)(:|\()+"
Dim matchImport = "(^|from \w+ )import ((?<m>\w+), )*(?<m>\w+)"
Dim result = Regex.Matches(content, String.Format("({0}|{1})", matchClass, matchImport), RegexOptions.Multiline) _
.Cast(Of Match) _
.SelectMany(Function(m) m.Groups("m").Captures.Cast(Of Capture).Select(Function(c) c.Value)) _
.ToList()
will, given a text file like
import os
import math
from time import clock
from random import randint
import DataArchiving
import TABasicFunctions
import HWDataConveterGate
import GeneralTestDataMapping
from something import FirstClass, SecondClass
def foo():
pass
def bar():
pass
class ClassOne(object):
class NestedClass:
pass
def thisisnotaclass(self):
v = [x.class for x in self]
v = [x.someimport for x in self]
class ClassTwo:
pass
class Class3:
pass
def main():
pass
if __name__ == '__main__':
main()
create a list that looks like:

Related

how do I assign data to class which inherits from "sqliteDict" class in python?

In the code below as you can see I have a test class that inherits from the sqliteDict class. There is also a get_term() method that returns the keys for the dictionary. In the main part, first I make an instance of the class and try to make a new sqliteDict file and assign simple data to it through a context manager block. Until now everything works great but when I try to read the data through the second context manager block from the same file, it seems the data is not saved in the file.
from collections import defaultdict
from sqlitedict import SqliteDict
class test(SqliteDict):
def __init__(self, filename: str = "inverted_index.sqlite", new = False):
super().__init__(filename, flag="n" if new else "c")
self._index = defaultdict(list) if new else self
def get_terms(self):
"""Returns all unique terms in the index."""
return self._index.keys()
if __name__ == "__main__":
with test("test.sqlite",new=True) as d:
d._index["test"]= ["ok"]
print("first attempt: ", [t for t in d.get_terms()])
d.commit()
with test("test.sqlite", new=False) as f:
print("second attempt: ",[t for t in f.get_terms()])
and the result is:
first attempt: ['test']
second attempt: []

How to mock imwrite in a loop

I am trying to use Python unittest library to test the following code.
from cv2 import imwrite
import h5py
import lumpy as np
class Myclass:
def __init__(self):
self.data = []
def get_data(self):
return self.data
def load_data(self, path):
count = 10
for i in range(count):
mat_file = path + f'{i}.mat'
with h5py.File(mat_file, 'r') as fin:
data = np.array(fin['data'])
for j in range(len(data)):
filename = path + f'{i}_{j}.jpg'
imwrite(filename, data)
self.data = data
I tried to do the following. But I am getting AttributeError saying Myclass has no attribute 'imwrite'. And I do not know how to mock the nested loops with image writing imwrite.
from mock import MagicMock, patch
def test():
m = MagicMock()
m.__enter__.return_value = data
with patch("h5py.File", return_value=m):
with patch(Myclass.imwrite) as mock_imwrite:
testclass = Myclass()
testclass.load_data(path='test')
assert testclass.get_data() == data
I hope someone can help me out. Any help is very much appreciated
The issue here is that your class Myclass does not have a function imwrite. Only the module (aka the file the class is defined in) is aware of this function.
If you want to patch the imwrite function of the package cv2, you have to write:
(untested code)
with patch('cv2.imwrite') as mock_imwrite:
testclass = Myclass()
...
But the as mock_imwrite part is only needed, if you run an assert on the mock. Otherwise, you may just skip it.

How to get Function to Access Varibles in Another Function

I have multiple functions. One function (estimation) calls on the variables of the other(callback) in order to perform a calculation. However, there are a couple of issues.
It seems like the variables aren't getting passed, and ...
It seems like the function(estimation) never gets called to run, and I don't know why.
What I want is to have the estimate result print out, but nothing is being printed.
If someone could let me know what I'm doing wrong I'd appreciate it.
EX:
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
import math
from geometry_msgs.msg import Quaternion
from sensor_msgs.msg import Imu
import numpy as np
from rclpy.qos import qos_profile_sensor_data
class S_E(Node):
def __init__(self):
super().__init__('s_e')
self.sub = self.create_subscription(Imu, '/imu', self.callback, qos_profile=qos_profile_sensor_data)
def callback(self, msg):
quat = self.quat = msg.orientation # x,y,z
a_rate = self.a_rate = msg.angular_velocity # x,y,z
return quat, a_rate
def estimation(self):
print("Hello")
quat, a_rate = callback()
estimate = (0.5 * a_rate) * quat
print(estimate)
def main(args=None):
rclpy.init(args=args) # initialize ROS2 Library
s_e = S_E() # make an object of class
try:
while (1):
rclpy.spin(s_e)
except Exception as e:
print("Exception: {}".format(e))
rclpy.spin(s_e)
rclpy.shutdown()
if __name__ == '__main__':
main()
You are not calling the estimation function on your object. You would do that by doing something like this
s_e = S_E()
s_e.estimation()

python absolute import of the function

trend.py and test_trend.py are in the same folder. I have a class Trend with a function find_regres_values that is called from a instance method perform_analysis.
trend.py:
class Trend:
def __init__(self, values, trend_type):
self.all_values = values
def permorn_analysis(self, first, trend_type):
#blabla
vals_reg = ["a", "b", "c", "d"]
find_regres_values(vals_reg, first, trend_type)
def find_regres_values(vals_reg, first, trend_type):
#do somethin
pass
in test_trend.py
from trend import find_regres_values
class ConsecRegions(unittest.TestCase):
def test_find_regres_values_decreas_min_before_max(self):
#initialize some values
output = find_regres_values(vals_reg, first, trend_type)
self.assertEqual(output, result)
It shows me an error:
File "test_trend.py", line 2, in <module>
from trend import find_regres_values
ImportError: cannot import name find_regres_values
How do I import one function for testing?
find_regres_values is a method of the class Trend, If you want find_regres_values to be its own function then remove the indentation
class Trend:
def __init__(self, values, trend_type):
self.all_values = values
def permorn_analysis(self,first,trend_type)
#blabla
vals_reg = some list
find_regres_values(vals_reg, first, trend_type)
def find_regres_values(vals_reg, first, trend_type):
#do something
What Python version you use?
If Python 3.x:
Create empty file __init__.py
For correct import use this code:
from trend import Trend
and edit call of method:
from trend import Trend
class ConsecRegions(unittest.TestCase):
def test_find_regres_values_decreas_min_before_max(self):
#initialize some values
output = Trend.find_regres_values(vals_reg, first, trend_type)
self.assertEqual(output, result)
For information:
In file trend.py after permorn_analysis method insert a colon.

Modifying wrapper python print to return type

All I get from this code is that, print in python is a wrapper function of write method of stdout so if I give it a return type it must return that as well, right? Then why can't I do that?
import sys
class CustomPrint():
def __init__(self):
self.old_stdout=sys.stdout
def write(self, text):
text = text.rstrip()
if len(text) == 0: return
self.old_stdout.write('custom Print--->' + text + '\n')
return text
sys.stdout=CustomPrint()
print "ab" //works
a=print "ab" //error! but why?
In python2.x, print is a statement. So, a = print "ab" is illegal syntax. Try just print "ab".
In python3, print is a function -- So you'd write: a = print("ab"). Note that starting at python2.6, you can get access to python3's print function via from __future__ import print_function.
Ultimately, what you want is something like:
#Need this to use `print` as a function name.
from __future__ import print_function
import sys
class CustomPrint(object):
def __init__(self):
self._stdout = sys.stdout
def write(self,text):
text = text.rstrip()
if text:
self._stdout.write('custom Print--->{0}\n'.format(text))
return text
__call__ = write
print = CustomPrint()
a = print("ab")

Categories

Resources