Sunday, September 5, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to print spades, hearts, diamonds, etc. in python

Posted: 05 Sep 2021 08:59 AM PDT

try to print heart sign using unit code: print("\U0002660") this sign should be an heart sign but don't work

Connection is locked when using remotessh

Posted: 05 Sep 2021 08:59 AM PDT

I used vscode remote to connect to server but met error like this " Acquiring lock on /home-4/yzhao140@jhu.edu/.vscode-server/bin/3c4e3df9e89829dce27b7b5c24508306b151f30d/vscode-remote-lock.yzhao140@jhu.edu.3c4e3df9e89829dce27b7b5c24508306b151f30d " I tried to delete .vscode-server in the server and reconnect, but it didn't work.

changing and setting encapsulated parameters from outside in python

Posted: 05 Sep 2021 08:59 AM PDT

I'm currently working on a project that has to send some signal to the instrument (one current and frequency by 1 iteration) and to recieve the response. Then all this data go to the data frame and we analyse it. I decide to encapsulate and make a pypi package from my code. So my code looks like this:

from drivers.N5183B import *  from drivers.M9290A import *  from drivers.znb_besedin import *    import zhinst, zhinst.ziPython    from resonator_tools.circuit import notch_port  from resonator_tools import circlefit    class TwoToneSpectroscopy:        def __init__(self, *, x_min, x_max, x_step, y_min, y_max, y_step, fr_min, fr_max):          """          Class provides methods for working with live data for Two Tone Spectroscopy          :param x_min: current minimum value (int | float)          :param x_max: current maximum value (int | float)          :param x_step: current step value (int)          :param y_min: frequency minimum value (int | float)          :param y_max: frequency maximum value (int | float)          :param y_step: frequency step value (int)          """          self.x_min = x_min          self.x_max = x_max          self.x_step = x_step          self.y_min = y_min          self.y_max = y_max          self.y_step = y_step            self.fr_min = fr_min          self.fr_max = fr_max            self.x_list = np.arange(self.x_min, self.x_max,                                  self.x_step)          self.y_list = np.arange(self.y_min, self.y_max,                                  self.y_step)            self.__x_ind = 0          self.__y_ind = 0            self.__x_raw = []          self.__y_raw = []          self.__heat_raw = []              # HERE I CONNECT INSTRUMENTS AND SET SOME PARAMETERS              self.hdawg = zhinst.ziPython.ziDAQServer('127.0.0.1', 8004, 6)          self.hdawgModule = self.hdawg.awgModule()                self.hdawg.setInt('/dev8307/sigouts/1/on',1)                     self.LO = N5183B('N5183B', 'TCPIP0::192.168.180.143::hislip0::INSTR')          self.LO_resp = Znb('TCPIP0::192.168.180.134::inst0::INSTR')            self.LO1 = Znb('TCPIP0::192.168.180.134::inst0::INSTR')          self.LO1.set_nop(1)          self.LO1.set_bandwidth(20)          self.LO1.set_power(-20)          self.LO1.set_averages(1)          self.LO1.autoscale_all()        def get_response(self, *, x_key: Iterable = None, y_key: Iterable = None, sleep: float = 0.005):          """          generator for pandas object          :param x_key: (optional) array like object          :param y_key: (optional) array like object          :param sleep: time sleep parameter (Sec). Default = 0.005.          :return: None          """            currents = np.array(x_key) if x_key is not None else self.x_list          freqs = np.array(y_key) if y_key is not None else self.y_list            try:                while self.__x_ind != len(currents):                      # HERE I WRITE CURRENT AND FREQUENCY TO THE INSTRUMENT AND APPEND DATAFRAME                      self.hdawg.setDouble('/dev8307/sigouts/1/offset',currents[i])  # Current write                                    self.LO.set_frequency(freqs[i])  # Frequency write                    self.__x_raw.append(float(currents[i]))  # Current read                  self.__y_raw.append(float(freqs[i]))  # Frequency read                      self.LO1.set_center(float(self.__find_resonator(self.fr_min, self.fr_max)))                                    result = self.LO1.measure()['S-parameter']                  self.__heat_raw.append(20*np.log10(abs(result)[0]))  # Response read                    if self.__y_ind + 1 == len(freqs):                      self.__x_ind += 1  # go to the next current                      self.__y_ind = 0  # go to the next round of frequencies                    else:                      self.__y_ind += 1                    time.sleep(sleep)            except KeyboardInterrupt:                pass        @property      def raw_frame(self):          return pd.DataFrame({'x_value': self.__x_raw, 'y_value': self.__y_raw, 'heat_value': self.__heat_raw})         def __find_resonator(self, fr_min, fr_max):           lo1_status = self.LO.get_status()          self.LO.set_status(0)            # prior bandwidth          bandwidth = self.LO_resp.get_bandwidth()          self.LO1.set_bandwidth(20)          nop = self.LO1.get_nop()          xlim = self.LO1.get_freq_limits()            self.LO1.set_nop(101)          self.LO1.set_freq_limits(fr_min, fr_max)          #print(fr_max)                    freqs = self.LO1.get_freqpoints()          S21s = self.LO1.measure()['S-parameter']                      # measure S21          notch = notch_port(freqs, S21s)          notch.autofit(electric_delay=50e-9)          result = notch.fitresults['fr']                             self.LO.set_status(lo1_status)          self.LO1.set_bandwidth(bandwidth)          #pna.set_average(average)          self.LO1.set_nop(nop)          self.LO1.set_freq_limits(*xlim)            return result  

So I only have to set init parameters in clean jupyter notebook and start getting response

"""Frequency"""  y_min = 4e9  y_max = 5e9  y_step = 2.5e6    """Currents"""  x_min = -1  x_max = 1  x_step = 0.08    data = TwoToneSpectroscopy(x_min=x_min, x_max=x_max,x_step=x_step,                             y_min=y_min, y_max=y_max, y_step=y_step,                             fr_min = 6.2785e9, fr_max = 6.2825e9)    data.get_response(sleep=0.3)  

But the bad thing about it is that I can't change any instrument's parameters, or connect to another port or simply to change drivers library (drivers can be drivers.N5183B or drivers.N5186B, etc).
So I want to make all the settings of instruments and __find_resonator(self, fr_min, fr_max) function to be out of my class (package). I am faced with such problem for the first time, so I don't exactly know what to do. My Idea was somethig like that:
Maybe I should add connect function to my TwoToneSpectroscopy class that would trigger all the settings inside my class. for example:

