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;
Related
Check the two part of code bellow. There is two method second one is python method which make a post request to a url but i want to do same api call with same payload with c# restsharp. I already tried to convert code like bellow but since i don't have idea about python i am not able to understand how can i add payload as its done in python code. I already tried to add this payload using request.AddBody but it is not same as it was done in python code. How can i add those payload info with restsharp request exactly as done in py? please advice
payload:
data={
"locationType": "LOCATION_INPUT",
"zipCode": zip_code,
"storeContext": "generic",
"deviceType": "web",
"pageType": "Gateway",
"actionSource": "glow",
"almBrandId": "undefined",
}
C#
public static IRestResponse MakeApiCall(string zip_code)
{
var client = new RestClient("https://www.example.com");
var request = new RestRequest(Method.POST);
//request.AddHeader();//i can add header like this thats not a problem
//request.AddCookie();//i can add cookie like this thats not a problem
request.AddBody("data=", #"{" +
"locationType\": \"LOCATION_INPUT",
"zipCode\": zip_code,
"storeContext\": \"generic",
"deviceType\": \"web",
"pageType\": \"Gateway",
"actionSource\": \"glow",
"almBrandId\": \"undefined");
var result = client.Execute(request);
return result;
}
Python:
def MakeApiCall(zip_code: str, headers: dict, cookies: dict):
response = requests.post(
url="https://www.example.com",
data={
"locationType": "LOCATION_INPUT",
"zipCode": zip_code,
"storeContext": "generic",
"deviceType": "web",
"pageType": "Gateway",
"actionSource": "glow",
"almBrandId": "undefined",
},
headers=headers,
cookies=cookies,
)
assert response.json()["isValidAddress"], "Invalid change response"
return response.cookies
If I understood your question correctly, you are trying to convert the method from python into a C# method. I am assuming that you are using .NET Core and the RestSharp library, if not you need to clarify what you are using in your original post.
In your class instantiate the RestClient class in a constructor
public class RandomClass
{
private readonly IRestClient _client;
public RandomClass(){
_client = new RestClient("baseUrl");
_client.UseSerializer(
() => new JsonSerializer { DateFormat = "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ" }
);
}
}
Now, define a class for your request data:
public class Location {
public string LocationType {get; set;}
public string ZipCode {get; set;}
public string StoreContext {get; set; }
public string DeviceType {get; set;}
public string ActionSource {get; set;}
public string BrandId {get; set;}
}
In your MakeApiCall method:
public IRestResponse MakeApiCall(Location data){
var request = _client.Request("/endpoint/relative/to/baseUrl", Method.POST);
var jsonToSend = JsonSerializer.Serialize(data);
request.AddParameter(
"application/json; charset=utf-8",
jsonToSend,
ParameterType.RequestBody
);
var response = _client.Execute(request);
if (response.ErrorException != null)
{
const string message = "Error retrieving response.";
throw new Exception(message, response.ErrorException);
}
// if we get to here then the request succeeded
return response.data;
}
I haven't tested it, but nonetheless it should point you in the right direction.
There are two ways to go about it.
Use a strongly typed data structure
Create a dynamic object and use that as your data object.
Create a class to store your data object
class MyDataType
{
[JsonProperty("locationType")]
public string LocationType { get; set; }
[JsonProperty("zipCode")]
public string ZipCode { get; set; }
//...
}
// and in your method, you would use the above datatype like this,
var data = new MyDataType
{
LocationType = "location",
ZipCode = "zipCode"
// ...
};
or 2. Create a dynamic / anonymous object and use that as json body.
var data = new
{
locationType = "location",
zipCode = "zipCode",
storeContext = "generic",
deviceType = "web",
pageType = "Gateway",
actionSource = "glow",
almBrandId = "undefined",
};
Once you have your object, I would recommend using AddJsonBody as AddBody is deprecated.
var client = new RestClient("https://www.example.com");
var request = new RestRequest(Method.POST);
request.AddHeader(#"Content-Type", #"application/json");
request.AddHeader(#"Accept", #"application/json");
request.AddJsonBody(data);
var result = client.Execute(request);
string actualData = result.Content;
result.Content would have your response. You can use Newtonsoft Json to convert data in your response to a class object and validate your data that way.
I'm new to JavaScript and AWS. And I invoked a separate Lambda function (Let's say child lambda) from a middle line of the main Lambda function (Let's say parent lambda) and use the returned value from the child lambda in the parent lambda.
My child lambda is implemented in Python 3.6 and parent lambda is implemented in Node.js 12.x.
I have an array assigned to variable 'img'. If a condition satisfies I need to invoke the child lambda by passing the Payload as 'img' array to do some extra calculations on that array and return it back to the parent lambda. And finally replace the 'img' variable with the returned array.
Below is the return code block I used in the child lambda.
return {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": json.dumps({
"returnArray": returnArr
})
}
returnArr is a 3d array.
I want to access "returnArray" and assign returnArr array to variable 'img'.
Below is the code block I use in the parent lambda to do that (Line 1).
const AWS = require('aws-sdk');
AWS.config.region = 'ap-southeast-2';
var lambda = new AWS.Lambda();
exports.handler = async (event, ctx, callback) => {
//////////code lines for other operations////////////
let img = //Line A - 3d array;
let body1;
if(condition){
var params = {
FunctionName: 'childFunction', // child lambda function written in Python 3.6
InvocationType: 'RequestResponse',
Payload: JSON.stringify({ "sendImg" : img})
};
lambda.invoke(params, function(err, data) {
if (err) {
console.log(err);
} else {
console.log('Returned '+ data.Payload); //Line B
let body1;
if(typeof(data.Payload) == 'object') {
body1 = data.Payload;
} else {
body1 = JSON.parse(data.Payload); //
}
img = body1.body["returnArray"]; //Line 1
console.log("arr : "img); Line 2
}
}).promise();
}
////////Rest of the code///////////////////////
};
But Line 2 gives this.
arr : undefined
I think this is happening since I don't have much NodeJS knowledge.
Could someone kindly tell me How to get the 3d array in Line 1?
Thanks.
You encoded the body element, so you need to parse it.
img = JSON.parse(body1.body).returnedArray;
I'm trying to bind a function that accepts multiple arguments and keyword arguments with PYBIND.
The function looks something like this:
{
OutputSP output;
InputSP input;
if (args.size() == 1)
{
input = py::cast<InputSP>(args[0]);
} else if (args.size() == 2)
{
query = py::cast<OutputSP>(args[0]);
expression = py::cast<InputSP>(args[1]);
}
// TODO: Default values - should be elsewhere?
Flags mode(Flags::FIRST_OPTION);
std::vector<MultiFlags> status({ MultiFlags::COMPLETE });
for (auto& kv : kwargs)
{
auto key_name = py::cast<string>(kv.first);
if (key_name == "flag")
{
mode = py::cast<Flags>(kv.second);
}
else if (key_name == "status")
{
status = py::cast<std::vector<MultiFlags> >(kv.second);
}
}
return method(output, input, mode, status);
}
Where Flags and MultiFlags are defined like this
py::enum_<Flags>(m, "Flags")
.value("FirstOption", Flags::FIRST_OPTION)
.value("SecondOption", Flags::SECOND_OPTION)
.export_values();
py::enum_<MultiFlags>(m, "MultiFlags")
.value("Complete", MultiFlags::COMPLETE)
.value("Incomplete", MultiFlags::INCOMPLETE)
.export_values();
and the wrapper with
m.def("method", &method_wrapper);
Now this should work fine if the call contains
status=[MultiFlags.Complete]
I'm looking for a way to check the type of the kwarg in advance so I could also accept a call that contains
status=MultiFlags.Complete
but can't find anything relevant in PYBIND11 docs. what is the correct way to do this?
Found it.
py::cast throws py::cast_error when casting fails, so I can treat the two options with try-catch:
else if (key_name == "status")
{
try
{
status = py::cast<std::vector<MultiFlags> >(kv.second);
} catch (py::cast_error&)
{
status = { py::cast<MultiFlags>(kv.second) };
}
}
I have multiple Hazelcast sets for which I want to find the Intersection, however I want to avoid pulling any data on the client side. My current approach is exactly that with this code. It finds intersection between the 1st set and the list of the rest of set so that set1 is now the intersection of all.
for i in range(1, len(sets)):
cur = sets[i]
set1.retain_all(cur.get_all())
Hazelcast's retain_all doesn't work with 2 set entities, only with a set and a collection which is not what I am looking for. For example, it can be done with Redis with this code, so I want its Hazelcast equivalent.
set_result = "set_result"
redisClient.sinterstore(set_result, *list(sets))
Any help would be appreciated!
Since Hazelcast's ISet is a Set which is a Collection the following code should work:
set1.retainAll(cur);
But, it doesn't seem like you'd like set1 to be modified but would rather store the result in a different set much like redis' sinterstore function.
The following is an example of an alternative implementation:
public class RetainAllExample {
public static void main(String[] args) {
HazelcastInstance h1 = Hazelcast.newHazelcastInstance();
HazelcastInstance h2 = Hazelcast.newHazelcastInstance();
Set<String> set1 = h1.getSet("set1");
Set<String> set2 = h1.getSet("set2");
set1.add("a");
set1.add("b");
set1.add("c");
set1.add("d");
set2.add("c");
set2.add("d");
set2.add("e");
String resultName = "result";
String[] setNames = new String[] { "set1", "set2"};
RetainAll retainAll = new RetainAll(resultName, setNames;
IExecutorService exec = h1.getExecutorService("HZ-Executor-1");
Future<Boolean> task = exec.submit(retainAll);
try {
if(task.get(1_000, TimeUnit.MILLISECONDS)) {
Set<String> result = h1.getSet(resultName);
result.forEach(str -> System.out.println(str + ", "));
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
System.exit(0);
}
static class RetainAll implements Callable<Boolean>, HazelcastInstanceAware, Serializable {
private HazelcastInstance hazelcastInstance;
private String resultSetName;
private String[] setNames;
public RetainAll(String resultSetName, String[] setNames) {
this.resultSetName = resultSetName;
this.setNames = setNames;
}
#Override
public Boolean call() {
try {
Set[] sets = new Set[setNames.length];
IntStream.range(0, setNames.length).forEach(i -> sets[i] = hazelcastInstance.getSet(setNames[i]));
ISet resultSet = hazelcastInstance.getSet(resultSetName);
resultSet.addAll(sets[0]);
IntStream.range(1, sets.length).forEach(i -> resultSet.retainAll(sets[i]));
}
catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
}
}
function CallMethod() {
$.getJSON('/website/RESTfulService.svc/LiveLocation/json?{x=1,y=2}', function(data) {
getResult(data.lat, data.lon);
});
}
Pass them as an object just after the URL and before the function:
function CallMethod() {
$.getJSON('/website/RESTfulService.svc/LiveLocation/json',
{
x: "1",
y: "2"
},
function(data) {
getResult(data.lat, data.lon);
});
}
Alternatively, first create javascript object for the sake of simplicity and then pass
var myObject = {x: "1", y: "2"};
$.getJSON('/website/RESTfulService.svc/LiveLocation/json', myObject, function(dataVal) {
//Use Your result
});
Just like Zheileman said, but note that this way, although you passed the parameters in JSON format, the actual parameters are passed to the webserver as an Encoded HTTP URL which will end up this way:
/website/RESTfulService.svc/LiveLocation/json?x=1&y=2