Thursday, May 12, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Limitations in Google admob and Facebook Audience Network for Xamarin.ios

Posted: 12 May 2022 05:19 AM PDT

I have tried integrating both google admob and facebook audience network in my application with no success.

I have now been told that there are limitations to the nuget packages which is why it is not working.

Someone must have successfully integrated native ads from these sites in Xamarin.iOS?

Please help!

Get (index,column) pair where the value is True

Posted: 12 May 2022 05:19 AM PDT

Say I have a dataframe df

  a        b     c  0 False  True   True  1 False  False  False  2 True   True   False  3 False   False  False  

I would like all (index,column) pairs e.g (0,"b"),(0,"c),(2,"a"),(2,"b") where the True value is.

Is there a way to do that, without looping over either the index or columns?

Asp.Net Core http requests shows Headers.ContentLength

Posted: 12 May 2022 05:19 AM PDT

I am doing an http get call and I can see that Headers.ContentLength always returns null whereas I can see that in fiddler a value: This is my code

string url = $"url";    HttpClientHandler httpClientHandler = new HttpClientHandler();    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;  httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;    HttpClient httpClient = new HttpClient(httpClientHandler)  {      BaseAddress = new Uri(url)  };    httpClient.DefaultRequestHeaders.Accept.Clear();  httpClient.DefaultRequestHeaders.Add("Authorization", $"Token {authToken.Value}");  httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");    httpClientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;    HttpResponseMessage response = await httpClient.GetAsync(string.Empty, HttpCompletionOption.ResponseHeadersRead);    response.EnsureSuccessStatusCode();      var responseString = await response.Content.ReadAsStringAsync();    var length = response.Content.Headers.ContentLength;  

ContentLength is always null. Fiddler below shows body length and also header length and Im downloading the data without any issue.

enter image description here

enter image description here

I need to be able to read content length header to decide if I will allow download. Why am I receiving null

Refine Array of Objects to Different Variables dynamically

Posted: 12 May 2022 05:19 AM PDT

I'm trying to create a food menu using javascript. I'm using the

`(      {"Category": "Drinks", "item": "Coke", "Price": "20"},      {"Category": "Snacks", "item": "French Fries", "Price": "20"},    {"Category": "Drinks", "item": "Limca", "Price": "19"},    {"Category": "Snacks", "item": "Manchurian", "Price": "19"}  ); `  

I need this to be in a repeater. Like:

Drinks:  Coke 20  Limca 19  Snacks:  French Fries 20  Manchurian 19  

So, I'm looking to parse the array of objects to assign it to the repeater.

React App Keep Reloading until it get crashed

Posted: 12 May 2022 05:19 AM PDT

I am new to react js, I created a react app, and whenever I try to open the app it continuously reloads. can anyone help me in this? i tried but unable to find out any perfect solution.

Any solution?

package.json

{    "name": "sf",    "author": "KKK Team",    "version": "0.0.1",    "private": true,    "homepage": "/sfrs",    "scripts": {      "start": "env-cmd -f .env.development react-scripts start",      "build:development": "env-cmd -f .env.development react-scripts build",      "build:nonprod": "env-cmd -f .env.nonprod react-scripts build",      "build:production": "env-cmd -f .env.production react-scripts build",      "build": "react-scripts build",      "test": "jest --verbose",      "test:dev": "jest",      "test:watch": "jest --silent --watchAll",      "test:coverage": "jest --silent --coverage",      "eject": "react-scripts eject"    },    "eslintConfig": {      "extends": "react-app"    },    "browserslist": {      "production": [        ">0.2%",        "not dead",        "not op_mini all"      ],      "development": [        "last 1 chrome version",        "last 1 firefox version",        "last 1 safari version"      ]    },    "dependencies": {      "@date-io/date-fns": "^1.3.13",      "@emotion/react": "^11.7.1",      "@emotion/styled": "^11.6.0",      "@material-table/core": "^0.2.20",      "@mui/icons-material": "^5.3.1",      "@mui/lab": "^5.0.0-alpha.66",      "@mui/material": "^5.3.1",      "@mui/styles": "^5.3.0",      "axios": "^0.25.0",      "buffer": "^6.0.3",      "clsx": "^1.1.1",      "crypto-browserify": "^3.12.0",      "env-cmd": "^10.1.0",      "jsonwebtoken": "^8.5.1",      "lodash": "^4.17.21",      "moment": "^2.29.1",      "msal": "^1.4.16",      "prop-types": "^15.8.1",      "react": "^17.0.2",      "react-dom": "^17.0.2",      "react-perfect-scrollbar": "^1.5.8",      "react-redux": "^7.2.6",      "react-router": "^6.2.1",      "react-router-dom": "^6.2.1",      "recompose": "^0.30.0",      "redux": "^4.1.2",      "redux-logger": "^3.0.6",      "redux-thunk": "^2.4.1",      "stream-browserify": "^3.0.0",      "sweetalert2": "^11.4.8",      "sweetalert2-react-content": "^4.2.0",      "util": "^0.12.4",      "validator": "^13.7.0",      "web-vitals": "^2.1.4"    },    "devDependencies": {      "@testing-library/jest-dom": "^5.16.1",      "@testing-library/react": "^12.1.2",      "@testing-library/user-event": "^13.5.0",      "eslint": "^7.11.0",      "eslint-config-airbnb": "^18.2.0",      "eslint-config-prettier": "^6.11.0",      "eslint-plugin-import": "^2.22.0",      "eslint-plugin-jsx-a11y": "^6.3.1",      "eslint-plugin-prettier": "^3.1.4",      "eslint-plugin-react": "^7.20.3",      "eslint-plugin-react-hooks": "^4.0.8",      "husky": "^4.2.3",      "jest-canvas-mock": "^2.3.1",      "lint-staged": "^10.0.8",      "prettier": "^1.19.1",      "react-error-overlay": "^6.0.9",      "react-scripts": "4.0.3"    },    "jest": {      "setupFiles": [        "jest-canvas-mock"      ]    },    "husky": {      "hooks": {        "pre-commit": "lint-staged",        "pre-push": "npm run test"      }    },    "lint-staged": {      "src/**/*.{js,jsx,json,css}": [        "prettier --write",        "eslint --fix"      ]    },    "babel": {      "presets": [        "@babel/preset-react",        [          "@babel/preset-env",          {            "targets": {              "node": "current"            }          }        ]      ],      "plugins": [        [          "@babel/plugin-proposal-class-properties",          {            "loose": true          }        ]      ]    },    "resolutions": {      "react-error-overlay": "6.0.9"    }  }  

I am using MUI 5. I have tried with upgrading and degrading the node version but unable to solve the issue.

React-Admin takes too much time to compile

Posted: 12 May 2022 05:19 AM PDT

I'm working on a ReactJS project which has very minimal setup nothing special but some it sucks sometimes due to it's compilation time.

It takes almost 10-15 mins to compile and start the project, I do have other ReactJS project on the same system but they start quickly thus there is no compilation time issue.

Can you explain how to avoid this? What could be the possible reasons?

Is there any way to convert voice into text in flutter?

Posted: 12 May 2022 05:19 AM PDT

I need to use voice recorder and convert that voice into text in flutter? Is there any packages or methods.

This is my code. Someone plz guide me what is the purpose of values 1.0/255 and (0,0,0) here?

Posted: 12 May 2022 05:19 AM PDT

. Someone plz guide me what is the purpose of values 1.0/255 and (0,0,0) here? inpBlob = cv2.dnn.blobFromImage(frame, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False)

I don't know why the size of val_acc and acc is different

Posted: 12 May 2022 05:19 AM PDT

x and y must have same first dimension, but have shapes (30,) and (1,)

enter image description here

model.compile(loss='categorical_crossentropy',                optimizer=optimizers.RMSprop(lr=1e-4),                metrics=['accuracy'])    train_datagen = ImageDataGenerator(rescale=1./255)  train_generator = train_datagen.flow_from_directory(      base_path,      target_size = (150,150),      batch_size = 20,      class_mode = 'categorical')    validation_datagen = ImageDataGenerator(rescale=1./255)  validation_generator = validation_datagen.flow_from_directory(      val_path,      target_size = (150,150),      batch_size = 20,      class_mode = 'categorical')        history = model.fit_generator(      train_generator,      steps_per_epoch=20,      epochs=30,      validation_data=validation_generator,      validation_steps=20)  

I don't know why it doesn't work

How to determine the number of distinct deterministic policies in a MDP?

Posted: 12 May 2022 05:18 AM PDT

I'm trying to tackle this question to understand MDP. Can someone explain how can you determine or calculate the number of distinct deterministic policies in the below MDP? Or resources where I can learn how to do this. I watched various videos and tried to google a way to calculate this but I seem to be going in circles. I have checked other examples as well but I don't see how it can be calculated.

The question is as follows,

Actions are represented by black dots. The pair of numbers beside each arrow indicates the transition probabilities (the left number) under action and the rewards (the right number) received when the agent goes to a state. Assume a discount factor of γ = 0.95.

MDP

Sorting By Numbers when the page loads without click event

Posted: 12 May 2022 05:19 AM PDT

Hi I have a modal for event details as in the picture enter image description here

And here, users can accept/reject the event or it can be pending. In api, the status : pending '0' - yellow bg, accept: '1' - green bg, reject: '3' - red bg

I want to sort them like 0-1-2-3 and show in the UI when the page is loaded. I wrote the sort fuction as below. But how can I show show it in UI ? the order doesnt change at all. I put this function to the button when I toggle the modal

const handleSort = () => {      createdEventDetails?.invites?.map(item => Number(item.status)).sort();      console.log(        'hey',        createdEventDetails?.invites?.map(item => Number(item.status)).sort(),      );    };  

Here is my full code

import React, {useEffect, useState} from 'react';  import {View, Text} from 'react-native';  import {Icon} from '@/components';  import styles from '@/screens/dashboard/friends/Events/Events.styles';  import images from '@/config/images';  import {TouchableOpacity} from 'react-native-gesture-handler';  import {blackColor} from '@/config/colors';  import {strings} from '@/localization';  import {useDispatch, useSelector} from 'react-redux';  import {    closeEventDetailsModal,    fetchEventDetails,    fetchEventsList,    openEventDetailsModal,  } from '@/store/events/events';  import CreatedEventDetails from './CreatedEventDetails';    const CreatedEvents = ({onPress}) => {    const eventsList = useSelector(state => state.events.eventsList);    const createdEventDetails = useSelector(state => state?.events?.eventDetails);      const eventModalVisibility = useSelector(      state => state.events.eventModalVisibility,    );    const dispatch = useDispatch();      const toggleModal = id => {      if (eventModalVisibility) {        dispatch(closeEventDetailsModal());      } else {        dispatch(openEventDetailsModal());      }      // setModalVisible(!isModalVisible);      dispatch(fetchEventDetails(id));      console.log('id', id);    };      useEffect(() => {      dispatch(fetchEventsList());    }, [dispatch]);      const handleSort = () => {      createdEventDetails?.invites?.map(item => Number(item.status)).sort();      console.log(        'hey',        createdEventDetails?.invites?.map(item => Number(item.status)).sort(),      );    };      return (      <View>        <View>          <Text style={styles.eventsTitleStyle}>            {strings.pendingEvents.allEventsTitle}          </Text>          {eventsList?.length > 0 ? (            eventsList?.map(event => {              const capitilizedLetter = event.name                .toLowerCase()                .charAt(0)                .toUpperCase();              const restOfTheName = event.name.slice(1);              return (                <TouchableOpacity                  onPress={() => {                    toggleModal(event.id);                    handleSort();                  }}                  key={event.id}>                  <View style={styles.eventDatesContainer}>                    <View style={styles.dateContainer}>                      <Text style={styles.date}>                        {event.event_date.substring(0, 10)}                      </Text>                      <Icon                        icon={images.ic_right_arrow}                        width={16}                        height={16}                        style={styles.inputArrow}                        color={blackColor}                      />                    </View>                    <Text                      style={                        styles.event                      }>{`${capitilizedLetter}${restOfTheName}`}</Text>                  </View>                </TouchableOpacity>              );            })          ) : (            <Text>There are no events</Text>          )}        </View>        <CreatedEventDetails          isVisible={eventModalVisibility}          closeModal={toggleModal}        />      </View>    );  };    export default CreatedEvents;  
import React, {useEffect, useState} from 'react';  import {View, ScrollView, Text, Image, Pressable} from 'react-native';  import styles from '@/screens/dashboard/friends/Events/CreatedEventDetails.styles';  import Modal from 'react-native-modal';  import common from '@/config/common';  import {useDispatch, useSelector} from 'react-redux';  import FastImage from 'react-native-fast-image';  import images from '@/config/images';  import {Icon, LoadingIndicator} from '@/components';  import {    closeEventDetailsModal,    fetchEventsList,    handleDeleteEvent,    handleWithDrawEvent,    LOADING,  } from '@/store/events/events';  import {EVENT_STATUS} from '@/constants/eventStatus';    const CreatedEventDetails = ({isVisible, closeModal}) => {    const createdEventDetails = useSelector(state => state?.events?.eventDetails);    const userInfo = useSelector(state => state.profile.user);    const dispatch = useDispatch();      const isLoading =      useSelector(state => state?.events?.eventResponseStatus) === LOADING;      const capitilizedLetter = createdEventDetails?.name      ?.toLowerCase()      .charAt(0)      .toUpperCase();    const restOfTheName = createdEventDetails?.name?.slice(1);      const deleteEvent = id => {      dispatch(handleDeleteEvent(id));      dispatch(closeEventDetailsModal());    };      const withDrawEvent = id => {      dispatch(handleWithDrawEvent(id));      dispatch(closeEventDetailsModal());    };      function getBgColor(condition) {      switch (condition) {        case EVENT_STATUS.STATUS_NEW:          return '#ef9d50';        case EVENT_STATUS.STATUS_ACCEPTED:          return '#a1dc6a';        case EVENT_STATUS.STATUS_TENTATIVE:          return 'blue';        case EVENT_STATUS.STATUS_REJECTED:          return 'red';        default:          return '#ef9d50';      }    }      const isOwner = createdEventDetails?.owner?.id === userInfo?.id;      const [loading, setLoading] = useState(true);    useEffect(() => {      setTimeout(() => {        setLoading(false);      }, 100);    }, []);      return (      <>        {loading ? (          <LoadingIndicator visible={isLoading} />        ) : (          <View style={styles.modalContainer}>            <Modal              isVisible={isVisible}              propagateSwipe              onModalWillHide={() => {                setTimeout(() => {                  dispatch(fetchEventsList());                }, 500);                // console.log('tarkan');              }}>              <View style={styles.content}>                <LoadingIndicator visible={isLoading} />                <View style={styles.closeBtnContainer}>                  <Pressable style={styles.closeBtn} onPress={closeModal}>                    <Text style={styles.closeText}>X</Text>                  </Pressable>                </View>                <View>                  <Text                    style={                      styles.contentTitle                    }>{`${capitilizedLetter}${restOfTheName}`}</Text>                  <Text style={styles.contenSubtTitle}>                    {createdEventDetails?.event_date?.substring(0, 10)}                    {'\n'}                    {createdEventDetails?.from_time} -{' '}                    {createdEventDetails?.to_time}                  </Text>                  <Text style={styles.contentText}>                    {createdEventDetails?.location}                  </Text>                  <View style={styles.participantsContainer}>                    <Text style={styles.contentTitle}>                      Participants ({createdEventDetails?.invites?.length})                    </Text>                    <View style={common.stickyButtonLine} />                    <ScrollView>                      {createdEventDetails?.invites?.map(invite => (                        <View style={styles.checkboxContainer} key={invite.id}>                          <View style={styles.imageContainer}>                            {invite?.user?.thumb ? (                              <FastImage                                source={{uri: invite?.user?.thumb}}                                style={styles.listItemUserImage}                                resizeMode={FastImage.resizeMode.cover}                              />                            ) : (                              <Icon                                icon={images.ic_user}                                style={styles.noUserIcon}                              />                            )}                            <Text style={styles.contentPersonName}>                              {invite?.user?.name}                            </Text>                          </View>                          // here in this map, I display the status colors according to                           // accept/reject/pending                          <View                            style={{                              backgroundColor: getBgColor(invite?.status),                              width: 25,                              height: 25,                              borderRadius: 25,                            }}                            onPress={handleSort}>                            <Text>{''}</Text>                          </View>                        </View>                      ))}                    </ScrollView>                  </View>                  <View>                    <View>                      <Text style={styles.contentTitle}>                        Hobbies ({createdEventDetails?.hobbies?.length})                      </Text>                      <View style={common.stickyButtonLine} />                      <View style={styles.hobbiesContainer}>                        {createdEventDetails?.hobbies?.map(hobby => (                          <View style={styles.emojiContainer} key={hobby.id}>                            <Text>{hobby.emoji}</Text>                          </View>                        ))}                      </View>                      <View style={common.stickyButtonLine} />                    </View>                    <View style={[styles.buttons, styles.singleButtonAlign]}>                      {isOwner ? (                        <Pressable style={styles.decline}>                          <Text                            style={styles.declineText}                            onPress={() => deleteEvent(createdEventDetails?.id)}>                            Delete                          </Text>                        </Pressable>                      ) : (                        <Pressable style={styles.decline}>                          <Text                            style={styles.declineText}                            onPress={() =>                              withDrawEvent(createdEventDetails?.id)                            }>                            Withdraw                          </Text>                        </Pressable>                      )}                    </View>                  </View>                </View>              </View>            </Modal>          </View>        )}      </>    );  };    export default CreatedEventDetails;  

Why am I getting error of 'android.widget.EditText com.google.android.material.textfield.TextInputLayout.getEditText()' on a null object reference

Posted: 12 May 2022 05:19 AM PDT

I have seen many forums related to this question but nothing resolved my issue. I hope I get it here.

Here is my Activity Code

public class addIndividual extends AppCompatActivity {  public TextInputLayout individualName;  public TextInputLayout individualPhno;  FirebaseFirestore db;  String name;  String phno;    @Override  protected void onCreate(Bundle savedInstanceState) {      db=FirebaseFirestore.getInstance();      individualName  = (TextInputLayout) findViewById(R.id.individualName);      individualPhno= (TextInputLayout) findViewById(R.id.individualPhno);      super.onCreate(savedInstanceState);      setContentView(R.layout.activity_add_individual);    }      public void submitButton(View view) {      name= individualName.getEditText().getText().toString();      phno= "hello";      Map<String,String> individualInfo = new HashMap<String,String >();      individualInfo.put("name",name.trim());      individualInfo.put("phNo",phno.trim());        db.collection("individuals").add(individualInfo)              .addOnCompleteListener(new OnCompleteListener<DocumentReference>() {                  @Override                  public void onComplete(@NonNull Task<DocumentReference> task) {                        Toast.makeText(addIndividual.this, "Inserted Successfully", Toast.LENGTH_SHORT).show();                  }              });      }  }  

XML Code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="horizontal"  android:layout_margin="10dp"  tools:context=".PSLogin.addIndividual">    <LinearLayout      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:orientation="vertical"      android:layout_gravity="center">            <com.google.android.material.textfield.TextInputLayout          android:id="@+id/individualName"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:hint="Enter Individual Name"          android:layout_below="@id/textView1"          android:layout_marginTop="40dp"          style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">          >            <com.google.android.material.textfield.TextInputEditText              android:layout_width="match_parent"              android:layout_height="wrap_content"              />        </com.google.android.material.textfield.TextInputLayout>        <com.google.android.material.textfield.TextInputLayout          android:id="@+id/individualPhno"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:hint="Enter Individual Phone Number"          android:layout_below="@id/username"          android:layout_marginTop="30dp"          style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">          >            <com.google.android.material.textfield.TextInputEditText              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:inputType="textPassword"              />        </com.google.android.material.textfield.TextInputLayout>        <Button          android:id="@+id/submit"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="Submit"          android:layout_below="@id/password"          android:onClick="submitButton"          android:layout_marginTop="30dp"          android:gravity="center"          style="?attr/materialButtonOutlinedStyle"          />    </LinearLayout>    </LinearLayout>  enter code here  

I have changed the TextInputLayout to EditText but the problem persists no result Error Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference When public EditText individualName;

Error is occurring at name= individualName.getEditText().getText().toString();

Keep only unmatched records when joining tables

Posted: 12 May 2022 05:20 AM PDT

I have 2 access tables that contain partially similar data, one being more enriched than the other. The idea here is to join the two tables by the fields id and num and to get from the table T2 the num that are not in the table T1

T1:

id num
1 34
3 51
7 23

T2:

id num status
1 34 done
1 79 done
1 39 done
3 51 done
7 23 done

Expected result:

id num status
1 79 done
1 39 done

Under access I read on internet that there is no MINUS operator like under MySQL, so I tried with EXCEPT but the query takes a long time (stopped after 10min)

So I tried this:

SELECT T2.*  FROM T2 LEFT JOIN T1 ON (T1.id =T2.id)   WHERE T1.num IS NULL AND ( (T2.status LIKE 'done') );  

The problem now is, I don't have all the records that are in T2 but not in T1

How to replace an Item in scala Map, keeping the order

Posted: 12 May 2022 05:19 AM PDT

I have a Map like this .

  val m1 = Map(1 -> "hello", 2 -> "hi", 3 -> "Good", 4 -> "bad")    val m2 = Map(1 -> "Great", 3 -> "Guy")  

Now I need to derive another Map from m1 and m2, and I need to replace elements of m1 by those m2 with order preserved.

m3 should like

   Map(1 -> "Great", 2 -> "hi",  3 -> "Guy", 4 -> "bad")  

Is there a way to do it in functional programming??

How to resolve the dateTime casting error in Marklogic import

Posted: 12 May 2022 05:20 AM PDT

I am getting this error while casting a value from a XML element into MarkLogic column using a template for the extraction of the data.

22/05/12 10:22:17 WARN mapreduce.ContentWriter: Batch 1009629724.0: TDE-INDEX: Error applying template /powerbi/shipment-CBE123.xml to document /powerbi/shipment/CBE00038464N/C:/Users/admin-rp/Documents/Marklogic/ML_With_PowerBI/bi-tools-master/bi-tools-master/power-bi/marklogic_powerbi_tutorial/data/CBE00038464N.xml: TDE-EVALFAILED: Eval for Column POD_ETA_Act_Arr='ns10:ASN/ns10:Schedule/ns5:TransportationUnitHeader/ns5:PrimarytUnit/ns5:TransportUnit/ns5:PortOfDischarge/ns9:ActualArrivalDate' returns XDMP-CAST: (err:FORG0001) Invalid cast: xs:untypedAtomic("") cast as xs:dateTime

The element value for the field ActualArrivalDate is like this in the XML file -

<ns5:PortOfDischarge>    <ns9:PortName />    <ns9:PortCode />    <ns9:ScheduledArrivalDate xsi:nil="true" />    <ns9:ActualArrivalDate xsi:nil="true" />    <ns9:ScheduledDepartureDate xsi:nil="true" />    <ns9:ActualDepartureDate xsi:nil="true" />  </ns5:PortOfDischarge>  

And my template form for this filed looks like this -

<column>    <name>POD_ETA_Act_Arr</name>    <scalar-type>dateTime</scalar-type><val>ns10:ASN/ns10:Schedule/ns5:TransportationUnitHeader/ns5:PrimarytUnit/ns5:TransportUnit/ns5:PortOfDischarge/ns9:ActualArrivalDate</val>    <nullable>true</nullable>  </column>  

Ordered bar plot with multiple groupings

Posted: 12 May 2022 05:20 AM PDT

Example data are here

I am struggling to create an ordered and grouped bar plot. Any assistance appreciated.

I have found two similar questions that essentially replicate what I am trying to produce but I cannot reproduce a similar plot myself. These questions are example 1 and example 2.

My code is as follows:

library(ggplot2); library(dplyr); library(tidyverse)    dput(n.bp.sp)  structure(list(Animal.group = c("Bird", "Bird", "Bird", "Bird",   "Bird", "Bird", "Bird", "Bird", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",   "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Reptile"  ), Family = c("Anatidae", "Columbidae", "Corvidae", "Corvidae",   "Icteridae", "Laridae", "Passeridae", "Psittacidae", "Aplodontiidae",   "Canidae", "Canidae", "Canidae", "Canidae", "Canidae", "Cricetidae",   "Cricetidae", "Cricetidae", "Cricetidae", "Cricetidae", "Cricetidae",   "Erinaceidae", "Felidae", "Geomyidae", "Geomyidae", "Geomyidae",   "Geomyidae", "Geomyidae", "Geomyidae", "Geomyidae", "Hystricdae",   "Leporidae", "Macropodidae", "Macropodidae", "Macropodidae",   "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae",   "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae",   "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae",   "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Mustelidae",   "Mustelidae", "Mustelidae", "Mustelidae", "Phalangeridae", "Procyonidae",   "Sciuridae", "Sciuridae", "Sciuridae", "Sciuridae", "Sciuridae",   "Sciuridae", "Sciuridae", "Spalacidae", "Suidae", "Urisidae",   "Colubridae"), Scientific.name = c("Branta canadensis", "Columba livia domestica",   "Coloeus monedula", "Corvus frugilegus", "Agelaius phoeniceus",   "Larus argentatus", "Passer domesticus", "Myiopsitta monachus",   "Aplodontia rufa", "Canis lupus", "Canis lupus dingo", "Canis lupus familiaris",   "Canis simensis", "Vulpes vulpes", "Lasiopodomys brandtii", "Microtus arvalis",   "Microtus californicus", "Microtus montanus", "Ondatra zibethicus",   "Peromyscus maniculatus", "Erinaceus europaeus", "Felis catus",   "Geomyidae spp.", "Geomys bursarius", "Thomomys bottae", "Thomomys mazma",   "Thomomys monticola", "Thomomys spp.", "Thomomys talpoides",   "Hystrix indica", "Oryctolagus cuniculus", "Macrcopus eugenii",   "Macropus rufogriseus", "Thylogale billardierii", "Bandicota bengalensis",   "Bandicota indica", "Gerbillurus paeba", "Golunda ellioti", "Meriones hurrianae",   "Millardia gleadowi", "Millardia meltada", "Mus booduga", "Mus musculus",   "Mus spp.", "Nesokia indica", "Rattus argentiventer", "Rattus exulans",   "Rattus losea", "Rattus nitidus", "Rattus norgevicus", "Rattus norvegicus",   "Rattus rattus", "Rattus spp.", "Rattus tiomanicus", "Tatera indica",   "Unspecified rodent spp.", "Unspecified rodent spp.", "Mustela erminea",   "Mustela furo", "Mustela nivalis", "Mustela spp.", "Trichosurus vulpecula",   "Procyon lotor", "Cynomys gunnisoni", "Cynomys leucurus", "Cynomys ludovicianus",   "Cynomys parvidens", "Funambulus tristriatus", "Otospermophilus beecheyi",   "Urocitellus beldingi", "Spalax ehrenbergi", "Sus scrofa", "Ursus americanus",   "Boiga irregularis"), Common.name = c("Canada goose", "Feral pigeon",   "Western jackdaw", "Rook", "Red-winged blackbird", "European herring gull",   "House sparrow", "Monk parakeet", "Mountain beaver", "Wolf",   "Dingo", "Dog", "Ethiopian wolf", "Red fox", "Brandt's vole",   "Common vole", "Califorian vole", "Montane vole", "Muskrat",   "Eastern deer mouse", "European hedgehog", "Cat", "Geomyidae spp.",   "Plains pocket gophers", "Botta's pocket gopher", "Mazama pocket gopher",   "Mountain pocket gopher", "Thomomys spp.", "Northern pocket gopher",   "Indian crested porcupine", "European rabbit", "Tammar wallaby",   "Red-necked wallaby", "Tasmanian pademelon", "Lesser bandicoot rat",   "Greater bandicoot rat", "Hairy-footed gerbil", "Indian bush rat",   "Indian desert gerbil", "Sand-colored soft-furred rat", "Soft-furred rat",   "Little indian field mouse", "House mouse", "Mus spp.", "Short-tailed bandicoot rat",   "Ricefield rat", "Polynesian rat", "Lesser ricefield rat", "Himalayan field rat",   "Brown rat", "Brown rat", "Black rat", "Rattus spp.", "Malayan field rat",   "Indian gerbil", "unspecified rodent spp.", "Unspecified rodent spp.",   "Stoat", "Ferret", "Weasel", "Mustela spp.", "Common brushtail possum",   "Raccoon", "Gunnison's prairie dog", "White-tailed prairie dog",   "Black-tailed prairie dog", "Utah prairie dog", "Jungle palm squirrel",   "California ground squirrel", "Belding's ground squirrel", "Middle east blind mole-rat",   "Feral pig", "American black bear ", "Brown treesnake"), n = c(1L,   49L, 4L, 65L, 1L, 4L, 5L, 2L, 1L, 12L, 42L, 33L, 3L, 305L, 2L,   4L, 1L, 1L, 1L, 3L, 1L, 144L, 3L, 3L, 15L, 2L, 15L, 8L, 37L,   10L, 88L, 1L, 20L, 1L, 193L, 5L, 3L, 23L, 12L, 3L, 86L, 37L,   237L, 64L, 79L, 16L, 16L, 4L, 23L, 6L, 90L, 273L, 58L, 17L, 81L,   1L, 35L, 81L, 23L, 17L, 1L, 253L, 2L, 37L, 36L, 40L, 36L, 1L,   16L, 2L, 3L, 41L, 5L, 76L)), row.names = c(NA, -74L), groups = structure(list(      Animal.group = c("Bird", "Bird", "Bird", "Bird", "Bird",       "Bird", "Bird", "Bird", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal",       "Reptile"), Family = c("Anatidae", "Columbidae", "Corvidae",       "Corvidae", "Icteridae", "Laridae", "Passeridae", "Psittacidae",       "Aplodontiidae", "Canidae", "Canidae", "Canidae", "Canidae",       "Canidae", "Cricetidae", "Cricetidae", "Cricetidae", "Cricetidae",       "Cricetidae", "Cricetidae", "Erinaceidae", "Felidae", "Geomyidae",       "Geomyidae", "Geomyidae", "Geomyidae", "Geomyidae", "Geomyidae",       "Geomyidae", "Hystricdae", "Leporidae", "Macropodidae", "Macropodidae",       "Macropodidae", "Muridae", "Muridae", "Muridae", "Muridae",       "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae",       "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae",       "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae",       "Mustelidae", "Mustelidae", "Mustelidae", "Mustelidae", "Phalangeridae",       "Procyonidae", "Sciuridae", "Sciuridae", "Sciuridae", "Sciuridae",       "Sciuridae", "Sciuridae", "Sciuridae", "Spalacidae", "Suidae",       "Urisidae", "Colubridae"), Scientific.name = c("Branta canadensis",       "Columba livia domestica", "Coloeus monedula", "Corvus frugilegus",       "Agelaius phoeniceus", "Larus argentatus", "Passer domesticus",       "Myiopsitta monachus", "Aplodontia rufa", "Canis lupus",       "Canis lupus dingo", "Canis lupus familiaris", "Canis simensis",       "Vulpes vulpes", "Lasiopodomys brandtii", "Microtus arvalis",       "Microtus californicus", "Microtus montanus", "Ondatra zibethicus",       "Peromyscus maniculatus", "Erinaceus europaeus", "Felis catus",       "Geomyidae spp.", "Geomys bursarius", "Thomomys bottae",       "Thomomys mazma", "Thomomys monticola", "Thomomys spp.",       "Thomomys talpoides", "Hystrix indica", "Oryctolagus cuniculus",       "Macrcopus eugenii", "Macropus rufogriseus", "Thylogale billardierii",       "Bandicota bengalensis", "Bandicota indica", "Gerbillurus paeba",       "Golunda ellioti", "Meriones hurrianae", "Millardia gleadowi",       "Millardia meltada", "Mus booduga", "Mus musculus", "Mus spp.",       "Nesokia indica", "Rattus argentiventer", "Rattus exulans",       "Rattus losea", "Rattus nitidus", "Rattus norgevicus", "Rattus norvegicus",       "Rattus rattus", "Rattus spp.", "Rattus tiomanicus", "Tatera indica",       "Unspecified rodent spp.", "Mustela erminea", "Mustela furo",       "Mustela nivalis", "Mustela spp.", "Trichosurus vulpecula",       "Procyon lotor", "Cynomys gunnisoni", "Cynomys leucurus",       "Cynomys ludovicianus", "Cynomys parvidens", "Funambulus tristriatus",       "Otospermophilus beecheyi", "Urocitellus beldingi", "Spalax ehrenbergi",       "Sus scrofa", "Ursus americanus", "Boiga irregularis"), .rows = structure(list(          1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,           14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L,           25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L,           36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L,           47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56:57, 58L,           59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L,           70L, 71L, 72L, 73L, 74L), ptype = integer(0), class = c("vctrs_list_of",       "vctrs_vctr", "list"))), row.names = c(NA, 73L), class = c("tbl_df",   "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",   "tbl_df", "tbl", "data.frame"))    n.bp.sp <- read.csv("test.csv", header = T)    n.bp.sp %>%    arrange(Animal.group, desc(n)) %>%    ggplot() +     aes(x = Family, y = n, fill = Animal.group) +    geom_bar(stat = "identity")+    scale_y_continuous(breaks = c(0, 250, 500, 750, 1000, 1250)) +    theme_classic()+    labs(x = "Family", y = "Number", fill = "Class") +    theme(axis.title.x = element_text(face = "bold"),          axis.title.y = element_text(face = "bold"),          axis.text.x = element_text(angle = 45, hjust = 1),          axis.text.y = element_text(),          legend.title = element_text(face = "bold"))  

This code produces this figure.

The correct figure should be grouped by Class and then otherwise the bars should be in descending order - essentially exactly the same as example 1 above.

i want to install laravel/horizon but it give error laravel v9

Posted: 12 May 2022 05:19 AM PDT

i write composer require laravel/horizon to composer but he give this error :

Your requirements could not be resolved to an installable set of packages.

Problem 1 - Root composer.json requires laravel/horizon ^0.1.0 -> satisfiable by laravel/horizon[v0.1.0]. - laravel/horizon v0.1.0 requires illuminate/contracts ~5.4 -> found illuminate/contracts[v5.4.0, ..., 5.8.x-dev] but these were not loaded, likely because it conflicts with another require.

You can also try re-running composer require with an explicit version constraint, e.g. "composer require laravel/horizon:*" to figure out if any version is installable, or "composer require laravel/horizon:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

my composer.json :

    "name": "laravel/laravel",      "type": "project",      "description": "The Laravel Framework.",      "keywords": ["framework", "laravel"],      "license": "MIT",      "require": {          "php": "^8.0.2",          "guzzlehttp/guzzle": "^7.2",          "laravel/framework": "^9.11",          "laravel/sanctum": "^2.14.1",          "laravel/tinker": "^2.7"      },      "require-dev": {          "fakerphp/faker": "^1.9.1",          "laravel/sail": "^1.0.1",          "mockery/mockery": "^1.4.4",          "nunomaduro/collision": "^6.1",          "phpunit/phpunit": "^9.5.10",          "spatie/laravel-ignition": "^1.0"      },      "autoload": {          "psr-4": {              "App\\": "app/",              "Database\\Factories\\": "database/factories/",              "Database\\Seeders\\": "database/seeders/"          }      },      "autoload-dev": {          "psr-4": {              "Tests\\": "tests/"          }      },      "scripts": {          "post-autoload-dump": [              "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",              "@php artisan package:discover --ansi"          ],          "post-update-cmd": [              "@php artisan vendor:publish --tag=laravel-assets --ansi --force"          ],          "post-root-package-install": [              "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""          ],          "post-create-project-cmd": [              "@php artisan key:generate --ansi"          ]      },      "extra": {          "laravel": {              "dont-discover": []          }      },      "config": {          "optimize-autoloader": true,          "preferred-install": "dist",          "sort-packages": true      },      "minimum-stability": "dev",      "prefer-stable": true  }  

How to: calculate percentile values for each values in R

Posted: 12 May 2022 05:19 AM PDT

I need to calculate percentile ranks for all the values in four columns in a dataset. The result should be something like this:

Name   Value1   Percentile1   Value2  Percentile2  Value3  Percentile3  Value4  Percentile4   a       X        0.000000               ....            ....            ....   b       X        0.159272               ....            ....            ....   c       X        1.000000               ....            ....            ....   d       X        0.240728               ....            ....            ....  ...  

The format of each percentile is 6-decimal. Could anyone please help with this? I tried ntile() but it can't give me 6 decimal numbers.

Input array value in function reactjs

Posted: 12 May 2022 05:19 AM PDT

I am trying to use "inputTime" in the if statement but i am not sure how to import it. I've tried "item.inputTime" and putting it in the "const check = (inputTime)" put i cant use it inside the check const. inputTime is an useState.

import React from 'react';  import nextId from "react-id-generator";    const Form = ({setInputText, inputText, setInputTime, inputTime, setInputDate, inputDate, todos, setTodos,  setStatus}) =>{                const check = () => {          var today = new Date();          var curTime = today.getHours()+':'+today.getMinutes();            todos.forEach(item => {              console.log(item.inputTime + curTime + inputTime);              if(item.inputTime > curTime){                  console.log("if");              } else{                  console.log("else");              }          });        }        return(          <form>              <input value={inputText} onChange={inputTextHandler} type="text" />                            <input value={inputTime} onChange={inputTimeHandler} type="time" />                  <button onClick={submitTodoHandler} type="submit">                  Lägg till              </button>                <button onClick={check(inputTime)} type="submit">                  Lägg till              </button>              <div>                  <select onChange={statusHandler}>                      <option value="all">All</option>                      <option value="completed">Completed</option>                      <option value="uncompleted">Uncompleted</option>                  </select>              </div>          </form>      );  };    export default Form;  

Using ExcelJS, how to read data from excel file using URL?

Posted: 12 May 2022 05:18 AM PDT

I have excel file upload in cloud. Using node js when front end pass URL i need to read data from excel file. Below is my code,

  var workbook = new ExcelJS.Workbook();     workbook.xlsx.load('https://s3.ap-southeast-1.amazonaws.com/staging-cgs3-storage.commonground.work/finance/invoices-usage/1652167540908/Book1.xlsx')      .then(function() {          var worksheet = workbook.getWorksheet(sheet);          worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {            console.log("Row " + rowNumber + " = " + JSON.stringify(row.values));          });      });  

But I'm getting this error,

Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html

Can anyone help me to fix this?

GoJS Diagram not loading at initial call

Posted: 12 May 2022 05:19 AM PDT

I have been trying to load a graph from a default selected value in a drop down list. This is the html for the select element.

            <select class="custom-select" id="activity">                  <option disabled value="">Select an activity</option>                  <option selected value="Running">Running</option>              </select>  

And then the javascript goes like this.

   function loop() {          setTimeout(function () {              load(activities.value);              loop();          }, 5000);      }            var activities = document.getElementById("activity");        load(activities.value);    

I tried this and the graph just dows not not load up. But then i tried this

   function loop() {          setTimeout(function () {              load(activities.value);              loop();          }, 5000);      }            var activities = document.getElementById("activity");      load(activities.value);      loop();  
function load(activity){      graph= {"class": "go.GraphLinksModel",                  "nodeDataArray": Iq2Lbqy660Nh_RP4z9jUhPZ1CZw,                  "linkDataArray": Iq2Lbqy660Nh_RP4z9jUhPZ1CZw                   }      myDiagram.model = go.Model.fromJson(graph);  }  

And the initial function call just before loop() does not load the graph. But after 5 seconds once the loop kicks in the graph loads up. And every 5 seconds it keeps loading up just like it should. I also tried adding a onchange event listener to the drop down with 2 more options and added.

    activities.addEventListener("change", () => {          load(activities.value);});  

and once i changed back and forth the graphs load up.

I also tried the myDiagram.requestUpdate(); right after the load(activities.value);.

Where an going wrong? What am i doing wrong?. Appreciate all advices and questions for any more clarification and ofcourse some answers if anyone can help.

Alternatives to Tensorflow Model Analysis (TFMA) for use with a PyTorch model

Posted: 12 May 2022 05:18 AM PDT

I have a PyTorch model, and I would like to be able to evaluate it on specific slices of input data as could be done with Tensorflow Model Analysis. Taking as example the Chicago taxi dataset, say that my model predicts the tip received.

What would be the best way for me to evaluate my model's performance for specific slices of data, such as accuracy per taxi company or per trip duration, like I would be able to do in TFMA with a Tensorflow model? (similar to how it is done in this tutorial)

I would like to know how, if at all possible, to use a PyTorch model in TFMA, and if it is not possible, what other methods exist to replicate the functionality mentioned above?

Any help or pointers would be greatly appreciated. :)

Showing #value! before enable editing on excel if I write formula using epplus

Posted: 12 May 2022 05:19 AM PDT

Using C# .net core I am updating existing excel template with Data and formulas using EPPlus lib 4.5.3.3. If you see the below screen shots all formula cells has '#value!' even after using Calculate method in C# code (Just for reference attached xml screen short just after downloading excel before opening it). Auto calculation is also enabled on excel.

in one of the blog mentioned to check the xml info,

My requirement is to upload this excel through code to sharepoint site and read the excel formula cells for other operations with out opening the excel manually.

is there any other way to calculate the formula cells form code and update the cell values?

I went through the Why won't this formula calculate unless i double click a cell? as well, but no luck.

enter image description here

enter image description here

using (ExcelPackage p = new ExcelPackage())              {                  MemoryStream stream = new MemoryStream(byteArray);                  p.Load(stream);                  ExcelWorksheet worksheet = p.Workbook.Worksheets.FirstOrDefault(a => a.Name == "InputTemplate");                  worksheet.Calculate();                  if (worksheet != null)                  {                      worksheet.Cells["A3"].Value = company.CompanyName;//// Company Name                      worksheet.Cells["B3"].Value = product.Name;////peoduct name                       worksheet.Cells["C3"].Value = product.NetWeight;                      worksheet.Cells["D3"].Value = product.ServingSize;                      worksheet.Cells["E3"].Value = 0;                        var produceAndIngredientDetailsForExcelList = await GetProduceAndIngredientDetails(companyId, productId);                        ////rowIndex will be 3                      WriteProduceAndIngredientDetailsInExcel(worksheet, produceAndIngredientDetailsForExcelList);                        ///rowIndex will update based on no. of produce and then Agregates.                      StageWiseAggregate(worksheet, produceAndIngredientDetailsForExcelList);                        ////Write Total Impacts Row                      TotalImpactsFormulaSection(worksheet);                        worksheet.Calculate();                  }                  Byte[] bin = p.GetAsByteArray();                  return bin;              }  

Formula Code

 var coloumnIndex = 22;///"V" Column            for (; coloumnIndex <= 27; coloumnIndex++)          {              var columnName = GetExcelColumnName(coloumnIndex);              worksheet.Cells[currentRowIndex, coloumnIndex].Formula = $"=SUBTOTAL(109,{columnName}{firstRowIndex}:{columnName}{currentRowIndex - 1})";          }  

R Shiny and Markdown - custom css font in pdf

Posted: 12 May 2022 05:19 AM PDT

I have used the gfonts package to download a css file which contains a custom font for use in my Shiny app. The app has a reporting function, that generates a RMarkdown PDF. Is there anyway to add this custom .css file that's in the www folder to set the font of the RMarkdown PDF? I am struggling to find a solution.

---  title: "Tool Report "  author: "Me"  date: "`r format(Sys.time(), '%d %B, %Y')`"  output: pdf_document    css: montserrat.css  params:     planName: NA    bYear: NA    whed: NA    imp: NA    red: NA    plotsummary: NA  fontsize: 10pt  header-includes:     - \usepackage[justification=raggedright,labelfont=bf,singlelinecheck=false]{caption}     - \let\Begin\begin     - \let\End\end  ---  

WooCommerce shop loop random array function not same values after each other

Posted: 12 May 2022 05:20 AM PDT

I'm using this array function to output random input values in the WooCommerce shop loop. I try now to have it like this, that the same input are not selected after each other.

Example: I have 4 different input values in the array. Now if [0] is randomly selected then for the second catch its not possible to select [0] again. Only [1], [2] and [4] would be possible. If [2] is selected for the second input then for the third select only the values [0], [1] and [3] should be selected.

In general: Not select the same array value for input after each other. But it should be possible that some inpute are selected more than once… but not after each other…

Is something somehow possible?

// Adding custom content block to shop loop row    add_action( 'woocommerce_shop_loop', 'add_custom_content_to_shop_loop_row' );  function add_custom_content_to_shop_loop_row() {        // Variables      global $wp_query;            // Custom array input options      $input = array("<img src='/wp-content/uploads/2022/01/banner-001.svg'>", "<img src='/wp-content/uploads/2022/01/banner-002.svg'>", "<img src='/wp-content/uploads/2022/01/banner-003.svg'>" );        // Column count      $columns = esc_attr( wc_get_loop_prop( 'columns' ) );            // Add content every X product      if ( (  $wp_query->current_post % 7 ) ==  0 && $wp_query->current_post !=  0 ) {                // output random array custom content          $rand_keys = array_rand($input, 1);            echo $input[$rand_keys] . "\n";      }    }  

I tried to use a method from here https://ofstack.com/PHP/37611/summary-of-5-methods-of-generating-non-repeating-random-numbers-in-php.html but it does not work at all.

Dynamic Input fields

Posted: 12 May 2022 05:19 AM PDT

I want to make input fields dynamic. According to the user-selected option in one dropdown, I have to change to another select option, and also user can add more input fields and delete them. I'm able to change according to users selection but now how I add more fields and delete it dynamically. --- script ----

<script>      $(document).ready(function() {        $("#standardone").change(function() {          $(this).find("option:selected").each(function() {            var optionValue = $(this).attr("value");            if (optionValue == "ss") {              $("#select1").show();              $("#select2").hide();              $("#select3").hide();              $("#select4").hide();              $("#select5").hide();              $("#medium1").show();              $("#board1").show();            }            if (optionValue == "C_1-4" || optionValue == "C_5-8" || optionValue == "C_9" || optionValue == "C_10" || optionValue == "C_9-10" || optionValue == "11-12_C") {              $("#select1").show();              $("#select2").hide();              $("#select3").hide();              $("#select4").hide();              $("#select5").hide();              $("#medium1").show();              $("#board1").show();            }            if (optionValue == "11-12_S") {              $("#select1").hide();              $("#select2").hide();              $("#select3").hide();              $("#select4").show();              $("#select5").hide();              $("#medium1").show();              $("#board1").show();            }            if (optionValue == "IIT-JEE") {              $("#select1").hide();              $("#select2").show();              $("#select3").hide();              $("#select4").hide();              $("#select5").hide();              $("#medium1").show();              $("#board1").show();            }            if (optionValue == "NEET") {              $("#select1").hide();              $("#select2").hide();              $("#select3").show();              $("#select4").hide();              $("#select5").hide();              $("#medium1").show();              $("#board1").show();            }            if (optionValue == "For_lang") {              $("#select1").hide();              $("#select2").hide();              $("#select3").hide();              $("#select4").hide();              $("#medium1").hide();              $("#board1").hide();              $("#select5").show();            }          });        }).change();          });   </script>  

---- body ----

<div class="col-sm-6 mb-3 ">                    <div class="form-group">                      <label for="name_of_business" class="font-weight-bold coac fw-bold">Standard</label>                      <br>                        <select name="std1" class="font-weight-bold" id="standardone">                        <option value="ss">Select Standard</option>                        <option value="C_1-4">Class 1-4</option>                        <option value="C_5-8">Class 5-8</option>                        <option value="C_9">Class 9</option>                        <option value="C_10">Class 10</option>                        <option value="11-12_C">11th-12th Commerce</option>                        <option value="11-12_S">11th-12th Science</option>                        <option value="IIT-JEE">IIT-JEE</option>                        <option value="NEET">NEET</option>                        <option value="For_lang">Foreign Langauges</option>                      </select>                    </div>                  </div>                    <div class="col-sm-6 mb-3">                    <div class="form-group">                      <label class="font-weight-bold fw-bold">Subjects</label>                      <br>                      <select name="sub11" class="font-weight-bold" id="select1">                        <option value="ss">Select Subject</option>                        <option value="all_sub">All Subjects</option>                      </select>                      <select name="sub12" class="font-weight-bold" id="select2">                        <option value="ss">Select Subject</option>                        <option value="all_sub">All Subjects</option>                        <option value="Physics">Physics</option>                        <option value="Chemistry">Chemistry</option>                        <option value="Maths">Maths</option>                      </select>                      <select name="sub13" class="font-weight-bold" id="select3">                        <option value="ss">Select Subject</option>                        <option value="all_sub">All Subjects</option>                        <option value="Physics">Physics</option>                        <option value="Chemistry">Chemistry</option>                        <option value="Biology">Biology</option>                      </select>                      <select name="sub14" class="font-weight-bold" id="select4">                        <option value="ss">Select Subject</option>                        <option value="all_sub">All Subjects</option>                        <option value="Physics">Physics</option>                        <option value="Chemistry">Chemistry</option>                        <option value="Maths">Maths</option>                        <option value="Biology">Biology</option>                      </select>                      <select name="sub15" class="font-weight-bold" id="select5">                        <option value="ss">Select Languge</option>                        <option value="Spoken_English">Spoken English</option>                        <option value="German">German</option>                        <option value="French">French</option>                        <option value="Spanish">Spanish</option>                      </select>                    </div>                  </div>  

In my WPF control, can I hide the validation control based on the size of the adorned element's row?

Posted: 12 May 2022 05:19 AM PDT

I have a user control with many sub controls within a grid. Since there are many controls per row, I'm controlling the visibility of the controls by setting the row height of their containing row to 0 (to hide them).

I'm using a validation template on some of these controls and displaying an icon next to the control using AdornedElementPlaceholder.

Since I'm not actually setting the visibility property of the adorned control, but instead hiding the row, the validation icon is not collapsed with the rest of the control.

Here's an abridged version of my XAML code:

<UserControl      <UserControl.Resources>      <ControlTemplate x:Key="ValidationTemplate" TargetType="Control">          <DockPanel>              <Grid                  Width="16"                  Height="16"                  Margin="10,0,0,0"                  VerticalAlignment="Center"                  DockPanel.Dock="Right">                  <Image Source="{x:Static icons:Icons.ValidationIcon}" ToolTip="{Binding Path=ErrorContent}" />              </Grid>              <AdornedElementPlaceholder />          </DockPanel>      </ControlTemplate>      </UserControl.Resources>      <Grid>          <Grid.RowDefinitions>              <RowDefinition Height="32"/>              <RowDefinition Height="{Binding Path=ScheduleType, Mode=OneWay, Converter={StaticResource ScheduleTypesToGridRowHeightConverter}, ConverterParameter={x:Static local:ScheduleTypes.Other}}"/>              <RowDefinition Height="{Binding Path=ScheduleType, Mode=OneWay, Converter={StaticResource ScheduleTypesToGridRowHeightConverter}, ConverterParameter={x:Static local:ScheduleTypes.Fixed}}"/>              <RowDefinition Height="{Binding Path=ScheduleType, Mode=OneWay, Converter={StaticResource ScheduleTypesToGridRowHeightConverter}, ConverterParameter={x:Static local:ScheduleTypes.Weekly}}"/>              <RowDefinition Height="{Binding Path=ScheduleType, Mode=OneWay, Converter={StaticResource ScheduleTypesToGridRowHeightConverter}, ConverterParameter={x:Static local:ScheduleTypes.FreeText}}"/>          </Grid.RowDefinitions>          <controls:DateInputBox              Grid.Column="2"              Grid.Row="5"              Height="28"              HorizontalAlignment="Left"              Watermark=""              Width="110"              Text="{Binding StartDateText, ValidatesOnDataErrors=True, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"              Validation.ErrorTemplate="{StaticResource ValidationTemplate}"              VerticalAlignment="Center"              ParseComplexDates="True"/>      </Grid>  </UserControl>  

From what I understand from a little research is that the validation icon is being displayed in the adorner layer, so doesn't collapse with the rest of the controls.

I'm now thinking that the "row height visibility pattern" was maybe not the best approach ;-) Is there a way I can get this to work without having to completely change my design? I do have a workaround using my view model but I'd like to explore other options first.

Using pypandoc on IIS server

Posted: 12 May 2022 05:19 AM PDT

After testing our Flask api on our local system, I have been unable to run the same app after deploying on IIS server. Basically it gives me 500 error whenever I use pypandoc, but when I remove it app works. You can consider the following simple snippet with pypandoc :

from flask import Flask    app = Flask(__name__)    import os    import pypandoc    #path= pypandoc.get_pandoc_path()    os.environ.setdefault('PYPANDOC_PANDOC','C:\\Pandoc\\pandoc.exe')      @app.route("/")    def home():    note =*** any html string ***     rtf_string = pypandoc.convert_text(note, 'rtf', format='html')    return rtf_string      if __name__ == "__main__":    app.run()    

Earlier I was getting the following error before setting 'PYPANDOC_PANDOC'

{"message": "Failed to Insert Data. No pandoc was found: either install pandoc and add it to your PATH or or call pypandoc.download_pandoc(...) or install pypandoc wheels with included pandoc.", "status": 0}

But I followed the following links and that error went away : Flask cannot find Pandoc on Linux Server (nginx+uwsgi)

Now I get the following error page : enter image description here

Poetry doesn't use the correct version of Python

Posted: 12 May 2022 05:19 AM PDT

I've recently installed both Pyenv and Poetry and want to create a new Python 3.8 project. I've set both the global and local versions of python to 3.8.1 using the appropriate Pyenv commands (pyenv global 3.8.1 for example). When I run pyenv version in my terminal the output is 3.8.1. as expected.

Now, the problem is that when I create a new python project with Poetry (poetry new my-project), the generated pyproject.toml file creates a project with python 2.7:

[tool.poetry]  name = "my-project"  version = "0.1.0"  description = ""  authors = ["user <user@email.com>"]    [tool.poetry.dependencies]  python = "^2.7"    [tool.poetry.dev-dependencies]  pytest = "^4.6"    [build-system]  requires = ["poetry>=0.12"]  build-backend = "poetry.masonry.api"  

It seems that Poetry defaults back to the system version of Python. How do I change this so that it uses the version installed with Pyenv?

Edit

I'm using MacOS, which comes bundled with Python 2.7. I think that might be causing some of the issues here. I've reinstalled Python 3.8 again with Pyenv, but when I hit Poetry install I get the following error:

The currently activated Python version 2.7.16 is not supported by the project (^3.8).  Trying to find and use a compatible version.    [NoCompatiblePythonVersionFound]  Poetry was unable to find a compatible version. If you have one, you can explicitly use it via the "env use" command.   

Should I create an environment explicitly for the project using Pyenv or should the project be able to access the correct Python version after running pyenv local 3.8.1.? When I do the latter, nothing changes and I still get the same errors.

Flutter: Get passed arguments from Navigator in Widget's state's initState

Posted: 12 May 2022 05:19 AM PDT

I have a StatefulWidget which I want to use in named route. I have to pass some arguments which I am doing as suggested in https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments i.e.

Navigator.pushNamed(        context,        routeName,        arguments: <args>,      );  

Now, I need to access these argument's in the state's initState method as the arguments are needed to subscribe to some external events. If I put the args = ModalRoute.of(context).settings.arguments; call in initState, I get a runtime exception.

20:49:44.129 4 info flutter.tools I/flutter ( 2680): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════  20:49:44.129 5 info flutter.tools I/flutter ( 2680): The following assertion was thrown building Builder:  20:49:44.129 6 info flutter.tools I/flutter ( 2680): inheritFromWidgetOfExactType(_ModalScopeStatus) or inheritFromElement() was called before  20:49:44.130 7 info flutter.tools I/flutter ( 2680): _CourseCohortScreenState.initState() completed.  20:49:44.130 8 info flutter.tools I/flutter ( 2680): When an inherited widget changes, for example if the value of Theme.of() changes, its dependent  20:49:44.131 9 info flutter.tools I/flutter ( 2680): widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor  20:49:44.131 10 info flutter.tools I/flutter ( 2680): or an initState() method, then the rebuilt dependent widget will not reflect the changes in the  20:49:44.131 11 info flutter.tools I/flutter ( 2680): inherited widget.  20:49:44.138 12 info flutter.tools I/flutter ( 2680): Typically references to inherited widgets should occur in widget build() methods. Alternatively,  20:49:44.138 13 info flutter.tools I/flutter ( 2680): initialization based on inherited widgets can be placed in the didChangeDependencies method, which  20:49:44.138 14 info flutter.tools I/flutter ( 2680): is called after initState and whenever the dependencies change thereafter.  20:49:44.138 15 info flutter.tools I/flutter ( 2680):   20:49:44.138 16 info flutter.tools I/flutter ( 2680): When the exception was thrown, this was the stack:  20:49:44.147 17 info flutter.tools I/flutter ( 2680): #0      StatefulElement.inheritFromElement.<anonymous closure> (package:flutter/src/widgets/framework.dart:3936:9)  20:49:44.147 18 info flutter.tools I/flutter ( 2680): #1      StatefulElement.inheritFromElement (package:flutter/src/widgets/framework.dart:3969:6)  20:49:44.147 19 info flutter.tools I/flutter ( 2680): #2      Element.inheritFromWidgetOfExactType (package:flutter/src/widgets/framework.dart:3285:14)  20:49:44.147 20 info flutter.tools I/flutter ( 2680): #3      ModalRoute.of (package:flutter/src/widgets/routes.dart:698:46)  20:49:44.147 21 info flutter.tools I/flutter ( 2680): #4      _CourseCohortScreenState.initState.<anonymous closure> (package:esk2/cohort_screen.dart:57:23)  

I do not want to put that logic in build method as build could be called multiple times and the initialization needs to happen only once. I could put the entire logic in a block with a boolean isInitialized flag, but that does not seem like the right way of doing this. Is this requirement/case not supported in flutter as of now?

No comments:

Post a Comment