# import all the stuff    def find_resonator(fr_min, fr_max):           lo1_status = LO.get_status()          LO.set_status(0)            # prior bandwidth          bandwidth = LO_resp.get_bandwidth()          LO1.set_bandwidth(20)          nop = LO1.get_nop()          xlim = LO1.get_freq_limits()            LO1.set_nop(101)          LO1.set_freq_limits(fr_min, fr_max)          #print(fr_max)            freqs = LO1.get_freqpoints()          S21s = LO1.measure()['S-parameter']              # measure S21          notch = notch_port(freqs, S21s)          notch.autofit(electric_delay=50e-9)          result = notch.fitresults['fr']              LO.set_status(lo1_status)          LO1.set_bandwidth(bandwidth)          #pna.set_average(average)          LO1.set_nop(nop)          LO1.set_freq_limits(*xlim)            return result    def connet_this("maybe something here"):                # Maybe import all instrument's libraries here one more time            hdawg = zhinst.ziPython.ziDAQServer('127.0.0.1', 8004, 6)          hdawgModule = self.hdawg.awgModule()                hdawg.setInt('/dev8307/sigouts/1/on',1)             LO = N5183B('N5183B', 'TCPIP0::192.168.180.143::hislip0::INSTR')          LO_resp = Znb('TCPIP0::192.168.180.134::inst0::INSTR')            LO1 = Znb('TCPIP0::192.168.180.134::inst0::INSTR')          LO1.set_nop(1)          LO1.set_bandwidth(20)          LO1.set_power(-20)          LO1.set_averages(1)          LO1.autoscale_all()                  find_res_func = find_resonator(fr_min = 6.2785e9, fr_max = 6.2825e9)    # Then we create instance of our class  """Frequency"""  y_min = 4e9  y_max = 5e9  y_step = 2.5e6    """Currents"""  x_min = -1  x_max = 1  x_step = 0.08    data = TwoToneSpectroscopy(x_min=x_min, x_max=x_max,x_step=x_step,                             y_min=y_min, y_max=y_max, y_step=y_step,                             fr_min = 6.2785e9, fr_max = 6.2825e9)    # make a connection  data.connect(connect_this())    #and get response  data.get_response(sleep=0.3)            

But there would be still problem inside data.get_response, so I don't know how to solve it, maybe I should pass functions directly into get_response?

