Scala method chaining - hello world - python

I'm currently learning method chaining. I've provided a working python example.
#!/bin/python3
import sys
class Generator(object):
def __init__(self):
return None
def echo(self, myStr):
sys.stdout.write(myStr)
return self
g = Generator()
g.echo("Hello, ").echo("World!\n")
But the Scala version doesn't seem to work, no text is being output.
#!/usr/bin/env scala
final class Printer() {
def echo(msg: String): this.type = {
println(msg)
this
}
}
class Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Does anybody know why the scala version is not working and why?

You need to compile and call your scala bytecode aferwards. Also, you don't need to specify this.type if your Printer is final, e.g. if your driver.scala file contains:
final class Printer() {
def echo(msg: String) = {
println(msg)
this
}
}
object Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Then just call:
scalac driver.scala
scala Driver

You should call the main method in your script.
new Driver().main(...) should solve your problem.
Besides, it is the norm to define a main method in an object.
So, instead of
class Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
new Driver().main(...)
I would recommend the following.
object Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Driver.main(...)
Good luck!

Related

Implementing pymemcache from python to rust

I am migrating a project from python to rust, more specifically right now a file which uses the pymemchace library to call the set and get methods.
In order to set and get the cache a class was created, something like this:
class Example:
def __init__(self):
# Create connection with to memcached server
def set_cache(self, ... ):
# Set cache
def get_cache(self, ... ):
# Get cache
Instance = Example()
I know the OOP concepts like classes are implemented a differently on Rust compared to python.
How do you guys think I should approach this ? Build a struct and implement a method using the memcache crate or build a trait and call it as I needed ?
Edit[7/11/2022]:
After reading the comments this is the first model I have for the implementation of the memecache main methods:
rust
extern crate memcache;
use memcache::{Client, MemcacheError};
pub struct CacheManager {
client: memcache::Client,
}
impl CacheManager {
pub fn __ini__() -> Self {
CacheManager {
client: memcache::Client::connect("memcache://localhost:11211").unwrap(),
}
}
pub fn set_cache(&self, key: &str, val: &str, expire: u32) -> bool {
self.client.set(key, val, expire).unwrap();
self.client.replace(" ", "", 100000000).unwrap();
true
}
pub fn get_cache(&self, key: &str) -> Result<Option<String>, MemcacheError> {
self.client.replace(" ", "", 100000000).unwrap();
self.client.get(key)
}
pub fn get_or_set(self, key: &str, val: &str) -> bool {
//If status cache already exist and value is the same then do nothing else set it
let cache_val = self.get_cache(key);
match cache_val.unwrap() {
Some(i) => {
if (i.parse::<i32>().unwrap() - val.parse::<i32>().unwrap()) < 1 {
true
} else {
false
}
}
None => {
self.set_cache(key, val, 86400);
false
}
}
}
}
What do you guys think ?
I will build some testing mod to try it out now.

How can I access a Rust Iterator from Python using PyO3?

