By Dimitri Kopriwa on Jun 03, 2021 04:00 am I am working on a React Native package that uses @react-navigation/native@^5.9.4 and @react-navigation/stack@^v5.14.4. I want to test my components that use react-navigation 5. After reading Testing with Jest documentation, I expected to be able to run my test. Instead, I have this error: FAIL @pass-culture/id-check src/components/pages/Identity/tests/Residence.test.tsx ● Test suite failed to run TypeError: Cannot read property 'BaseButton' of undefined at Object.<anonymous> (../../node_modules/@react-navigation/stack/lib/commonjs/views/TouchableItem.ios.tsx:5:1) at Object.<anonymous> (../../node_modules/@react-navigation/stack/lib/commonjs/views/Header/HeaderBackButton.tsx:13:1) Configuration This is how my setup.ts entrypoint look like: require('react-native-gesture-handler/jestSetup'); jest.mock('react-native-reanimated', () => { const Reanimated = require('react-native-reanimated/mock'); // The mock for `call` immediately calls the callback which is incorrect // So we override it with a no-op Reanimated.default.call = () => {}; return Reanimated; }); // Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing // jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper'); // As of react-native@0.64.X file has moved jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper'); How can I configure react-navigation and test my module? Read in browser »  By CharmCcc on Jun 03, 2021 04:00 am When I just run a program to test connection with mqtt broker, client will always be lost. Here is my code var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) { fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic()) } var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) { fmt.Println("Connected") } var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) { fmt.Printf("Connect lost: %v\n", err) } var messageSubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) { fmt.Printf("Sub message: %s from topic: %s\n", msg.Payload(), msg.Topic()) } func main() { opts := mqtt.NewClientOptions() opts.AddBroker("tcp://broker.emqx.io:1883") opts.SetClientID("go_mqtt_client") opts.SetResumeSubs(true) opts.SetAutoReconnect(true) opts.SetOrderMatters(false) opts.SetCleanSession(false) // opts.SetTLSConfig() opts.SetDefaultPublishHandler(messagePubHandler) opts.OnConnect = connectHandler opts.OnConnectionLost = connectLostHandler client := mqtt.NewClient(opts) if token := client.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } sub(client) s := make(chan os.Signal, 1) signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) select { case <-s: glog.Infoln(`quit`) glog.Flush() } } func sub(client mqtt.Client) { topic := "topic/test" token := client.Subscribe(topic, 2, messageSubHandler) token.Wait() fmt.Printf("Subscribed to topic: %s\n", topic) } the result is $ go run cmd/client/client.go Connected Subscribed to topic: topic/test Connect lost: EOF Connected Connect lost: EOF Connected ... I know it's because of the clientId. But now I just run a client called go_mqtt_client, I don't know if it's because of the configuration. I've had this problem twice. First time I don't remember what was changed and it can work. But the second time (Right now), I can't fix it. It just can work if I change the ClientId... Read in browser »  By JuYeong on Jun 03, 2021 04:00 am I coded like this to remove duplicate values. vue <div class="col-md-6" style="float: left"> <ul class="list-group"> <li class="list-group-item" :class="{ active: index1 == currentIndex1 }" v-for="(member, index1) in uniqueMemName" v-bind:value="member.mem_name" :key="index1" @click="setActiveMember(member, index1)" > <strong style="margin-bottom: 5px"> {{member.mem_name}} </strong> </li> </ul> </div> vue (script) computed: { uniqueMemName() { return _.uniqBy(this.members, function(m) { return m.mem_name; }); } }, I also installed lodash. But I get an error. Which part is wrong? Please let me know if there is another method other than the one I wrote. Read in browser »  By Ankur Paranjpe on Jun 03, 2021 04:00 am I am trying to save API response and its data in Redux store, and the data should be called as soon as the page loads or Refresh. But there is neither any error or any output for the data as props in components. I go through the redux document but cant crack it properly. Is the below way correct? My code until here is: roleReducer.js export function activeUserRole() { return function (dispatch) { axios.get(`xyz/getUserDetails`) .then( (response) => { dispatch({ type: GET_USER_ROLES, data: ( response.data ) }) }) } } userRoleAction.js const activeUserRolesAction = (activeRoles) => { return { type: "GET_USER_ROLES", payload: activeRoles, } }; export default activeUserRolesAction; Saved the Data in store as activeUserRole: activeUserRole Calling the Props in component with following: <p>Active user Roles: {this.props.activeUserRole}</p>
Read in browser »  By ali al-karaawi on Jun 03, 2021 03:59 am In drf you can install djanog-filter and do url/?id=1&username=jack but in the following data what if I want to filter the dates. For example dates.title=interview. [{ "id": 1, "password": "pbkdf2_sha256$260000$xkkKjiHK3ddS1fbGwpt7bQ$EZOhxwywEWGL+0JfzSIEgWFXPPN/f8JelGX2RrjplQM=", "last_login": "2021-06-02T13:25:51Z", "username": "jack", "email": "x@x.com", "secon_email": "", "first_name": null, "last_name": null, "middle_name": null, "is_active": true, "is_staff": true, "is_superuser": true, "is_email_verified": true, "is_role_verified": true, "date_joined": "2021-06-02T13:24:36Z", "receive_newsletter": false, "birth_date": null, "city": null, "about_me": "", "phone_number": "", "second_phone_number": "", "imageUrl": null, "age": "", "address": null, "dates": [{ "id": 1, "deleted": null, "title": "apoentment", "description": "", "start": null, "end": null, "from_time": null, "to_time": null, "date_created": "2021-06-03T06:49:50.929466Z", "recurrence": , "priority": "", "date_type": 1, "created_by": 1, "users": [1] }, { "id": 2, "deleted": null, "title": "interview", "description": "", "start": null, "end": null, "from_time": null, "to_time": null, "date_created": "2021-06-03T06:49:50.929466Z", "recurrence": , "priority": "", "date_type": 2, "created_by": 1, "users": [1] } ] }] class UsersSerializer(DynamicSerializer): # dates is relational data ( it is another other model) class Meta: model = User fields = [*[x.name for x in User._meta.fields], 'dates'] depth = 1
Read in browser »  By flowermia on Jun 03, 2021 03:59 am Trying to run tests in TypeScript with Jest/SuperTest - however when I run npm test, it returns these errors: What package am I missing/not importing? FAIL test/test.ts ● Test suite failed to run test/test.ts:8:3 - error TS2304: Cannot find name 'before'. 8 before(PlatformTest.bootstrap(Server)); ~~~~~~ test/test.ts:9:3 - error TS2304: Cannot find name 'before'. 9 before(() => { ~~~~~~ test/test.ts:12:3 - error TS2304: Cannot find name 'after'. 12 after(PlatformTest.reset); These are my imports: import {PlatformTest} from "@tsed/common"; import * as SuperTest from "supertest"; import {Server} from "../src/Server";
Read in browser »  By mitim on Jun 03, 2021 03:59 am I'm trying to unravel a bit of the dark unknown that is webgl via PixiJS library. At this point, it probably should be noted that I haven't used PixiJS for awhile either, but it seemed to be a much more preferable approach than to manipulate the lower level underlying webgl state. My logic is currently this: I create two buffers ("current" and "previous") with the same fragment shader as well as a render buffer and a "render" fragment shader. Both buffers start off with the same content: a fill that is rgb(255, 10, 0) for every pixel. Right now, the fragment shader does this: void main(){ vec2 pixel = texture2D(buffer, vTextureCoord).xy; pixel.x = pixel.x * 0.95; // decrease red a bit pixel.y = pixel.y * 1.05; // increase green a bit gl_FragColor = vec4(pixel, 0.0, 1.0); } In the animation loop this is what is supposed to happen: - render previous buffer into the current buffer
- render the current buffer to the render buffer (for screen display)
- current and previous buffers are swapped: current buffer now becomes the previous buffer
Thus what should be happening is the red progressively fades out and green fades in. Right now, what happens is red fades out to black and green never fades in. It settles on rgb(9, 10, 0). From playing with (lots of random guessing), I've found that if I start with a higher green, say 11 or higher it works. Or if I increase the 'green rate' to 1.06 in the shader. Then it works. But for some reason, it does not at green 10 and 1.05 rate. My only guess is maybe some precision/rounding issues on the GLSL side but since I can't trace out any values within the shader, I don't really know. Nor do I know how to fix it. Though, quite possible/probable I'm just doing something else wrong entirely. What I currently have in jsfiddle: https://jsfiddle.net/nfrLjhgk/1/ Read in browser »  By hossam rakha on Jun 03, 2021 03:59 am I'm developing an application on flutter and I want to disable the application for tablets on both android and ios. Read in browser »  By Uche on Jun 03, 2021 03:59 am I have a site where a user can initiate an activation request, make payment to complete the activation, or delete the request (which will have the user return back to the notification page). Initiating activation requests and making a payment is working fine - thanks for the helps I got here. But the difficult part that is yet to work is being able to redirect the user to the notification page, the DELETE query is working but the redirection is NOT working. I have tried bits of help from similar questions I saw here but none worked for me. Here is the HTML part, where I have the Delete button and the item id to be deleted: <div class="nk-kycfm-action pt-2"> <input type="hidden" value="23" id="del_ID"> <button class="btn btn-lg btn-danger remove">Delete</button> </div> Here is the Javascript that pops up before I delete based on the item ID: <script type="text/javascript"> $(".remove").click(function(){ var delVal = document.getElementById("del_ID").value; if(confirm('Are you sure to delete this Activation request?')) { $.ajax({ url: 'bia-deleting-request-one.php', type: 'GET', data: {id: delVal}, error: function() { alert("Deletion not successful"); } }); } }); </script> Here is the PHP page where I successfully deleted the item BUT COULD NOT REDIRECT THE USER TO NOTIFICATION PAGE: if(isset($_GET['id'])) { $Product_To_Edit = $_GET['id']; $stmt = $db_c->prepare('DELETE FROM bia_user_package_table WHERE p_id = ? AND basic_user_id = ?'); $stmt->bind_param('ii', $Product_To_Edit, $Your_Basic_ID); $stmt->execute(); echo "<script type='text/javascript'> window.location.href = 'bia-package-notification.php'; </script>"; exit(); } I have tried so many options like this but it did not work for me: if ($stmt->affected_rows === 1) { header("location:bia-package-notification.php"); } All I need is to be able and redirect the user back to bia-package-notification.php once the deletion query is successful. Read in browser »  By Frank Sandqvist on Jun 03, 2021 03:59 am We have a server that allows for anyone to do processing on different vector files. One feature we are planning is to allow them to convert SVG's with text elements to paths. In order to do this accurately, we need to have the fonts they use installed on our server. Therefore it would require us to also have some licensed fonts installed on our server. What I'm wondering is, how does the font's license affect this? I would think that, since our server is only a pass-through (e.g. the user of it explicitly asks to convert licensed font X), it would be the user's responsibility to make sure that the end use of the converted work is used accurately (and they hold a license). I would imagine that our server holds the same responsibility as, say, Illustrator or Inkscape. E.g. it can replicate licensed fonts even if the end user does not own a license. Any input would be greatly appreciated! Read in browser »  By Stan on Jun 03, 2021 03:59 am I need to get request body after exeption in my ExceptionHandlingMiddleware. Before Exeption I get easy request body, but after I can't. Part of code from ExceptionHandlingMiddleware bellow. try { await _next.Invoke(context); } catch (Exception exception) { RequestBody = await FormatRequest(context.Request); } private async Task<string> FormatRequest(HttpRequest request) { request.EnableBuffering(); var body = request.Body; var buffer = new byte[Convert.ToInt32(request.ContentLength)]; await request.Body.ReadAsync(buffer, 0, buffer.Length); var bodyAsText = Encoding.UTF8.GetString(buffer); return $"{request.Scheme} {request.Host}{request.Path} {request.QueryString} {bodyAsText}"; } In result I get this body I tried to get body in try by this way try { RequestBody = await FormatRequest(context.Request); await _next.Invoke(context); } And it works, I get normal json data, but I have exeption that my model in not valid because it is empty. I tried to do request.EnableBuffering(); before exeption but it didn't help me. So If I try to get body after exeption, I can`t parse it. If I get it before exeption my model in controller is not valid. How I can get my model after exeption for loggin in ExceptionHandlingMiddleware? Read in browser »  By SHByun on Jun 03, 2021 03:59 am How do i fix the code? line 12, 17, 19, 20, 33, 34 annotation problem and i did make parameter I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method:I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method:I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method:I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method:I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method:I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method: package com.ds.settings; import android.app.DialogFragment; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class TestActivity { @Override public void TestActivity(String id, String pass) { Toast.makeText(this, id+"/"+pass, Toast(private int Toast).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { show(); } }); } void show() { DialogFragment newFragment = new DialogFragmentExample(); newFragment.show(getFragmentManager(), "dialog"); //"dialog"라는 태그를 갖는 프래그먼트를 보여준다. } } Read in browser »  By Samarth Sharma on Jun 03, 2021 03:58 am def myFunction(x): if x%2 == 0: print("number is even") else: print("number is odd") myFunction(input("Enter number"))
Read in browser »  By vambay colony on Jun 03, 2021 03:57 am I have a HTML table that displays data from MySQL using PHP. It is creating unwanted blank space right above it. How can I get rid off it? echo "<center><br><br><b>Your commissions are :</b></center>"; $sql1 = "SELECT orderid, dateofpur, orderamount,commissionamount FROM comm where referralcode='".$sum1."'"; $result2 = $conn->query($sql1); if ($result2->num_rows > 0) { echo "<center><div><table><tr><th>S.No.</th><th>Order ID</th><th>Date of order</th><th>ORDER AMOUNT</th><th>COMMISSION</th></tr>"; // output data of each row while($row1 = $result2->fetch_assoc()) { echo "<tr><td>".$counter2++."</td><td>".$row1["orderid"]."</td><td>".$row1["dateofpur"]. "</td><td>".$row1["orderamount"]. "</td><td>".$row1["commissionamount"]. "</td></tr><br>"; } echo "</table></div></center><br>"; here is how my page is looking Read in browser »  By roshannepal_x on Jun 03, 2021 03:54 am Why this program to make a linked list of characters and printing currently added item is showing output twice ? And I am new to data structure,so i wanna ask another question . Is this implementation in Insert function is done correctly by me? Code #include <stdio.h> #include <stdlib.h> struct Node { char data; struct Node *next; }; struct Node *Head; void Insert(char data) { struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = data; temp->next = Head; Head = temp; printf("Data in this Node: %c \n", temp->data); } int main() { Head=NULL; char data; while (1) { printf("Enter a Character : "); scanf("%c", &data); if (data == '0') break; Insert(data); } } Output PS C:\Users\Dell\OneDrive\Desktop\Data Structure1\Data Structure Text Book> cd "c:\Users\Dell\OneDrive\Desktop\Data Structure1\Data Structure Text Book\Linked list\" ; if ($?) { gcc practice1.c -o practice1 } ; if ($?) { .\practice1 } Enter a Character : q Data in this Node: q Enter a Character : Data in this Node: Enter a Character : w Data in this Node: w Enter a Character : Data in this Node: Enter a Character : 0 PS C:\Users\Dell\OneDrive\Desktop\Data Structure1\Data Structure Text Book\Linked list>
Read in browser »  By Learner on Jun 03, 2021 03:51 am I have a simple table and I want to sort it by specific rules. My desired output looks like this: PERSON_THIRD_BUF PERSON_TWO_BUF PERSON_TWO_BUF_11 PERSON_TWO_BUF_10 PERSON_TWO_BUF_9 PERSON_TWO_BUF_8 PERSON_TWO_BUF_7 PERSON_TWO_BUF_6 PERSON_TWO_BUF_5 PERSON_TWO_BUF_4 PERSON_TWO_BUF_3 PERSON_TWO_BUF_2 PERSON_TWO_BUF_1 So PERSON_THIRD_BUF should be the first, PERSON_TWO_BUF should be the second, and PERSON_TWO_BUF_* should be in descending order: I've managed to sort PERSON_TWO_BUF, PERSON_THIRD_BUF, however I could not figure out how to sort PERSON_TWO_BUF_* in descending order. DECLARE @t table(col1 VARCHAR(50)); insert into @t values ( N'PERSON_TWO_BUF' ), ( N'PERSON_THIRD_BUF' ), ( N'PERSON_TWO_BUF_1' ), ( N'PERSON_TWO_BUF_2' ), ( N'PERSON_TWO_BUF_3' ), ( N'PERSON_TWO_BUF_4' ), ( N'PERSON_TWO_BUF_5' ), ( N'PERSON_TWO_BUF_6' ), ( N'PERSON_TWO_BUF_7' ), ( N'PERSON_TWO_BUF_8' ), ( N'PERSON_TWO_BUF_9' ), ( N'PERSON_TWO_BUF_10' ), ( N'PERSON_TWO_BUF_11' ) SELECT * FROM @t ORDER BY CASE WHEN COL1 = 'PERSON_THIRD_BUF' THEN 0 WHEN COL1 = 'PERSON_TWO_BUF' THEN 1 WHEN COL1 LIKE 'PERSON_TWO_BUF_%' THEN 3 END Any help will be greatly appreciated Read in browser »  By Ariel on Jun 03, 2021 03:40 am I'm trying to make something similar to the iOS notes app but for journaling; basically, I want there to be a list of journal entry cells users can scroll through which each display a detail view after they're clicked on where the user can view and edit their journal entry. The updating works fine, the only issue is that JournalDetailView dismisses itself after updateEntry() is called (after the user taps the "Done" button). I'm guessing this is because updateEntry() forces the view to reload, but I'm not sure how to get around this. Here's the model: struct JournalEntry: Identifiable, Hashable, Codable { @DocumentID var id: String? = UUID().uuidString @ServerTimestamp var date: Timestamp? var text: String var userId: String? } Here's the view code: struct JournalCellView: View { @ObservedObject var vm: JournalViewModel @Binding var addButtonTapped: Bool @State var showDetail = false @State var entry: JournalEntry var body: some View { NavigationLink(destination: JournalDetailView(vm: vm, entry: $entry, text: entry.text), isActive: $showDetail, label: { VStack { HStack { Text(entry.date!.dateValue(), style: .date) .fontWeight(.bold) .font(.system(size: 18)) .foregroundColor(.black) .padding(.bottom, 3) Spacer() } HStack { Text(entry.text) .font(.system(size: 14)) .foregroundColor(.secondary) .lineLimit(1) Spacer() } }.padding() .background(RoundedRectangle(cornerRadius: 18).foregroundColor(.white)) .padding(.vertical, 4) .onTapGesture { showDetail = true } .onAppear { if addButtonTapped { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { showDetail = true } addButtonTapped = false } } }) } } struct JournalDetailView: View { @Environment(\.presentationMode) var presentationMode @ObservedObject var vm: JournalViewModel @Binding var entry: JournalEntry @State var text: String @State var isTyping = false var body: some View { VStack { HStack { Button(action: { presentationMode.wrappedValue.dismiss() }, label: { Image(systemName: "chevron.left").foregroundColor(.burgundy) }) Spacer() if isTyping { Button(action: { endEditing() updateEntry() isTyping = false }) { Text("Done") .foregroundColor(.burgundy) } } else { Text("") } }.padding(.vertical) Text(entry.date!.dateValue(), style: .date) TextEditor(text: $text) .onTapGesture { isTyping = true } Spacer() }.padding() .navigationBarHidden(true) } func updateEntry() { vm.updateJournalEntry(docID: entry.id!, date: entry.date!, text: text) } } Here's updateJournalEntry(): func updateJournalEntry(docID: String, date: Timestamp, text: String) { db.collection("journals").document(docID ).updateData(["date": date, "text": text, "userId": Auth.auth().currentUser!.uid]) }
Read in browser »  By Komali on Jun 03, 2021 03:26 am I'm working on Kmeans clustering but unlike supervised learning I cannot figure the performance metrics for clustering algorithms. How to perform the accuracy after training the data? can anyone help me regarding these? Thank You. Read in browser »  By Meenakshisundaram Ramanathan on Jun 03, 2021 03:18 am I have a text file in the below format . I need to remove the text between the first and second semicolon (delimiter ), but retain the second semicolon $cat test.txt abc;def;ghi;jkl mno;pqr;stu,xxx My expected output abc;ghi;jkl mno;stu,xxx I tried using sed 's/^([^;][^;]*);.*$/\1/', but it removes everything after the first semicolon. I also tried with cut -d ';' -f2, this only give the 2nd field as output. Read in browser »  By PirateApp on Jun 03, 2021 02:18 am Buefy has a Field.vue component that looks as shown below <template> <div class="field" :class="rootClasses"> <div v-if="horizontal" class="field-label" :class="[customClass, fieldLabelSize]"> <label v-if="hasLabel" :for="labelFor" :class="customClass" class="label" > <slot v-if="$slots.label" name="label"/> <template v-else>{{ label }}</template> </label> </div> <template v-else> <label v-if="hasLabel" :for="labelFor" :class="customClass" class="label"> <slot v-if="$slots.label" name="label"/> <template v-else>{{ label }}</template> </label> </template> <b-field-body v-if="horizontal" :message="newMessage ? formattedMessage : ''" :type="newType"> <slot/> </b-field-body> <div v-else-if="hasInnerField" class="field-body"> <b-field :addons="false" :type="newType" :class="innerFieldClasses"> <slot/> </b-field> </div> <template v-else> <slot/> </template> <p v-if="hasMessage && !horizontal" class="help" :class="newType" > <slot v-if="$slots.message" name="message"/> <template v-else> <template v-for="(mess, i) in formattedMessage"> {{ mess }} <br :key="i" v-if="(i + 1) < formattedMessage.length"> </template> </template> </p> </div> </template> Full code for the above is right HERE I want to add a transition the paragraph with class help so that it doesn't abruptly appear and disappear. How do I achieve this? Read in browser »  By Totti on Jun 03, 2021 02:08 am Question about the batch process using the java spring framework. Found that setting httpComponentsClientHttpRequestFactory.setBufferRequestBody to false solves the heap error. However, when I ran a performance test, the heap error still occurred. If the input file for the batch process is a 1000MB file, it terminates normally, but if it exceeds 1000MB, an error occurs. Does anyone know how to fix this other than setting httpComponentsClientHttpRequestFactory.setBufferRequestBody to false? Read in browser »  By Sarah Szabo on Jun 03, 2021 02:00 am I have a program which would benefit greatly (large dataset with a somewhat involved mapping and filtering scheme, but not dependent on exterior variables / synchronization) from using parallelStream(), but must be collected as a set. I'm somewhat new to parallel-streams (this being my first experience with them), and tried using var nvmePackets = list.parallelStream().map(x -> complicated_mapping_here).collect(Collectors.toSet()); only to discover that this led to concurrent modification of a non-concurrent backend and a deadlock condition behind the scenes. Since the operation benefits from concurrency, is there any way to do this using parallelstream? Or do I have to use another technique? It always hangs at the stop where this line of code is executed, and waits forever at ForkJoinTask.java at externalAwaitDone(); when I use the debugger. Unfortunatly, there isn't a Set analog of toConcurrentMap() that I could find. How can I avoid this deadlock while still getting both the parallelism granted for the computation and having the end result be a set? System: JDK 16 Read in browser »  By shashank shekhar on Jun 02, 2021 03:15 pm I need to count data from reqst body in httptrigger function.Data is coming as object type. I am deserialisizing the reqd body as shown below.Below are the object type data i am getting in req.body. { "Response": [ { "id": "1", "name": "Warburtons Medium Sliced Soft White Bread 400g", "description": "Warburtons Medium Sliced White 400G", "brand": "Warburtons", "ean": "123", "mediaStorageKey": "b", "maxQuantity": 6, "price": 0.95, "size": 400, "sizeUnits": "Grams" }, { "id": "a", "name": "Co-op Orvieto Classico 75cl", "description": "Co-op Orvieto Classico 75CL", "brand": "Co-op", "ean": "489", "mediaStorageKey": "c", "maxQuantity": 6, "price": 5.5, "size": 75, "sizeUnits": "Centilitres" }, { "id": "kl", "name": "Co Op Garden Peas in Water 290g", "description": "Co-op Garden Peas 290G", "brand": "Co Op", "ean": "678", "mediaStorageKey": "f", "maxQuantity": 6, "price": 0.45, "size": 175, "sizeUnits": "Grams" } ] } string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic body = JsonConvert.DeserializeObject(requestBody); dynamic data = body["Response"]; Till this i am getting data like below. {[{"id":"1","name":"b"},{"id":"f","name":"j"}]} But now i am not able to count these data which gives 2 in this case as i have to apply for loop. Neither Count,Count() is working here. I am getting the below error. Newtonsoft.Json.Linq.JValue does not contain a definition for Count
Read in browser »  By salimtop on Jun 02, 2021 01:39 pm I expect to get the following output: My rank is: 0 num is: 0 My rank is: 1 num is: 1 My rank is: 2 num is: 2 My rank is: 3 num is: 3 from the following code: #pragma omp parallel { int my_rank = omp_get_thread_num(); #pragma omp parallel for num_threads(4) for(int i = 0; i < 4; i++){ printf("My rank is: %d num is: %d\n",my_rank, i); } } But it gives following output: My rank is: 0 num is: 0 My rank is: 0 num is: 1 My rank is: 0 num is: 2 My rank is: 0 num is: 3 My rank is: 2 num is: 0 My rank is: 2 num is: 1 My rank is: 2 num is: 2 My rank is: 2 num is: 3 My rank is: 3 num is: 0 My rank is: 3 num is: 1 My rank is: 3 num is: 2 My rank is: 3 num is: 3 My rank is: 1 num is: 0 My rank is: 1 num is: 1 My rank is: 1 num is: 2 My rank is: 1 num is: 3 What is the problem? Why it does not work? Read in browser »  By Sushma on Jun 02, 2021 08:47 am I am getting this error: Exception occurs here in line db.SaveChanges(); 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll.Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. What is wrong with the code.Plz help me. Below is my Code Model class: public class EmployeeDb : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Employee>().ToTable("EmployeeTable"); } public DbSet<Employee> Employees { get; set; } } public class Employee { [Key] public int EmployeeID { get; set; } public string EmployeeName { get; set; } public string EmployeeAddress { get; set; } public string EmployeeEmail { get; set; } } Controller class: public class EmployeeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Create(Employee emp) { EmployeeDb dbobj = new EmployeeDb(); dbobj.Employees.Add(emp); dbobj.SaveChanges(); return View("Employee",emp); } } View : @model EmployeeMgmt.Models.Employee @using (Html.BeginForm("Create","Employee",FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Employee</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.EmployeeID, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.EmployeeID, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.EmployeeID, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmployeeName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.EmployeeName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.EmployeeName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmployeeAddress, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.EmployeeAddress, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.EmployeeAddress, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmployeeEmail, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.EmployeeEmail, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.EmployeeEmail, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> What is causing this error, and how do I fix it? Read in browser »  Recent Articles:
|
No comments:
Post a Comment