data.get_response(current_write_func = hdawg.setDouble,                    current_params = dict('param1': '/dev8307/sigouts/1/offset'),                    frequency_write_func = LO.set_frequency,                    set_center = LO1.set_center,                    #...)    

I would be very happy to get some feedback about this, because I don't want to paste all TwoToneSpectroscopy class inside jupyter notebook every time. It would be very messy. This class contains not only get_response function, there are way more additional and helpful functions there

Conditional update either column1 or column2 or column3

Posted: 05 Sep 2021 08:58 AM PDT

I want to write a sql update statement like

UPDATE p  SET CASE WHEN inv.name='your' THEN p.your_qty=inv.qty      CASE WHEN inv.name='other' THEN p.other_qty=inv.qty      CASE WHEN inv.name='my' THEN p.my_qty=inv.qty  FROM products p  JOIN Qty_products_inv inv  ON p.itemNo= inv.itemNo  

How to put insert Flatlist as item in another Flatlist?

Posted: 05 Sep 2021 08:58 AM PDT

i am new in React Native and this is my first time asking question in stackoverflow. im sorry if the way i'm asking question is in wrong format. What i'm trying to do is that i can add item 'User' in the flatlist by using Modal and in each User , i can add new items with another modal. My target output would be:

User 1

  • eat
  • drink -.......

User 2

  • code
  • eat
  • ......

My output right now only shows User while the items for each User is invisible Your help and support are much appreciated

This are my code:

  const [isModalVisible_Users, setIsModalVisible_Users] = useState(false);    const [isModalVisible_Attributes, setIsModalVisible_Attributes] = useState(false);      const [usersInput, setUsersInput] = useState('');    const [attributesInput, setAttributesInput] = useState('');      const [users, setUsers] = useState([]);    const [attributes, setAttributes] = useState([]);      useEffect(() => {      getUsersFromDevice();    }, []);    useEffect(() => {      saveUsersToDevice(users,attributes);    }, [users,attributes]);      const ListUsers = ({users}) => {      return <View style={styles.listItem}>        <View style={{flex :1}}>          <Text style={[styles.userText]}>          {users?.userName}          </Text>        </View>        <TouchableOpacity style={[styles.addAttributes]} onPress={() => changeModalVisibility_Attributes(true)}>          <Icon name="add" size={15} color={'#fff'}/>        </TouchableOpacity>        <Modal            transparent={true}            animationType="fade"            visible={isModalVisible_Attributes}            onRequestClose={() => changeModalVisibility_Attributes(false)}          >                <AddAttributesModal                changeModalVisibility={changeModalVisibility_Attributes}                />        </Modal>        <FlatList        showsVerticalScrollIndicator={false}        contentContainerStyle={{ padding: 20 , paddingBottom: 100}}        data={attributes}        renderItem={({ item }) => <ListGrade attributes={item}/>}        />      </View>;    };      const ListGrade = ({attributes}) => {      return <View style={styles.listItem}>        <View style={{flex :1}}>          <Text style={[styles.attributeText]}>          {attributes?.attributesName}          </Text>        </View>      </View>;    };      const AddUsersModal = () => {      return <SafeAreaView style={styles.modal}>      <View style={styles.modalWrapper}>        <View style={styles.modalTitleWrapper}>          <Text style={styles.modalTitle}>Add User</Text>        </View>        <View style={styles.typeMsgContainer}>          <TextInput            editable={true}            style={styles.typeMsgBox}            placeholder={'Add User...'}            value={usersInput}            onChangeText={(text) => setUsersInput(text)}          />            <TouchableOpacity style={styles.sendBtn} onPress={addUsers}>            <View >              <Icon name="add" size={30} color="white"/>            </View>          </TouchableOpacity>        </View>    </View>    </SafeAreaView>;    };      const addUsers = () => {      if (usersInput === ''){        Alert.alert('Error', 'Please input todo');      } else {        const newUser = {          id: Math.random(),          userName: usersInput,        };        setUsers([...users,newUser]);        setUsersInput('');        changeModalVisibility_Users(false);      }    };      const AddAttributesModal = () => {      return <SafeAreaView style={styles.modal}>      <View style={styles.modalWrapper}>        <View style={styles.modalTitleWrapper}>          <Text style={styles.modalTitle}>Add Attributes</Text>        </View>        <View style={styles.typeMsgContainer}>          <TextInput            editable={true}            style={styles.typeMsgBox}            placeholder={'Add Attributes...'}            value={attributesInput}            onChangeText={(text) => setAttributesInput(text)}          />            <TouchableOpacity style={styles.sendBtn} onPress={addAttributes}>            <View >              <Icon name="add" size={30} color="white"/>            </View>          </TouchableOpacity>        </View>    </View>    </SafeAreaView>;    };      const addAttributes = () => {      if (attributesInput === ''){        Alert.alert('Error', 'Please input grade');      } else {        const newAttribute = {          id: Math.random(),          attributesName: attributesInput,        };        setGrades([...attributes,newAttribute]);        setGradeInput('');        changeModalVisibility_Attributes(false);      }    };      return (      <SafeAreaView style={{flex:1}}>        <LinearGradient                      colors={['#00BFFF', '#87CEFA', '#87CEEB' , '#ADD8E6']}                      style={{flex:1}}        >        <View style={styles.subjectWrapper}>          <View style={styles.taskTitle}>            <Text style={styles.sectionTitle}>Subjects</Text>            <TouchableOpacity onPress={() => changeModalVisibility_Users(true)} style={styles.ClearButton}>              <Icon name="add" size={25} color="#0066ff"  />            </TouchableOpacity>            <Modal                  transparent={true}                  animationType="fade"                  visible={isModalVisible_Users}                  onRequestClose={() => changeModalVisibility_Users(false)}              >                <AddUserModal                changeModalVisibility={changeModalVisibility_Users}                />            </Modal>          </View>          <FlatList            showsVerticalScrollIndicator={false}            contentContainerStyle={{ padding: 20 , paddingBottom: 100}}            data={users}            renderItem={({ item }) => <ListSubject user={item}/>}          />        </View>        </LinearGradient>      </SafeAreaView>    );  

Pandas regex: replace commas between parentheses in a DataFrame

Posted: 05 Sep 2021 08:58 AM PDT

I have this sample of data:

University,Center (first, second, third),Dept#1,ID=234,  

What I want is:

University,Center (first@ second@ third),Dept#1,ID=234,  

I tried many different methods but I could not find any questions or videos about parentheses.

Thanks

Window events get caught by WndProc but not in the app loop

Posted: 05 Sep 2021 08:58 AM PDT

I have the following test application :

fn init(wnd: &mut WINDOW, state: &mut Serializable) {      println!("hewwo, im {}",wnd.get_window_name());      println!("Im cwassy, i have {}",wnd.get_class_name());  }    fn make_on_events() -> HashMap<UINT, Box<WINDOW_CB>> {      let mut map: HashMap<UINT, Box<WINDOW_CB>> = HashMap::new();      map.insert(WM_SIZING,                 Box::new(                     |wnd: &mut WINDOW, state: &mut Serializable| {                         println!("im weesizing!");                         unsafe { GetClientRect(wnd.get_hwnd(), LPRECT::from(wnd.expose_client_rect_mut())) };                     }                 )      );        map  }      fn main() {      WINDOW::new("winduw", "cwass")          .do_loop(init,  make_on_events());    }    

where WINDOW is the defined as

pub struct WINDOW {      hwnd: HWND,      atom: ATOM,        class_name: WideString,      window_name: WideString,        background_brush: HBRUSH,        client_rect: RECT,    }  ```.    When I create window I fill my WindowClassExW like so:     ```rust  let window_class = WndClassExW {              cbSize: size_of::<WndClassExW>() as u32,              style: CS_OWNDC | CS_HREDRAW | CS_VREDRAW,              lpfnWndProc: Some(mWndProc),              cbClsExtra: 0,              cbWndExtra: 0,              hInstance: hinstance,              hIcon: null_mut(),              hCursor: null_mut(),              hbrBackground: background_brush,              lpszMenuName: null_mut(),              lpszClassName: class_name.ptr(),              hIconSm:null_mut()          };  

and among other things I specify the mWndProc which is defined below:

  pub unsafe extern "system" fn mWndProc(hWnd: HWND, message: UINT, wParam: WPARAM, lParam: LPARAM) -> LRESULT {        match message {          WM_DESTROY => {              unsafe { PostQuitMessage(0) };              exit(0);          },          WM_SIZING => {              unsafe {PostMessageW(null_mut(), WAS_RESIZED, 0, 0)};              0          },          WM_CLOSE => {              unsafe {assert!(DestroyWindow(hWnd).is_true())};              exit(0);          }          _ => {              DefWindowProcW(hWnd, message, wParam, lParam)          }      }  }  

. The WINDOW I created then enters its inner loop defined here:

pub fn do_loop(&mut self, on_init: WINDOW_CB, on_event: HashMap<UINT, Box<WINDOW_CB>>) {            let mut state: Serializable = Serializable::new();            unsafe { ShowWindow(self.hwnd, SW_SHOW) };            on_init(self, &mut state);            let mut msg: MSG = unsafe {zeroed()};            'main: loop {                while unsafe {                  PeekMessageW(LPMSG::from(&mut msg),                               self.hwnd,                               0,                               0,                               PM_REMOVE)              }.is_true() {                      match msg.message {                      msg => {                          if on_event.contains_key(&msg) {                              on_event.get(&msg).unwrap().as_ref()(self, &mut state);                          }                      },                  }                    unsafe {TranslateMessage(LPMSG::from(&msg)).is_true()};                  unsafe {DispatchMessageW(LPMSG::from(&msg))};                }          }      }  

The issue is that events like WM_SIZING are not detected in the do_loop but are detected in mWndProc. As far as I know WndProc is called whenever DispatchMessage is called. This happens later in the loop - but still the match arm doesn't pick up any events.

So The following questions are - why, and is there a way I can ensure events live after WndProc and until they are manually retrieved via PeekMessageW was called?

deprecation warning in xgboost

Posted: 05 Sep 2021 08:57 AM PDT

UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release.

I want to suppress the warnings.

I see this answer use_label_encoder =False but is doesn't work for me.

I searched everywhere but nothing seemed to work.

Thanks in advance

How to fix "f = lambda x: f(x)+1" in a functional programming language?

Posted: 05 Sep 2021 08:57 AM PDT

Consider the following code in python:

f = lambda x: x

f = lambda x: f(x)+1

f(1)

Python throws an "infinite loop" error while running the last line, which is clear in the way that it interprets the second line as a recursive formula for f.

But the second line seems resonable if one substitutes the 'value' of f in the right side, and then assigns the resulting function to f (in the left).

Does there exists a straightforward way for fixing this error in python (or another language which can work with functions) via lambda calculus operations?

I asked this question just for curiosity to know much more about functional languages, but it seems to me that the answer helps to produce loop calculations on functions!

How to react to route changes on Vue 3, "script setup" composition API?

Posted: 05 Sep 2021 08:57 AM PDT

This is an example of routes I have in my application:

{    path: "/something",    name: "SomeRoute",    component: SomeComponent,    meta: {showExtra: true},  },  {    path: "/somethingElse",    name: "SomeOtherRoute",    component: SomeOtherComponent,  },  

Then I have the following component, which as you will notice has two script tags, one with composition API, one without:

<template>    <div>      This will always be visible. Also here's a number: {{ number }}    </div>      <div v-if="showExtra">      This will be hidden in some routes.    </div>  </template>    <script setup lang="ts">  import type { RouteLocationNormalized } from "vue-router"  import { ref } from "vue"    const number = 5  const showExtra = ref(true)    const onRouteChange = (to: RouteLocationNormalized) => {    showExtra.value = !!to.meta?.showExtra  }  </script>    <script lang="ts">  import { defineComponent } from "vue"      export default defineComponent({    watch: {      $route: {        handler: "onRouteChange",        flush: "pre",        immediate: true,        deep: true,      },    },  })  </script>  

This works correctly: when I enter a route with meta: {showExtra: false} it hides the extra div, otherwise it shows it.

What I want to do, however, is achieve the same by only using the composition API, in other words removing the second <script> tag entirely. I have tried this:

<script setup lang="ts">  import type { RouteLocationNormalized } from "vue-router"  import { ref } from "vue"  import { onBeforeRouteUpdate } from "vue-router"      // ...  // same as before  // ...    onBeforeRouteUpdate(onRouteChange)  </script>  

But this won't take effect as expected when I switch route. I'm aware of the watch function I could import, but I'm unsure how to get the meta information about the route and how to appease the type checker.

Add items to a newly created array in C#

Posted: 05 Sep 2021 08:59 AM PDT

Problem

I am in Unity trying to create an empty array of GameObjects at a certain length and then add a GameObject into it by calling an index of the array. Here is an example of what I try to achieve:

GameObject[] testArray = new GameObject[4];  testArray[0] = previouslyDefinedGameobject;  

This causes my program to throw me the "IndexOutOfRangeException: Index was outside the bounds of the array" error.

What I tried

I tried this with the same result:

GameObject[] testArray = new GameObject[4]{null, null, null, null};  testArray[0] = previouslyDefinedGameobject;  

I find this a bit odd since I can do this:

int[] intArray = new int[5];  intArray[0] = 3;  

What Works

If I later in the code add a new array of GameObjects at null then it will work somehow:

GameObject[] testArray = new GameObject[4];  testArray = new GameObject[4]{null, null, null, null};  testArray[0] = previouslyDefinedGameobject;  

What I want

Is there really no better way than what works? I find this incredible tedious and makes my code super ugly and long.

!! EDIT !! Here is the real exact code:

[HideInInspector] public GameObject[] toolFrameObjects = new GameObject[4];    void OnEnable()  {      toolFrameObjects[0] = null;          }  

I can't position a div in CSS without it messing up the animation

Posted: 05 Sep 2021 08:57 AM PDT

I tried making a rotating square that would turn into an oval while rotating 180 degrees, the issue I encountered is that as the square rotates it moves to the left so that the top-left corner always stays in the same. Visualization of the problem. I think it's caused by the fact that my animation changes the width of the square:

`@keyframes squarestuff {    50% {      transform: rotate(180deg);      width: 5rem;      border-radius: 50%;    }`  

Jetpack Compose: Performance problem when element with GlideImage is clickable in LazyColumn

Posted: 05 Sep 2021 08:59 AM PDT

I have VideoListScreen with LazyColumn and as my item I use VideoItem. This LazyColumn it's created with grid items to have lazy grid view with Category header. Tag is tag of category. Category details is information about category colors, title etc.:

@Composable  fun VideoItem(      videoPath: String,      brush: Brush,      modifier: Modifier = Modifier,      onClick: () -> Unit  ) {      val assetFileDescriptor = LocalContext.current.assets.open(videoPath)      Surface(          modifier = modifier              .padding(5.dp)              .aspectRatio(1f)              .clickable { onClick() },          shape = Shapes.small,          elevation = 1.dp      ) {          GlideImage(              imageModel = assetFileDescriptor.readBytes(),              contentScale = ContentScale.Crop,              requestOptions = RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE),              shimmerParams = ShimmerParams(                  baseColor = MaterialTheme.colors.background,                  highlightColor = Blue200,                  durationMillis = 650,                  dropOff = 0.65f,                  tilt = 20f              )          )          Box(modifier = Modifier              .background(brush)              .fillMaxSize() )      }  }  

VideoListScreen:

@Composable  fun VideoListScreen(      navController: NavHostController,      tag: String  ) {      val cells = 2      val context = LocalContext.current      val categoryDetails = getCategoryDetailsBy(tag)      val videos = fetchVideos(context, tag)      LazyColumn(contentPadding = PaddingValues(5.dp)) {          item {              CategoryElement(                  categoryDetails = categoryDetails,                  modifier = Modifier                      .fillMaxWidth()                      .height(130.dp)                      .padding(5.dp),                  customTitle = "O kategorii"              )          }          gridItems(videos, cells) { assetFileName ->              val videoPath = "$tag/$assetFileName"              VideoItem(                  videoPath = videoPath,                  brush = categoryDetails.transparentBrush              ) { navController.navigateToPlayer(videoPath) } //onClick function          }      }  }    private fun fetchVideos(context: Context, tag: String): List<String> {      return context.resources.assets.list("$tag/")?.toList() ?: listOf()  }  

gridItems extension function:

    fun <T> LazyListScope.gridItems(      data: List<T>,      cells: Int,      itemContent: @Composable BoxScope.(T) -> Unit,  ) {      items(data.chunked(cells)) { row ->          Row(Modifier.fillMaxWidth()) {              for ((index, item) in row.withIndex()) {                  Box(Modifier.fillMaxWidth(1f / (cells - index))) {                      itemContent.invoke(this, item)                  }              }          }      }  }  

The problem is that when I try to apply clickability on this item (no matter where) the thumbnail loading (from the assets) becomes almost twice as slow. What's interesting when onClick function is empty, performance issue disappearing. In function called "navigateToPlayer(videoPath)" I navigate to another screen and send "videoPath" with navController.

If you have any questions, feel free to ask!

Duplicating rows in pandas Python

Posted: 05 Sep 2021 08:57 AM PDT

i hope you are doing good . I have the following output :

ClassName   Bugs   HighBugs  LowBugs  NormalBugs     Class1      4        0        1         3   Class2      0        0        0         0   Class3      3        0        1         2   Class4      0        0        0         0   Class5      6        2        2         2    

The result i want is as follow :

ClassName   Bugs   HighBugs  LowBugs  NormalBugs     Class1      1        0        0         1   Class1      1        0        0         1   Class1      1        0        0         1   Class1      1        0        1         0   Class2      0        0        0         0   Class3      1        0        0         1   Class3      1        0        0         1   Class3      1        0        1         0   Class4      0        0        0         0   Class5      1        0        0         1   Class5      1        0        0         1   Class5      1        0        1         0   Class5      1        0        1         0   Class5      1        1        0         0   Class5      1        1        0         0    

Little explanation , what i want is to duplicate the classes depending on the column Bugs and Bugs = HighBugs + LowBugs + NormalBugs , as you can see in the result i want is that when the classes are duplicated we have only one's and zero's depending on the number of Bugs.

Thank you in advance and have a good day you all .

What ergonomic keyboard are you using?

Posted: 05 Sep 2021 08:57 AM PDT

I am thinking about buying an ergonomic keyboard.

Can you suggest to me some best ergonomic keyboards?

What ergonomic keyboard are you using?

Should I buy ortholinear or staggered keyboard?

Why am I asking this on StackOverflow: I think there are many professional programmers who already have an ergonomic keyboard and can write their own experiences.

Thank you.

Send raw frames with C++

Posted: 05 Sep 2021 08:57 AM PDT

I am wanting to send raw ethernet frames with C++ for networking testing, I've looked at a few methods but some have some truly terrible examples. So I thought I would just ask what the best method would be, I don't need to drop frames, so no need for kernel mode (although a kernel mode solution would be useful as well). Doesn't need to be Windows, but it would make it easier.

How to get two text inputs to show in one message with OnClickListener in Android Kotlin?

Posted: 05 Sep 2021 08:59 AM PDT

I have two text input fields and a button. I managed to implement that, when both textfields are filled and I click the button, a message showing the input from the first text field is showing.

What I would like to do is to implement that when both textfields are filled and I click the button, a message showing the input from the both text fields (in one message) is showing.

Could anyone help me to do that?/ Has anyone done something similar? Thank you in advance!

class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {      super.onCreate(savedInstanceState)      setContentView(R.layout.activity_main)              val autotextView              = findViewById<AutoCompleteTextView>(R.id.autoTextViewStart)      val autotextViewZiel              = findViewById<AutoCompleteTextView>(R.id.autoTextViewZiel)          // Get the array of languages      val languages              = resources.getStringArray(R.array.Languages)      // Create adapter and add in AutoCompleteTextView      val adapter              = ArrayAdapter(this,          android.R.layout.simple_list_item_1, languages)      autotextView.setAdapter(adapter)      autotextViewZiel.setAdapter(adapter)          val button              = findViewById<Button>(R.id.btn); if (button != null)      {          button.setOnClickListener(View.OnClickListener {              val enteredText = autotextView.getText()              Toast.makeText(this@MainActivity, enteredText, Toast.LENGTH_SHORT).show()          })      }  

How to run this command in a shell?

Posted: 05 Sep 2021 08:58 AM PDT

For a lot of my node scripts I need to inject environment variables from a node.js script. The resulting bash command always ends up looking like this:

yarn workspace @nl/server dotenv -e .env.development prisma --preview-feature db seed  

The problem here is that the --preview-feature flag will not be used for the prisma command that it was intended for. I've tried:

yarn workspace @nl/server dotenv -e .env.development -- prisma --preview-feature db seed  

But it did not help. I'd love to know how I can run commands like the one above while applying the correct arguments.

How to wait until a WeakHashMap has updated?

Posted: 05 Sep 2021 08:58 AM PDT

Is there another way besides a fixed timeout to know when a WeakHashMap has updated its entries after a key becomes weakly reachable?

For example this code which nulls the strong reference to the key still prints that the entry is in the map unless a timeout is added.

    WeakHashMap<Integer, Integer> map = new WeakHashMap<>();      Integer i = 1000;      map.put(i, 1);      System.out.println(map.size()); // prints 1      i = null;      System.gc();      //Thread.sleep(0);      System.out.println(map.size()); // without sleep prints 1, with sleep prints 0  

Is there a more elegant way to know when the WeakReferences have finished updating?

Run exe from Send To context menu

Posted: 05 Sep 2021 08:57 AM PDT

I would like to run this exe on any image that is selected. (https://github.com/roothaxor/Exif-Remove).

Using Send To menu directly, bat file in Send Menu, or any method...

The exe can be used like this:

  • Copy exif.exe to C:\Windows\ -- or to any folder that you have picture in
  • Go to the directory where you have your pictures
  • Hold SHIFT KEY and click RIGHT CLICK
  • Select "Open command window here"
  • Write exif and press ENTER KEY
  • It'll regenerate the image files without exif data and save them, also auto delete the files with exif data

OS Windows 10

How can I parse html table inside a script respecting merged cells

Posted: 05 Sep 2021 08:58 AM PDT

This header is contained in a js file https://www.portaldefinancas.com/js-tx-ctb/th-cdib.js

enter image description here

document.write(""),document.write('</p></caption><thead><tr><th rowspan="4">M&ecirc;s de<br>Refer&ecirc;ncia</th><th colspan="7">Taxas - %</th></tr><tr>    <th rowspan="3">Mensal</th><th colspan="4">Anualizada</th><th colspan="2">Acumulada</th></tr><tr>   <th colspan="2">Ano de<br>252 dias<br> &uacute;teis</th><th colspan="2">Ano de<br>365/366 dias<br>corridos</th><th rowspan="2">No ano</th><th rowspan="2">Em <br>12 meses</th></tr><tr><th>Dias</th><th>    Taxa</th><th>Dias</th><th>  Taxa</th></tr></thead><tbody>');  

How can I parse the headers respecting the merged rows and merged columns. The script I use today is

function getHeaders(url) {    var source = UrlFetchApp.fetch(url).getContentText()    source = source.split('document')[2]    var table = '<table><tr><th ' + source.match(/(?<=<th ).*(?=th>)/g) + 'th></tr></table>'    table=table.replace(/&ecirc;/g,'ê').replace(/&uacute;/g,'ú').replace(/<br>/g,'\n')    var doc = XmlService.parse(table);    var rows = doc.getDescendants().filter(function(c) {      var element = c.asElement();      return element && element.getName() == "tr";    });    var data = rows.slice(0).map(function(row) {      return row.getChildren("th").map(function(cell) {        return cell.getValue();      });    });    return data;   }  

but it doesn't respect merged areas. Thanks for any help !

I am trying to create a shortcut in Powershell from one server to another

Posted: 05 Sep 2021 08:57 AM PDT

$PrivateDrive = "Sharedrivepath1"  $ScanDrive = "ScanDrivePath2"    New-Item -Itemtype SymbolicLink -Path $PrivateDrive -Name ScanDrive -Value $ScanDrive  

I am trying to create a shortcut from the ScanDrive to the PrivateDrive, I have a full filepath and have access to both locations.

These both exist.

But I get the error "New-Item : Symbolic Links are not supported for the specified path"

EDIT: This is how I declare my Private and Scan Drives

$SamaccountName = ($name).Givenname + '.' + ($name.Surname)  $PrivateDrive = '\\SERVER1\private\home folders\' + $SamaccountName  $ScanDrive = "\\SERVER2\Shares_2\" + $SamaccountName  

Docusign webhooks SignMessageWithX509Cert mTLS

Posted: 05 Sep 2021 08:58 AM PDT

Trying out mutualTLS in demo account and trying to understand how the validations work. We are using eventNotifications with signMessageWithX509Cert property set to true. However, have no clue if it is working as DocuSign gives no information about it.

Questions:

  • Is mTLS enabled/possible for demo accounts?
  • If I have signMessageWithX509Cert=true and have no mTLS in my listener, all requests pass either way? DocuSign does not validation? I'm receiving all events either way and no error is thrown by DocuSign.
  • How can we know mTLS worked from Docusign logs in Connect console?

Using setValue instead of PostValue for LiveData

Posted: 05 Sep 2021 08:57 AM PDT

I have following Base class :

open class BaseViewModel<T>(  private val schedulerProvider: BaseSchedulerProvider,  private val requestObservable: Observable<T>  ) : ViewModel() {       private val compositeDisposable = CompositeDisposable()       private val _liveData = MutableLiveData<Resource<T>>()     val liveData: LiveData<Resource<T>>        get() = _liveData       protected fun sendRequest() {         _liveData.postValue(Resource.Loading)         composeObservable { requestObservable }.subscribe({             _liveData.postValue(Resource.Success(it))         }) {             _liveData.postValue(Resource.Failure(it.localizedMessage))             Timber.e(it)         }.also { compositeDisposable.add(it) }     }  }  

In one of my derived classes I have following logic :

class DetailViewModel(api: QapitalService, schedulerProvider: BaseSchedulerProvider,          currencyFormatter: CurrencyFormatterDefault, goal: SavingsGoal      ) : BaseViewModel<DetailWrapper>(schedulerProvider,          Observable.zip(api.requestFeeds(goal.id).map { it.wrapper },              api.requestSavingRules().map { it.wrapper },              BiFunction<List<Feed>, List<SavingsRule>, DetailWrapper>              { feeds, savingRules -> DetailWrapper(feeds,                  savingRules.joinToString { it.type },                  feeds.asWeekSumText(currencyFormatter)              ) })) {        init {          sendRequest()      }        class DetailWrapper(          val feeds: List<Feed>,          val savingRules: String,          val weekSumText: String)  }  

As you see in the sendRequest() method, I have postValue(Loading). I believe it is on the main thread and there is no need for PostValue rather I can setValue.

But by using setValue when I click on Home hardware button and resume the app again, ProgressBar appears again. Why that happens?

When I use PostValue, progressBar does not appear when I resume the app.

I have made some other similar projects and I did not face which the issue that I explained above, but that projects were a single Activity and multiple fragments using Navigation component. In the above project I have multiple Activities with multiple fragments which are getting attached to the Activities layout.

Full source code can be found : https://github.com/AliRezaeiii/SavingGoals-Cache

Hore is my progressBar in my fragment_detail layout :

<ProgressBar              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_gravity="center"              app:showLoading="@{vm.liveData}" />  

And here is showLoading binding adapter :

@BindingAdapter("showLoading")      fun showLoading(view: ProgressBar, resource: Resource<*>?) {          view.visibility = if (resource is Resource.Loading) View.VISIBLE else View.GONE      }  

iframe Vimeo fullscreen button not showing

Posted: 05 Sep 2021 08:59 AM PDT

For some reason, the Vimeo iframe is missing the fullscreen button. It works if I use the official embed code directly in the HTML, but not this way.

JS:

var iframe = document.createElement("iframe");  var videoid = document.querySelector(".active .video-id");  videoid.setAttribute("src", "allow='autoplay; fullscreen' webkitallowfullscreen mozallowfullscreen allowfullscreen");   iframe.setAttribute("src", "https://player.vimeo.com/video/" + videoid.id + "?autoplay=1&portrait=0&title=0 width='100' height='100' frameborder='0' allow='autoplay; fullscreen' webkitallowfullscreen mozallowfullscreen allowfullscreen");   videoid.appendChild(iframe);  

CSS:

    .video-id {          position: relative;          padding-bottom: 56.25%;          height: 0;          overflow: hidden;          z-index: -1;          pointer-events: none;      }      .video-id iframe,        .video-id object,        .video-id embed {          position: absolute;          top: 0;          left: 0;          width: 100%;          height: 100%;          pointer-events: auto;      }  

Error: Unauthorized at Request.callback . status: 401

Posted: 05 Sep 2021 08:59 AM PDT

https://developer.github.com/apps/quickstart-guides/using-the-github-api-in-your-app/

I am following the above tutorial on GitHub on setting up GitHub API, however, I encounter this problem.

==================================================

I simply run sudo smee --url https://smee.io/0AcqgdnAAdZA5q --path /event_handler --port 3002 in my terminal, and then I create an issue in one of the repos that the app is installed, just for testing purposes.

And then the following error appears while smee try to redirect the message to my mac computer,

{ Error: Unauthorized      at Request.callback (/usr/local/lib/node_modules/smee-client/node_modules/superagent/lib/node/index.js:706:15)      at IncomingMessage.parser (/usr/local/lib/node_modules/smee-client/node_modules/superagent/lib/node/index.js:916:18)      at IncomingMessage.emit (events.js:203:15)      at endReadableNT (_stream_readable.js:1145:12)      at process._tickCallback (internal/process/next_tick.js:63:19)    status: 401,    response:     Response {       _events: [Object: null prototype] {},       _eventsCount: 0,       _maxListeners: undefined,       res:        IncomingMessage {          _readableState: [ReadableState],          readable: false,          _events: [Object],          _eventsCount: 4,          _maxListeners: undefined,          socket: [Socket],          connection: [Socket],          httpVersionMajor: 1,          httpVersionMinor: 1,          httpVersion: '1.1',          complete: true,          headers: [Object],          rawHeaders: [Array],          trailers: {},          rawTrailers: [],          aborted: false,          upgrade: false,          url: '',          method: null,          statusCode: 401,          statusMessage: 'Unauthorized ',          client: [Socket],          _consuming: false,          _dumped: false,          req: [ClientRequest],          text: '' },       request:        Request {          _events: [Object: null prototype] {},          _eventsCount: 0,          _maxListeners: undefined,          _agent: false,          _formData: null,          method: 'POST',          url: 'http://127.0.0.1:3002/event_handler',          _header: [Object],          header: [Object],          writable: true,          _redirects: 0,          _maxRedirects: 5,          cookies: '',          qs: {},          _query: [],          qsRaw: [],          _redirectList: [],          _streamRequest: false,          _data: [Object],          req: [ClientRequest],          protocol: 'http:',          host: '127.0.0.1:3002',          _endCalled: true,          _callback: [Function],          res: [IncomingMessage],          response: [Circular],          called: true },       req:        ClientRequest {          _events: [Object],          _eventsCount: 3,          _maxListeners: undefined,          output: [],          outputEncodings: [],          outputCallbacks: [],          outputSize: 0,          writable: true,          _last: true,          chunkedEncoding: false,          shouldKeepAlive: false,          useChunkedEncodingByDefault: true,          sendDate: false,          _removedConnection: false,          _removedContLen: false,          _removedTE: false,          _contentLength: 7597,          _hasBody: true,          _trailer: '',          finished: true,          _headerSent: true,          socket: [Socket],          connection: [Socket],          _header:           'POST /event_handler HTTP/1.1\r\nhost: smee.io\r\nAccept-Encoding: gzip, deflate\r\nuser-agent: GitHub-Hookshot/b4238f9\r\ncontent-type: application/json\r\nconnection: close\r\naccept: */*\r\nx-github-event: issues\r\nx-github-delivery: 2ffd9d80-fba0-11e9-8f34-9987220100a1\r\nx-hub-signature: sha1=9b59ee3122af7a623934083d8d5432f32a7d42d6\r\nx-request-id: f422646b-fb28-4904-9b88-7294c9a01fbe\r\nx-forwarded-for: 140.82.115.249\r\nx-forwarded-proto: https\r\nx-forwarded-port: 443\r\nvia: 1.1 vegur\r\nconnect-time: 0\r\nx-request-start: 1572500103861\r\ntotal-route-time: 0\r\ncontent-length: 7597\r\ntimestamp: 1572500103863\r\n\r\n',          _onPendingData: [Function: noopPendingOutput],          agent: [Agent],          socketPath: undefined,          timeout: undefined,          method: 'POST',          path: '/event_handler',          _ended: true,          res: [IncomingMessage],          aborted: undefined,          timeoutCb: null,          upgradeOrConnect: false,          parser: null,          maxHeadersCount: null,          [Symbol(isCorked)]: false,          [Symbol(outHeadersKey)]: [Object] },       text: '',       body: {},       files: undefined,       buffered: true,       headers:        { 'content-type': 'text/html;charset=utf-8',          'content-length': '0',          'x-xss-protection': '1; mode=block',          'x-content-type-options': 'nosniff',          'x-frame-options': 'SAMEORIGIN',          server: 'WEBrick/1.3.1 (Ruby/2.3.7/2018-03-28)',          date: 'Thu, 31 Oct 2019 05:35:04 GMT',          connection: 'close' },       header:        { 'content-type': 'text/html;charset=utf-8',          'content-length': '0',          'x-xss-protection': '1; mode=block',          'x-content-type-options': 'nosniff',          'x-frame-options': 'SAMEORIGIN',          server: 'WEBrick/1.3.1 (Ruby/2.3.7/2018-03-28)',          date: 'Thu, 31 Oct 2019 05:35:04 GMT',          connection: 'close' },       statusCode: 401,       status: 401,       statusType: 4,       info: false,       ok: false,       redirect: false,       clientError: true,       serverError: false,       error:        { Error: cannot POST /event_handler (401)            at Response.toError (/usr/local/lib/node_modules/smee-client/node_modules/superagent/lib/node/response.js:94:15)            at ResponseBase._setStatusProperties (/usr/local/lib/node_modules/smee-client/node_modules/superagent/lib/response-base.js:123:16)            at new Response (/usr/local/lib/node_modules/smee-client/node_modules/superagent/lib/node/response.js:41:8)            at Request._emitResponse (/usr/local/lib/node_modules/smee-client/node_modules/superagent/lib/node/index.js:752:20)            at IncomingMessage.parser (/usr/local/lib/node_modules/smee-client/node_modules/superagent/lib/node/index.js:916:38)            at IncomingMessage.emit (events.js:203:15)            at endReadableNT (_stream_readable.js:1145:12)            at process._tickCallback (internal/process/next_tick.js:63:19) status: 401, text: '', method: 'POST', path: '/event_handler' },       created: false,       accepted: false,       noContent: false,       badRequest: false,       unauthorized: true,       notAcceptable: false,       forbidden: false,       notFound: false,       unprocessableEntity: false,       type: 'text/html',       charset: 'utf-8',       links: {},       setEncoding: [Function: bound ],       redirects: [] } }  

But one thing I am sure is that smee successfully receives the webhook coming from GitHub server, it is just something wrong while redirecting the hook to my personal mac computer. The proof is that I can view the post message from smee website.

I can view the hook on smee website directly

There is a script running on my mac computer, serving as a local server, waiting for the redirect from smee . But I think it's not relevant to the question here so I am not going to post the code here. It's just a simple ruby script copying from the Github repo.

What is the nestjs error handling approach (business logic error vs. http error)?

Posted: 05 Sep 2021 08:57 AM PDT

While using NestJS to create API's I was wondering which is the best way to handle errors/exception. I have found two different approaches :

  1. Have individual services and validation pipes throw new Error(), have the controller catch them and then throw the appropriate kind of HttpException(BadRequestException, ForbiddenException etc..)
  2. Have the controller simply call the service/validation pipe method responsible for handling that part of business logic, and throw the appropriate HttpException.

There are pros and cons to both approaches:

  1. This seems the right way, however, the service can return Error for different reasons, how do I know from the controller which would be the corresponding kind of HttpException to return?
  2. Very flexible, but having Http related stuff in services just seems wrong.

I was wondering, which one (if any) is the "nest js" way of doing it?

How do you handle this matter?

Maven crashes when trying to compile a project "Error executing Maven."

Posted: 05 Sep 2021 08:57 AM PDT

I'm trying to compile a project that uses maven.

Running mvn compile results in the following error:

[ERROR] Error executing Maven.  [ERROR] java.lang.IllegalStateException: Unable to load cache item  [ERROR] Caused by: Unable to load cache item  [ERROR] Caused by: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils  

This happens anywhere that I run this, it doesn't have to be in the project directory.

What am I doing wrong?

maven 3.3.9, ubuntu 17.04

Full output from mvn -X:

Apache Maven 3.3.9  Maven home: /usr/share/maven  Java version: 9-Ubuntu, vendor: Oracle Corporation  Java home: /usr/lib/jvm/java-9-openjdk-amd64  Default locale: en_GB, platform encoding: UTF-8  OS name: "linux", version: "4.10.0-21-generic", arch: "amd64", family: "unix"  [ERROR] Error executing Maven.  com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: Unable to load cache item      at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2205)      at com.google.common.cache.LocalCache.get(LocalCache.java:3951)      at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3955)      at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4870)      at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4876)      at com.google.inject.internal.FailableCache.get(FailableCache.java:48)      at com.google.inject.internal.ConstructorInjectorStore.get(ConstructorInjectorStore.java:50)      at com.google.inject.internal.ConstructorBindingImpl.initialize(ConstructorBindingImpl.java:137)      at com.google.inject.internal.InjectorImpl.initializeBinding(InjectorImpl.java:533)      at com.google.inject.internal.AbstractBindingProcessor$Processor$1.run(AbstractBindingProcessor.java:160)      at com.google.inject.internal.ProcessedBindingData.initializeBindings(ProcessedBindingData.java:44)      at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:123)      at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)      at com.google.inject.Guice.createInjector(Guice.java:99)      at com.google.inject.Guice.createInjector(Guice.java:73)      at com.google.inject.Guice.createInjector(Guice.java:62)      at org.codehaus.plexus.DefaultPlexusContainer.addPlexusInjector(DefaultPlexusContainer.java:481)      at org.codehaus.plexus.DefaultPlexusContainer.<init>(DefaultPlexusContainer.java:206)      at org.apache.maven.cli.MavenCli.container(MavenCli.java:545)      at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:281)      at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)      at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)      at java.base/java.lang.reflect.Method.invoke(Method.java:547)      at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)      at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)      at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)      at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)  Caused by: java.lang.IllegalStateException: Unable to load cache item      at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:79)      at com.google.inject.internal.cglib.core.internal.$LoadingCache.get(LoadingCache.java:34)      at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)      at com.google.inject.internal.cglib.core.$AbstractClassGenerator.create(AbstractClassGenerator.java:291)      at com.google.inject.internal.cglib.reflect.$FastClass$Generator.create(FastClass.java:65)      at com.google.inject.internal.BytecodeGen.newFastClass(BytecodeGen.java:204)      at com.google.inject.internal.DefaultConstructionProxyFactory.create(DefaultConstructionProxyFactory.java:55)      at com.google.inject.internal.ProxyFactory.create(ProxyFactory.java:159)      at com.google.inject.internal.ConstructorInjectorStore.createConstructor(ConstructorInjectorStore.java:90)      at com.google.inject.internal.ConstructorInjectorStore.access$000(ConstructorInjectorStore.java:29)      at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:37)      at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:33)      at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)      at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3540)      at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2321)      at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2284)      at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2199)      ... 28 more  Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils      at com.google.inject.internal.cglib.reflect.$FastClassEmitter.<init>(FastClassEmitter.java:67)      at com.google.inject.internal.cglib.reflect.$FastClass$Generator.generateClass(FastClass.java:77)      at com.google.inject.internal.cglib.core.$DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)      at com.google.inject.internal.cglib.core.$AbstractClassGenerator.generate(AbstractClassGenerator.java:329)      at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)      at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)      at com.google.inject.internal.cglib.core.internal.$LoadingCache$2.call(LoadingCache.java:54)      at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)      at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:61)      ... 44 more  

react native show current time and update the seconds in real-time

Posted: 05 Sep 2021 08:58 AM PDT

I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don't update unless I refresh the page. I also tried using setInterval function in render(), it do got update but it's expensive for CPU. is there a good method to realise the function?

state = {      curTime: null,  }  render(){      setInterval(function(){this.setState({curTime: new  Date().toLocaleString()});}.bind(this), 1000);      return (          <View>              <Text style={headerStyle.marginBottom15}>Date: {this.state.curTime}</Text>          </View>      );  }  

How to give automatically generated buttons names in Tkinter?

Posted: 05 Sep 2021 08:57 AM PDT

So i am genertaing a grid of 3x3 buttons for a Tic Tac Toe game im making, and i want to to end up so that when a button is pressed it changes to either a X or O, however i dont know how to give each button a unique identifier so i know which button to change.

Heres the code for the buttons.

num=1  for row in range(3):  for column in range(3):      Button(TTTGrid,bg="#ffffff",  width=20,height = 6, command=lambda row=row, column=column: TTTGridPress(row, column),relief=SUNKEN).grid(row=row, column=column, sticky=W)      num=num+1  

No comments:

Post a Comment