I'm quite new with Rust, and my first 'serious' project has involved writing a Python wrapper for a small Rust library using PyO3. This has mostly been quite painless, but I'm struggling to work out how to expose lazy iterators over Rust Vecs to Python code.
So far, I have been collecting the values produced by the iterator and returning a list, which obviously isn't the best solution. Here's some code which illustrates my problem:
use pyo3::prelude::*;
// The Rust Iterator, from the library I'm wrapping.
pub struct RustIterator<'a> {
position: usize,
view: &'a Vec<isize>
}
impl<'a> Iterator for RustIterator<'a> {
type Item = &'a isize;
fn next(&mut self) -> Option<Self::Item> {
let result = self.view.get(self.position);
if let Some(_) = result { self.position += 1 };
result
}
}
// The Rust struct, from the library I'm wrapping.
struct RustStruct {
v: Vec<isize>
}
impl RustStruct {
fn iter(&self) -> RustIterator {
RustIterator{ position: 0, view: &self.v }
}
}
// The Python wrapper class, which exposes the
// functions of RustStruct in a Python-friendly way.
#[pyclass]
struct PyClass {
rust_struct: RustStruct,
}
#[pymethods]
impl PyClass {
#[new]
fn new(v: Vec<isize>) -> Self {
let rust_struct = RustStruct { v };
Self{ rust_struct }
}
// This is what I'm doing so far, which works
// but doesn't iterate lazily.
fn iter(&self) -> Vec<isize> {
let mut output_v = Vec::new();
for item in self.rust_struct.iter() {
output_v.push(*item);
}
output_v
}
}
I've tried to wrap the RustIterator class with a Python wrapper, but I can't use PyO3's #[pyclass] proc. macro with lifetime parameters. I looked into pyo3::types::PyIterator but this looks like a way to access a Python iterator from Rust rather than the other way around.
How can I access a lazy iterator over RustStruct.v in Python? It's safe to assume that the type contained in the Vec always derives Copy and Clone, and answers which require some code on the Python end are okay (but less ideal).
You can make your RustIterator a pyclass and then implement the proper trait (PyIterProtocol) using the rust iter itself.
Not tested, but something like:
#[pyclass]
pub struct RustIterator<'a> {
position: usize,
view: &'a Vec<isize>
}
impl<'a> Iterator for RustIterator<'a> {
type Item = &'a isize;
fn next(&mut self) -> Option<Self::Item> {
let result = self.view.get(self.position);
if let Some(_) = result { self.position += 1 };
result
}
}
#[pyproto]
impl PyIterProtocol for Iter {
fn __next__(mut slf: PyRefMut<Self>) -> IterNextOutput<usize, &'static str> {
match self.next() {
Some(value) => IterNextOutput::Yield(value),
None => IterNextOutput::Return("Ended")
}
}
}

Frida - hook native method failure on android-Q

I have a sample app, which have a int add(int a,int b) in native library.
I use below code to hook the add method:
#!/usr/bin/env python3
import frida
import sys
package_name = "com.sample.hello"
apiname = "add"
def get_messages_from_js(message, data):
if message['type'] == 'send':
print(message['payload'])
else:
print(message)
def instrument_debugger_checks():
hook_code = """
Interceptor.attach(Module.findExportByName(null, "%s"), {
onEnter: function(args) {
console.log("onEnter...");
//send (Memory.readUtf8String (args [1]));
},
onLeave: function(args) {
console.log("onLeave...");
}
});
"""%(apiname)
return hook_code
process = frida.get_usb_device().attach(package_name)
script = process.create_script(instrument_debugger_checks())
script.on('message',get_messages_from_js)
script.load()
sys.stdin.read()
I use below command to get the function name from so:
$ nm -D libnative2.so |grep add
0000000000082504 T _ZNSt6__ndk114__shared_count12__add_sharedEv
0000000000082574 T _ZNSt6__ndk119__shared_weak_count10__add_weakEv
000000000008255c T _ZNSt6__ndk119__shared_weak_count12__add_sharedEv
0000000000042d8c T add
I have tried all these names, result is the same.
But when I run it, I got below error:
{'type': 'error', 'description': 'Error: expected a pointer', 'stack': 'Error: expected a pointer\n at frida/runtime/core.js:387\n at /script1.js:9', 'fileName': 'frida/runtime/core.js', 'lineNumber': 387, 'columnNumber': 1}
What's wrong with my code?
Looks like You have an issue with timing.
Try the following Frida script:
Java.perform(function() {
const System = Java.use("java.lang.System");
const Runtime = Java.use("java.lang.Runtime");
const SystemLoad_2 = System.loadLibrary.overload("java.lang.String");
const VMStack = Java.use("dalvik.system.VMStack");
SystemLoad_2.implementation = function(library) {
console.log("Loading dynamic library => " + library);
try {
const loaded = Runtime.getRuntime().loadLibrary0(VMStack.getCallingClassLoader(), library);
if(library.includes("native2")) {
// here your hook
Interceptor.attach(Module.findExportByName("libnative2.so", "%s"), {
onEnter: function(args) {
console.log("onEnter...");
//send (Memory.readUtf8String (args [1]));
},
onLeave: function(args) {
console.log("onLeave...");
}
});
}
return loaded;
} catch(ex) {
console.log(ex);
}
};
});

