crystal-lang : how to fill an array with all modules defined in files in a specific package of the project? - metaprogramming

All in the question,
I would like to know if it's possible to do something like this in Crystal (pseudo-code) :
modules = Array(Module).new
foreach (file in specific_package) do
if (file.is_a(crystal_module) do
modules.push(file.module)
end
end

Crystal doesn't have packages but modules. If you want to get all modules in a file you can try this:
require "compiler/crystal/syntax"
Modules = [] of String
class ModuleVisitor < Crystal::Visitor
def visit(node : Crystal::ModuleDef)
Modules << node.name.names.join("::")
true
end
def visit(node : Crystal::ASTNode)
true
end
end
Dir.glob("./*.cr").each do |file|
visitor = ModuleVisitor.new
parser = Crystal::Parser.new(File.read(file))
parser.filename = file
node = parser.parse
node.accept(visitor)
end
puts Modules.join("\n")
Then you'd get an Array(String) with all modules names
Try it online!
If you want to get all included modules in a class try this:
class Class
def included_modules
{% if #type.ancestors.any? { |a| a.class.stringify.ends_with?(":Module") } %}
{{ #type.ancestors.select { |a| a.class.stringify.ends_with?(":Module") } }}
{% else %}
[] of Nil
{% end %}
end
end
module Foo::Bar
end
class Baz
include Foo::Bar
end
puts Baz.included_modules # => [Foo::Bar]
Try it online!

Related

find if all elements of a list exists in a file and create new list

Team,
issue is that it is still appending those lines to needed_list that match the pattern defined in skip_list. Not sure if there is space or why it is not skipping them, ex: // or }
I have two files and I need to see if a string from each line in fileA is referred in file2.
For this, I am looping over all strings just before : in fileA and check against all lines in file2 and printing them and skipping those lines from being printed that are not used in file2.
But I am observing that some strings from skip_list are still being printed.
Please ignore what sort of files these are because these are manually created sample files to test code.
file1
package deploy
application: sonarqube: helm: values: {
sonarqube: {
namespace: "sonarqube"
deploymentType: "StatefulSet"
role: "server"
// There should not be more than 1 sonarqube instance connected to the same database. Please set this value to 1 or 0 (in case you need to scale down programmatically).
file2
metadata:
name: {{ .scanjob }}
namespace: {{ .Values.namespace }}
command: ls
deploy: deploymentType
type: role: server
code
class SearchIn():
skip_list = ['{','}','/','[]','[',']','//','#']
needed_list = []
def charts_files(self, args):
chart_name = args
self.local_path = Path(environ.get("HOME"))/chart_name/"templates"
self.files_list=listdir(local_path)
return self.files_list
def values(self, args):
self.charts_files(chart_name)
values = "values.cue"
with open(self.local_path/values, 'r') as v:
for aline in v:
trimmed_line=aline.strip().split(":",1)[0]
print(trimmed_line)
for aptrn in self.skip_list:
if aptrn in trimmed_line or aptrn is trimmed_line:
continue
else:
print("no pattern found")
print(trimmed_line)
if trimmed_line not in self.needed_list:
self.needed_list.append(trimmed_line)
print(self.needed_list)
co = SearchIn()
chart_name = input(r'Enter chart name:')
co.values(chart_name)
Output: some snip
}
no pattern found
}
['package deploy', 'application', 'sonarqube', 'namespace', 'deploymentType', 'role', '// There should not.....
..
..
expected output
needed_list should not contain any element from skip_list
}
['package deploy', 'application', 'sonarqube', 'namespace', 'deploymentType','role'....]

#babel.localselector not called

I have a problem using Flask Babel and python3.6.
My code is as following:
#babel.localeselector
def get_locale():
lang_supported = app.config.get('LANGUAGES', [])
lang = request.accept_languages.best_match(lang_supported.keys())
print('de', lang_supported)
return lang
I do not get anything printed at the console. I do not know what I did wrong.
My App is initiated as following in the same file:
app = Flask(__name__)
app.config.from_object("config")
babel = Babel(app)
In my config file everything relevant to Babel is following:
LANGUAGES = {
'en': 'English',
'de': 'Deutsch'
}
# BABEL_TRANSLATION_DIRECTORIES = '/path/to/flask/translations'
# BABEL_DEFAULT_LOCALE = 'de'
# BABEL_DEFAULT_TIMEZONE = 'Europe/Berlin'
While looking for some solutions, I also tried the commented lines.
I was able to use pybabel and create my .pot, .po, .mo, files. And I created my Translation for 'de'
I do not find anything about, why my print statement is not executed.
When I manually create a context_processor and call my get_locale(), the print statement appears as expected.
Please let me know, if you need something more for debugging.
Update: code example calling the gettext
Inside of a view I called it for example like this:
from flask_babel import gettext as _
print(_('Hello'))
or
from flask_babel import gettext
print(gettext('Hello'))
and in Jinja2:
{{ _( 'Hello' ) }}

How to print out the values of variables in a valuebox in soot?

This is the related code fragment where I can't print out the values from valuebox. May I know what's the problem?
public GuaranteedDefsAnalysis(UnitGraph graph)
{
super(graph);
DominatorsFinder df = new MHGDominatorsFinder(graph);
unitToGenerateSet = new HashMap<Unit, FlowSet>(graph.size() * 2 + 1, 0.7f);
// pre-compute generate sets
for(Iterator unitIt = graph.iterator(); unitIt.hasNext();){
Unit s = (Unit) unitIt.next();
FlowSet genSet = emptySet.clone();
for(Iterator domsIt = df.getDominators(s).iterator(); domsIt.hasNext();){
Unit dom = (Unit) domsIt.next();
for(Iterator boxIt = dom.getDefBoxes().iterator(); boxIt.hasNext();){
ValueBox box = (ValueBox) boxIt.next();
box.getValue().toString(); // simply using toString does not work
if(box.getValue() instanceof Local)
genSet.add(box.getValue(), genSet);
}
}
unitToGenerateSet.put(s, genSet);
}
doAnalysis();
}
Can you maybe rephrase your question? What do you mean by "does not work"? Did you forget to add the println statement maybe?

groovy read a file, resolve variables in file content

I am new to Groovy and I could not get around this issue. I appreciate any help.
I want to read a file from Groovy. While I am reading the content, for each line I want to substitute the string '${random_id}' and '${entryAuthor}' with different string values.
protected def doPost(String url, URL bodyFile, Map headers = new HashMap() ) {
StringBuffer sb = new StringBuffer()
def randomId = getRandomId()
bodyFile.eachLine { line ->
sb.append( line.replace("\u0024\u007Brandom_id\u007D", randomId)
.replace("\u0024\u007BentryAuthor\u007D", entryAuthor) )
sb.append("\n")
}
return doPost(url, sb.toString())
}
But I got the following error:
groovy.lang.MissingPropertyException:
No such property: random_id for class: tests.SimplePostTest
Possible solutions: randomId
at foo.test.framework.FooTest.doPost_closure1(FooTest.groovy:85)
at groovy.lang.Closure.call(Closure.java:411)
at groovy.lang.Closure.call(Closure.java:427)
at foo.test.framework.FooTest.doPost(FooTest.groovy:83)
at foo.test.framework.FooTest.doPost(FooTest.groovy:80)
at tests.SimplePostTest.Post & check Entry ID(SimplePostTest.groovy:42)
Why would it complain about a property, when I am not doing anything? I also tried "\$\{random_id\}", which works in Java String.replace(), but not in Groovy.
You are doing it the hard way. Just evaluate your file's contents with Groovy's SimpleTemplateEngine.
import groovy.text.SimpleTemplateEngine
def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}'
def binding = ["firstname":"Sam", "lastname":"Pullara", "city":"San Francisco", "month":"December", "signed":"Groovy-Dev"]
def engine = new SimpleTemplateEngine()
template = engine.createTemplate(text).make(binding)
def result = 'Dear "Sam Pullara",\nSo nice to meet you in San Francisco.\nSee you in December,\nGroovy-Dev'
assert result == template.toString()
you better use groovy.text.SimpleTemplateEngine class; check this for more details http://groovy.codehaus.org/Groovy+Templates
The issue here is that Groovy Strings will evaluate "${x}" by substituting the value of 'x', and we don't want that behaviour in this case. The trick is to use single-quotes which denote plain old Java Strings.
Using a data file like this:
${random_id} 1 ${entryAuthor}
${random_id} 2 ${entryAuthor}
${random_id} 3 ${entryAuthor}
Consider this code, which is analogous to the original:
// spoof HTTP POST body
def bodyFile = new File("body.txt").getText()
StringBuffer sb = new StringBuffer()
def randomId = "257" // TODO: use getRandomId()
def entryAuthor = "Bruce Eckel"
// use ' here because we don't want Groovy Strings, which would try to
// evaluate e.g. ${random_id}
String randomIdToken = '${random_id}'
String entryAuthorToken = '${entryAuthor}'
bodyFile.eachLine { def line ->
sb.append( line.replace(randomIdToken, randomId)
.replace(entryAuthorToken, entryAuthor) )
sb.append("\n")
}
println sb.toString()
The output is:
257 1 Bruce Eckel
257 2 Bruce Eckel
257 3 Bruce Eckel

Can't create instance variable using before_suite method in miniTest

I want create a #conn before all test case and can be used for all test case so i did something like:
class SQLTest < Test::Unit::TestCase
def self.before_suite
#conn = PG.connect(dbname:'MapSwitcher',host:'localhost', user:'Lin')
end
def test_employee_table_have_5_entries
result = #conn.exec("SELECT COUNT(*) FROM employees")
assert_equal(result.getvalue(0,0).to_i, 5)
end
end
And I got an error:
noMethodError: private method `exec' called for nil:NilClass
it seems like the #conn can't be accessed in the test case,
class SQLTest < MiniTest::Unit::TestCase
def setup
#conn = PG.connect(dbname:'MapSwitcher',host:'localhost', user:'Lin')
end
def test_employee_table_have_5_entries
result = #conn.exec("SELECT COUNT(*) FROM employees")
assert_equal(result.getvalue(0,0).to_i, 5)
end
end

Resources