Multiple Conditions and Object Creation using Design Pattern

I am studying design pattern which I can implement to achieve the same purpose as below. However, I am stuck since most of the examples in the net are pretty simple.
I have tried to look at factory method or even strategy method but can't figure out if any of them could be used.
Any suggestion from the guru here?
def checkSomething():
if ...:
return True
else:
return False
def main(mode, state):
if checkSomething() == False:
if mode == False or (mode == True and state == False):
obj_a = Class_A()
return obj_a
else:
Class_B().run()
obj_c = Class_C()
return obj_c
You can return a pair or tuple where first part may be some enum indicating type.
You can create a base class and derive your return class type from common base class. Here, you need to design your program to depend on base class rather than on derived type.
all my personally thoughts
factory pattern opted out here: you are not only creating objects but also making them do stuff
state machine opted out here: there is no state transition here
So I am using the strategy pattern below. But I think you can still use the factory pattern on top so that you further separate the concern of the creation of objects out from the strategy classes.
sort of C# pseudo code here:
interface IClass
{
void Run();
}
class Class_A : IClass { ... }
class Class_B : IClass { ... }
class Class_C : IClass { ... }
interface IStrategy
{
IClass Execute();
}
class StrategyA : IStrategy
{
IClass IStrategy.Execute()
{
var obj_a = Class_A();
return obj_a;
}
}
class StrategyB : IStrategy
{
IClass IStrategy.Execute()
{
Class_B.Run();
var obj_c = Class_C();
return obj_c;
}
}
class DecisionMaker
{
private IStrategy _strategy;
public DecideStrategy(IStrategy strategy) => _strategy = strategy;
public IClass ExecuteStrategy() => _strategy.Execute();
}
main()
{
var decisionMaker = new decisionMaker();
if conditionA
decisionMaker.DecideStrategy(new StrategyA());
else if conditionB
decisionMaker.DecideStrategy(new StrategyB());
return decisionMaker.ExecuteStrategy();
}

Access reactjs data through multiple classes

I have a reactjs class called MyDictionary that renders data that a python file sends in. This class returns a dictionary structure. I want to access only a couple of elements from MyDictionary via a separate class, and a different set of elements also from MyDictionary, via a separate class. I tried React.createElement(SomeOtherClass, { as shown below, but this doesn't work... what am I missing?
class MyDictionary extends React.Component {
render() {
return this.props.results.map((result, index) =>
React.createElement(
"div",
{ className: "col-sm-12" },
React.createElement(SomeOtherClass, {
key: result.id,
name: result.name,
index: result.index,
activity: this.props.index + 1,
images: this.props.image_labels
})
)
);
}
}
return MyDictionary;
Looks like your this operator inside the callback function is not what you expect.
The easiest way to resolve this is to create a var to this before your map call.
var _this = this;
Then use _this instead of this inside your callback.
You should also read up on javascript closures.
Edit: render() should return one root element.
class MyDictionary extends React.Component {
render() {
var _this = this;
var children = this.props.results.map((result, index) =>
React.createElement(
"div",
{ className: "col-sm-12" },
React.createElement(SomeOtherClass, {
key: result.id,
name: result.name,
index: result.index,
activity: _this.props.index + 1, // using _this
images: _this.props.image_labels // using _this
})
)
);
return React.createElement("div", null, children);
}
}
return MyDictionary;

Categories

Resources