2024-01-30

Issue while executing the multi-layer commands on windows

The below is executing on windows:

C:\cygwin\bin\bash.exe  -c "echo abc; echo 1 ; c:/cygwin/bin/bash.exe -c "c:/cygwin/bin/tcsh.exe echo def; pwd "  "

Running the above command, and getting the output as:

abc
1
[PPP@machine1 ...Users/PPP]$ 

Desired Output:

 abc
 1
 def
 C:\Users\PPP 

In all, I want the commands under tcsh to also work (In above command, it is "echo def; pwd"). How can I have the progress on it?



Sitecore instance styles are not available after installation [closed]

After Installing sitecore instance, My login page is looking like this enter image description here

after login it is looking without styling you can find the image below enter image description here

Can you please help me in this

I don't have any idea what to do next



2024-01-29

Problem moving lines (one by one) from one text file to another

I try to create a program that moves the first line in a text file to another and then remove said line in the first file (i.e. they are moved one by one). This should continue until there aren't any more lines in the first file to be moved to the second file.

The problem I have is that the program freezes and won't quit properly. I have experimented with the code and reached the conclusion that the error probably is in the counting of lines but that's all...

Here is the code:

# Create the second file
open("file2.txt", 'w', encoding="utf-8-sig").close()

# Find out how many lines in file one
lines = open("file1.txt", 'r', encoding="utf-8-sig").readlines()

# Loop the amount of lines
while range(len(lines)) != 0:
    
    # Get the first line in the first file
    first_line = open("file1.txt", 'r', encoding="utf-8-sig").readline()
    
    # Write the line to the second file
    out = open("file2.txt", 'a', encoding="utf-8-sig")
    out.write(first_line)
    
    # Remove the first line from the first file
    all_lines = open("file1.txt", 'r', encoding="utf-8-sig").readlines()
    new_file = open("file1.txt", 'w', encoding="utf-8-sig")
    new_file.writelines(all_lines[1:])
    new_file.close()

I would really appreciate some help with the code and critic in general.



2024-01-28

.NET core minmal APIs not connecting with react native app (Expo CLI)

I am trying to connect my .Net core minmal apis backend with react native but it keeps giving me network error, I dont know what I am doing wrong. I have double checked the url the ip address too many times but still could not make it to work. Please , I would appreciate your help.

I have tried the same application with a node backend it worked fine for node, may be because node was using http while .net backend is using https but I still do not understand if there is any thing wrong.

enter image description here

enter image description here

enter image description here

enter image description here



2024-01-27

Moengage Push Notification Click Not Redirecting While App On Foreground/Running in Background

Hello I am currently running a Flutter app that is using Moengage to send push notifications. Currently, the notification is receiving just fine. But, there is a problem that only occurs in iOS: the notification is not redirecting to specified link when the notification is clicked when the application is currently opened/running in background. Is there any specific configuration that I might have missed? Sorry I am unable to give a piece of code but based on the documentation I don't think there is much things to be done in the setup after push notifications are received perfectly right?



2024-01-24

Cycles per element in out-of-order execution

Problemyour text Consider the following code on a machine that run a multiplication in 5 cycles.

double aprod(double a[], int n)
{
int i;
double x, y, z;
double r = 1;

for (i=0; i < n-2; i += 3){
    x = a[i]; y=a[i+1]; z=a[i+2];
    r = r * (x * (y * z));
}

}

Compute the theoretical Cycles per Element (CPE), where the only limiting factor is the data dependencies.

Reference The problem is part of the Problem 5.9, p. 589, in Computer Systems: A Programmer's Perspective from Bryant et al.

My solution:

You have basically three multiplications per iteration. 1.

dummy1 := (y * z)
    dummy2 := x*(dummy1)
    
      r*(dummy2)
      

      The dummy1 and dummy2 were just introduced to clearly state the multiplications. In the code, they are replaced by their definition, e. g. dummy1 is replaced by (y*z).

      The 3. multiplication of an iteration has no data dependency to 1. and 2. multiplication of the following iteration. Thus, the 3. multiplication of an iteration and 1. as well as 2. multiplications of an iteration can be executed out of order (and instruction-level-parallelism is appliable).

      However, 1. and 2. multiplication have an data dependency, thus need to be executed sequentially. Therefore, a machine can compute 3. multiplication of an iteration and 1. multiplication of the next iteration in parallel, and subsequently compute 2. multiplication of the next iteration. Overall, 2 multiplications are computed in parallel and subsequently another multiplication is computed. Therefore, theoretical CPE is 2*5 / 3 = 3.33.

      The solution of the book states on p. 604 that the theoretical CPE is 5 / 3 = 1.67 arguing that 1. and 2. multiplications can be computed in parallel to the 3. multiplication. The theoretical CPE implies that all three multiplications can be computed in parallel.

      Does the book miss that there is a data dependency between 1. and 2. multiplication, thus are not parallelizable?



      2024-01-23

      R: Merging Parts of a Graph Together

      I am working with the R programming language.

      I have the following "Tree" that depicts the results of a coin flipping game (start at 5 points, and 0.5 prob of +1 and 0.5 prob of -1 at each turn):

      outcomes <- c(-1, 1)  
      
      combinations <- expand.grid(rep(list(outcomes), 10))
      colnames(combinations) <- paste("Turn", 1:10)
      
      library(data.tree)
      
      generate_tree <- function(node, depth, total) {
          if (depth == 0) {
              node$Set(total = total)
              return(node)
          } else {
              for (outcome in outcomes) {
                  child <- node$AddChild(name = as.character(total + outcome), total = total + outcome)
                  generate_tree(child, depth - 1, total + outcome)
              }
              return(node)
          }
      }
      
      root <- Node$new("Start", total = 5)
      
      root <- generate_tree(root, 4, 5)
      
      print(root, "total")
      
      plot(root, "total")
      

      enter image description here

      My Question: Is it possible to reformat (i.e. merge) this graph such that at each turn, all "nodes" with the same "value" are collapsed into a single node? This would mean that at each turn, a given "value" could only appear once.

      After reading the following references (How to collapse branches in a phylogenetic tree by the label in their nodes or leaves?, Plotting a tree - collapsing a vector of nodes) tried to do this with the following code:

      collapse_nodes <- function(node) {
          if (node$isRoot) {
              return(node)
          } else {
              parent <- node$parent
              siblings <- parent$children
              same_value_siblings <- siblings[sapply(siblings, function(x) x$total == node$total)]
              if (length(same_value_siblings) > 1) {
                  node$parent <- NULL
                  parent$RemoveChild(node$name)
              }
              return(node)
          }
      }
      root <- Traverse(root, collapse_nodes, mode = "post-order")
      
      print(root, "total")
      plot(root, "total")
      

      Unfortunately, I got the following error:

      Error in Traverse(root, collapse_nodes, mode = "post-order") : 
        unused argument (mode = "post-order")
      

      Can someone please suggest how to resolve this problem? Thanks!

      Note: In the end, all nodes of the same color will merged into a single node - this is what I am trying to achieve:

      enter image description here



      Optimization with a nested set of constraints

      I am trying to use Gekko to find an optimal solution for a camera lens distortion calibration problem (Undistort). In my case I am interested in solving a simpler problem that is only concerned with determining two or four variables (K1 K2 || K1 K2 CX CY). I was able to use scipy.optimize.minimize to come to some reasonable solutions that I know are within a good range, however, my solution relies on a rather complex invertibility constraint of the final result and I found that this was not possible to implement in scipy. So, I am looking for some help on how to model this invertibility constraint using Gekko.

      The invertibility constraint is as follows ( see div_constraint_invertibility() ):

      def get_rad_norm_k(dc, w, h):
            dmi = get_max_dist(dc=dc, w=w, h=h)
            r2 = m.sqrt(dmi) / 2
            r2_2 = r2*r2
            r2_4 = r2_2*r2_2
            denk1 = -12 * r2_2
            denk2 = -12 * r2_4
            return denk1, denk2
      
      def get_max_dist(dc, h, w):
          corner_distances = [(dc[0] - 0)**2 + (dc[1] - 0)**2,
                              (dc[0] - 0)**2 + (dc[1] - w)**2,
                              (dc[0] - h)**2 + (dc[1] - w)**2,
                              (dc[0] - h)**2 + (dc[1] - 0)**2]
      
          mx = corner_distances[0]
          for cd in corner_distances[1:]:
              mx = m.max3(mx, cd)
          return mx
      
      def div_constraint_invertibility(x, ldm):
      
          p1 = x[0]
          p2 = x[1]
          dc = [ldm.Cx, ldm.Cy]
          
          w = ldm.width
          h = ldm.height
          denk1, denk2 = get_rad_norm_k(dc=dc, w=w, h=h)
          
          r1sq = get_max_dist(dc=dc, w=w, h=h)
          r1p4 = r1sq**2
          
          k1 = (((-p1) / (1 + p1)) + ((16 * p2) / (1 + p2))) / denk1
          k2 = (((-4 * p2) / (1 + p2)) + (p1 / (1 + p1))) / denk2
          
          if -2 < r1sq * k1 < 2:
              if -1. - r1sq * k1 < r1p4 * k2 < (1. - r1sq * k1) / 3:
                  return 1  # Passed Check
          else:
              if r1sq * k1 >= 2:
                  if -1. - r1sq * k1 < r1p4 * k2 < (-r1p4 * k1**2 / 12):
                      return 1  # Passed Check
          
          return -1  # Failed Check
      

      The list of values in argument x contains [P1, P2] or [P1, P2, CX, CY] where P1 and P2 are normalized values of K1 and K2. I have tried to implement the methods using Gekko functions, my next step was to try to implement the conditional checks in "div_constraint_invertibility" using m.if3(). Although, I am wondering if there is a better way to format the problem here as I feel that such a nested m.if3() structure is not a very elegant solution and moreover I am not certain what I should actually return from the function (I probably should be returning some function value rather than -1 or 1...).

      EDIT 1 Scipy entry point and other contextual code. Here is the scipy minimization approach. The function cumulative_point_to_line_error takes a set of points belonging to an arc extracted from a distorted image and applies the distortion model to determine the line equation fit error after undistorting the image points. An initial starting point looks something like:

      dm0 = [-0.0, 0.0, input_image_center_X, input_image_center_Y]
      

      Along with an array of points that correspond to an arc. For example, depending on the image there may be 30 lists containing sets of points relating to the same extracted arc.

      I can provide even more code but wanted to avoid dumping a wall of code...let me know and I can dm you it or I can provide more code here too.

      def model_estimation(ip, w, h, oc):
          ldm = ip.lens_model
          dc = [ldm.Cx, ldm.Cy]
          prevk1 = ldm.d[1]
      
          if len(ldm.d) != 3:
              ldm.d.append(0)
          prevk2 = ldm.d[2]
          if oc:
              dm0 = [prevp1, prevp2, dc[0], dc[1]]
          else:
              dm0 = [prevp1, prevp2]
      
          cons = []
          bnds = []
          if oc:
              dc_drift = 2
              bnds = [(-np.inf, np.inf), (-np.inf, np.inf),
                      (float(ldm.width / 2 - dc_drift), float(ldm.width / 2 + dc_drift)),
                      (float(ldm.height / 2 - dc_drift), float(ldm.height / 2 + dc_drift))]
      
          cons.append({'type': 'ineq', 'fun': div_constraint_invertibility, 'args': (ip.lens_model,)})
      
          print(f"Optimizing: {dm0}")
          if cons:
              print(f"Constraints:")
              for con in cons:
                  print(f"Const: {con['fun'].__name__}")
          if bnds:
              print(f"Bounds:")
              for idx, bnd in enumerate(bnds):
                  print(f"{bnd[0]} <= x{idx} <= {bnd[1]}")
      
          result = spo.minimize(fun=cumulative_point_to_line_error, x0=np.array(dm0), args=(ip,),
                                constraints=cons, bounds=bnds, method='SLSQP', options={"disp": True})
      
          print(f"Optimization Result: {result.x} | {result.fun}")
      

      EDIT 2

      I gave it a shot trying to convert my objective to one that is useable with Gekko. Is is possible to call m.Minimize on something like 'cumulative_point_to_line_error'? Currently working on how to handle the division by 0 check in the 'div_update_point' method:

      def HornerPoly(poly, n, nrmx):
          sol = poly[n]
          i = n - 1
          while i > -1:
              sol = sol * nrmx + poly[i]
              i -= 1
          return sol
      
      
      def div_update_point(m, px, py, K1, K2, dc_x, dc_y):
          center_dist = (px - dc_x)**2 + (py - dc_y)**2
          dist_coef = [1, K1, K2]
          A = HornerPoly(dist_coef, len(dist_coef) - 1, center_dist)
      
          # m.IF ?
          if A == 0:
              return px, py
          else:
              A = 1.0 / A
      
          new_x = dc_x + (px - dc_x) * A
          new_y = dc_y + (py - dc_y) * A
          return new_x, new_y
      
      def cumulative_point_to_line_error(m, p1, p2, dc_x, dc_y, w, h, houghlines):
      
      n1 = m.Intermediate(((-p1) / (1 + p1)) + (16 * p2 / (1 + p2)))
      n2 = m.Intermediate(((-4 * p2) / (1 + p2)) + (p1 / (1 + p1)))
      denk1, denk2 = get_rad_norm_k(m, dc_x=dc_x, dc_y=dc_y, w=w, h=h)
      
      cumulative_err = 0
      for idx, hl in enumerate(houghlines):
      
          pnts_o = hl.pnts
          err = 0
          zero = 10e-100
          num_pnts = len(pnts_o)
          um = vm = 0
          suu = suv = svv = 0
      
          pnts_e = []
          for pnt in pnts_o:
              x, y = div_update_point(px=pnt[0], py=pnt[1], K1=n1/denk1, K2=n2/denk2, dc_x=dc_x, dc_y=dc_y)
              pnts_e.append([x, y])
      
          for pnt in pnts_e:
              x = pnt[0]
              y = pnt[1]
              um += x
              vm += y
          um = um / num_pnts
          vm = vm / num_pnts
      
          for pnt in pnts_e:
              x = pnt[0]
              y = pnt[1]
              suu += (x - um)**2
              suv += (x - um) * (y - vm)
              svv += (y - vm)**2
          suu = suu / num_pnts
          suv = suv / num_pnts
          svv = svv / num_pnts
      
          if np.abs(suv) <= zero:
              # print('XY <= ZERO*')
              if suu < svv and svv > zero:
                  hl.a = 1.
                  hl.b = 0.
                  hl.c = -um
                  err = 0.
                  # print(f'Iter. Method Line: {self.a}x + {self.b}y + {self.c} = 0')
                  # print(f'Error == {err}')
                  return hl, err
              if svv < suu and suu > zero:
                  hl.a = 0.
                  hl.b = 1.
                  hl.c = -vm
                  err = 0
                  # print(f'Iter. Method Line: {self.a}x + {self.b}y + {self.c} = 0')
                  # print(f'Error == {err}')
                  return hl, err
              # print('Failed to recalculate!')
              return None, err
      
          r = np.array([[1, 0, 0],
                        [1, 0, 0],
                        [0, 1, 0],
                        [0, 1, 0]], dtype=float)
      
          h = 0.5 * (suu - svv) / suv
          if h > 0:
              r[0, 1] = -h - np.sqrt(1. + np.square(h))
              r[0, 2] = -(um + r[0, 1] * vm)
              r[1, 1] = -1. / r[0, 1]
              r[1, 2] = -(um + r[1, 1] * vm)
              r[2, 0] = h + np.sqrt(1. + np.square(h))
              r[2, 2] = -(r[2, 0] * um + vm)
              r[3, 0] = -1. / r[2, 0]
              r[3, 2] = -(r[3, 0] * um + vm)
          else:
              r[0, 1] = -h + np.sqrt(1. + np.square(h))
              r[0, 2] = -(um + r[0, 1] * vm)
              r[1, 1] = -1. / r[0, 1]
              r[1, 2] = -(um + r[1, 1] * vm)
              r[2, 0] = h - np.sqrt(1. + np.square(h))
              r[2, 2] = -(r[2, 0] * um + vm)
              r[3, 0] = -1. / r[2, 0]
              r[3, 2] = -(r[3, 0] * um + vm)
      
          for row in range(0, r.shape[0]):
              norm = np.sqrt(np.square(r[row, 0]) + np.square(r[row, 1]))
              for col in range(0, r.shape[1]):
                  r[row, col] /= norm
      
          min = 0
          k = 0
          for pnt in pnts_e:
              x = pnt[0]
              y = pnt[1]
              sol = r[0, 0] * x + r[0, 1] * y + r[0, 2]
              min += np.square(sol)
      
          for row in range(1, r.shape[0]):
              h = 0
              for pnt in pnts_e:
                  x = pnt[0]
                  y = pnt[1]
                  sol = r[row, 0] * x + r[row, 1] * y + r[row, 2]
                  h += np.square(sol)
              if h < min:
                  k = row
                  min = h
      
          hl.a = r[k, 0]
          hl.b = r[k, 1]
          hl.c = r[k, 2]
          # err = min
      
          # Update ip TODO: edit houghline list?
          houghlines[idx] = hl
          cumulative_err += min
      return cumulative_err
      


      2024-01-22

      Keyboard input with pynput on a Mac

      keyboard fails on a Mac and I would like to use pynput but fail to execute successfully.

      from pynput import keyboard
      import time
      
      def on_press(key, ts, gt_forward, rb, extent, aoi, aoibuffer, jparams):
          if key == keyboard.Key.enter:
              print("\nYou pressed Enter... we continue with osm_LoD1_3DCityModel.")
              
              ...lots of code that saves something.
              
      def on_release(key):
          if key == keyboard.Key.esc:
              # Stop listener
              return False
      
      def main():
          start = time.time()
          
          ...code here...
      
          print('')
          print("Have a look at the matplotlib render that might highlight errors (red) in the 2D vectors.\n\nIf there are no challenges press 'Enter' to continue; else press 'Esc' to exit: ")
      
          with keyboard.Listener(
                  on_press=lambda key: on_press(key, ts, gt_forward, rb, extent, aoi, aoibuffer, jparams),
                  on_release=keyboard) as listener:
              listener.join()
      
          src_ds = None      
          end = time.time()
          print('runtime:', str(timedelta(seconds=(end - start))))  
      
      if __name__ == "__main__":
          main()
      

      I need to pass the ts, gt_forward, rb, extent, aoi, aoibuffer, jparams variables to on_pass function ---...lots of code that saves something. will use it-- but am not sure of the proper syntax. I get an error message.

        File ~/miniconda3/envs/osm3D_v3/lib/python3.8/site-packages/spyder_kernels/py3compat.py:356 in compat_exec
          exec(code, globals, locals)
      
        File ~/Documents/osm_LoD1_3DCityModel/Jan2024_fromGitHub/osm3DMainMac.py:178
          main()
      
        File ~/Documents/osm_LoD1_3DCityModel/Jan2024_fromGitHub/osm3DMainMac.py:155 in main
          listener.join()
      
        File ~/miniconda3/envs/osm3D_v3/lib/python3.8/site-packages/pynput/_util/__init__.py:276 in join
          six.reraise(exc_type, exc_value, exc_traceback)
      
        File ~/miniconda3/envs/osm3D_v3/lib/python3.8/site-packages/six.py:718 in reraise
          raise value.with_traceback(tb)
      
        File ~/miniconda3/envs/osm3D_v3/lib/python3.8/site-packages/pynput/_util/__init__.py:228 in inner
          return f(self, *args, **kwargs)
      
        File ~/miniconda3/envs/osm3D_v3/lib/python3.8/site-packages/pynput/_util/darwin.py:265 in _handler
          self._handle(proxy, event_type, event, refcon)
      
        File ~/miniconda3/envs/osm3D_v3/lib/python3.8/site-packages/pynput/keyboard/_darwin.py:273 in _handle
          self.on_release(key)
      
        File ~/miniconda3/envs/osm3D_v3/lib/python3.8/site-packages/pynput/_util/__init__.py:144 in inner
          if f(*args) is False:
      
      TypeError: 'module' object is not callable
      

      How do I structure the function call successfully please?

      Also will the revised script, with pynput, execute successfully on a Windows machine?



      2024-01-21

      Blocking the clock signal

      Let's say I need to find out that the BLOCK signal came earlier than the 5 clk signal. These signals are asynchronous to each other, so I can't use the classic construction as shown below.

      always(posedge clk)
      if(cnt==4 && !BLOCK)
      flag<=1;
      else 
      flag<=0;
      //The flag will be set to 1 only if the BLOCK signal does not arrive before 5 clk.
      
      always(posedge clk)
      cnt <= cnt + 1;
      

      But I can block clk when the BLOCK signal arrives so that it stops clocking flag and the flag is not set to 1.

      wire clk_flag = clk & !BLOCK;
      
      always(posedge clk_flag)
      if(cnt==4)
      flag<=1;
      else 
      flag<=0;
      
      //The flag will be set to 1 only if the BLOCK signal does not arrive before 5 clk
      
      always(posedge clk)
      cnt <= cnt + 1;
      

      Is it acceptable to mix signals through "and" for clk in design?

      I have not seen such solutions, but I do not see anything dangerous for the design here, I do not know how to solve the problem with signals in another way. Or maybe someone knows how to solve the problem of determining which of the two signals came earlier (the fifth clk or BLOCK) if they are asynchronous? Thanks.



      Why is it adding me a random pixel on the screen?

      I'm making the snake game and I got to the part where there are (for now) 3 asterisks that make the snake. When I move from vertical to horizontal and from horizontal to vertical it adds another asterisk this is how it looks beforethis is how it looks after
      And for some reason just adds another * to the row of *s in the same place every time after 3 times to the leftwhen I pressed left for the 4th time

      For now my code is:

      IDEAL
      MODEL small
      STACK 100h
      DATASEG
      ; --------------------------
      ; Your variables here
      ; --------------------------
      saveal db, ' '  ;used in line 223-233
      
      app dw 0       ;place of the apple
      st_am dw 3
      stars dw 0, 0, 0  ;places of the *
      
      CODESEG
      proc black
      body:
          mov [es:si], ax
          add si, 2
          cmp si, 25*80*2
          jnz body
        ret
      endp black
      
      proc up
          mov di, 80*2
          cmp si, di
          jb not_move_up
          
          cmp si, [app]
          jnz move_up
          call apple
          
      move_up:
          call delete
          
          mov di, [stars+2]
          mov [stars+4], di
          mov di, [stars]
          mov [stars+2], di
          sub di, 80*2
          mov ah, 156
          mov al, '*'
          mov [es:di], ax
          mov [stars], si
          
          sub si, 80*2
          mov ah, 156
          mov al, '*'
          mov [es:si], ax
          
      not_move_up:
        ret
      endp up
      
      proc down
      
          mov di, (24*80*2)-1
          cmp si, di
          jg not_move_down
          
          cmp si, [offset app]
          jnz move_down
          call apple
          
      move_down:
          call delete
          
          mov di, [stars+2]
          mov [stars+4], di
          mov di, [stars]
          mov [stars+2], di
          add di, 80*2
          mov ah, 156
          mov al, '*'
          mov [es:di], ax
          mov [stars], si
          
          add si, 80*2
          mov ah, 156
          mov al, '*'
          mov [es:si], ax
      not_move_down:
        ret
      endp down
      proc left
      
          mov dx, 0
          mov bx, si
          mov ax, si
          mov si, 80*2
          div si
          mov si, bx
          cmp dx,0
          jz not_move_left
          
          cmp si, [offset app]
          jnz move_left
          call apple
          
      move_left:
          call delete
          
          mov di, [stars+2]
          mov [stars+4], di
          mov di, [stars]
          mov [stars+2], di
          mov ah, 156
          mov al, '*'
          mov [es:di], ax
          mov [stars], si
          
          sub si, 2
          mov ah, 156
          mov al, '*'
          mov [es:si], ax
      not_move_left:
        ret
      endp left
      proc right
      
          mov dx, 0
          mov bx, si
          mov ax, si
          mov si, 80*2
          div si
          mov si, bx
          cmp dx,158
          jz not_move_right
          
          cmp si, [app]
          jnz move_right
          call apple
          
      move_right:
          call delete
          
          mov di, [stars+2]
          mov [stars+4], di
          mov di, [stars]
          mov [stars+2], di
          mov ah, 156
          mov al, '*'
          mov [es:di], ax
          mov [stars], si
          
          add si, 2
          mov ah, 156
          mov al, '*'
          mov [es:si], ax
      not_move_right:
        ret
      endp right
      
      proc apple
          mov ax, 40h
          mov es, ax
          mov ax, [es:6ch]
          and ax, 0000001111111110b
          mov di,ax
          mov [offset app], di
          mov ax, 0b800h
          mov es, ax
          
          mov al, '@'
          mov ah, 154
          mov [es:di], ax
        ret 
      endp apple
          
      proc delete
          mov bx, offset stars
          mov di, [st_am]
          dec di
          shl di, 1
          mov di, [bx+di]
          mov ax, 0b800h
          mov es, ax
          
          mov al, ' '
          mov ah, 0
          
          mov [es:di], ax
        ret
      endp delete
      start:
          mov ax, @data
          mov ds, ax
      ; --------------------------
      ; Your code here
      ; --------------------------
          mov ax, 0b800h
          mov es, ax
          
          mov si,0
          mov al, ' '
          mov ah, 0
          call black
          
          mov bx, offset stars
          
          mov si, ((12*80+40)*2)-2
          mov al, '*'
          mov ah, 156
          mov [es:si], ax
          mov [bx], si
          mov si, (12*80+40)*2
          mov al, '*'
          mov ah, 156
          mov [es:si], ax
          mov [bx+2], si
          mov si, ((12*80+40)*2)+2
          mov al, '*'
          mov ah, 156
          mov [es:si], ax
          mov [bx+4], si
          mov si, ((12*80+40)*2)-2    
      
          call apple
          
      yesOrno:
          mov ah, 1h
          int 21h
          mov [byte ptr saveal], al
          
          cmp [byte ptr saveal], 'w'
          jz w
          cmp [byte ptr saveal], 'a'
          jz a
          cmp [byte ptr saveal], 's'
          jz s
          cmp [byte ptr saveal], 'd'
          jz d
          cmp [byte ptr saveal], 'q'
          jmp exit
          
      w:
          call up
          jmp yesOrno
      s:
          call down
          jmp yesOrno 
      a:
          call left
          jmp yesOrno
      d:
          call right
          jmp yesOrno
          
      exit:
          mov ax, 4c00h
          int 21h
      END start
      

      I tried to think myself, but I couldn't think of something.
      So sorry for asking a lot.



      Axios methods GET and POST do not respond in Vercel deploy

      I have a MERN project in my Vercel account which is divided into two parts: client and server. Both pages are perfectly deployed and available but my Axios methods related to the server page don't work in my deploy when they do in my local PC. The only one that responds correctly is the hero, which brings me six images from my database and renders what I need. However, when I go into another route the browser console throws an error 500. For instance, I am in a route where I have an useEffect hook with an Axios POST method and I have no response from the server.

      Axios from the front:

      useEffect(()=>{
          async function getList(){
            try{
              const response = await axios.post("https://pelis-mern-server-five.vercel.app/lists/get-my-list", {id:user._id, profId:profileId}, {withCredentials:true, headers:{"Content-Type":"application/json"}})
              console.log(response)
              if(response.data.list.length > 0){
                console.log("hay")
                setList(response.data.list)
              }
            }catch(err){console.log(err.stack)}
          }
          getList()
        },[])
      

      Controller from the back (route /lists/get-my-list):

      const get_my_list = async (req,res) => {
          console.log("req.user", req.user)
          const {id, profId} = req.body
          const user = await User.findById(id)
          const index = user.profiles.findIndex(prof => prof._id == profId)
          const list = user.profiles[index].myList
          res.json({list:list})
      }
      

      This is what I obtain in my browser's console (my catch's console.log(err.stack)):

      AxiosError: Request failed with status code 500
          at settle.js:19:12
          at XMLHttpRequest.f (xhr.js:111:7)
      

      Axios also says that the error is BAD_RESPONSE, not BAD_REQUEST. The same error happens when I go into my dashboard with a GET method in an useEffect.

      useEffect(()=>{
              async function obtainProfiles(){
                  try{
                      const data = await axios.get("https://pelis-mern-server-five.vercel.app/profiles",{withCredentials:true})
                      console.log(data.data)
                      setProfiles(data.data)
                  }catch(err){
                      console.log(err.stack)
                  }
              }
              obtainProfiles()
      },[])
      

      From the back (route /profiles):

      const get_all_profiles = async (req,res) => {
        console.log("req.user", req.user)
        let call = await User.findById({_id:req.user.id})
        let profiles = call.profiles
        res.json(profiles)
      }
      

      I check the logs in my server's deploy and this is the error that appears every time I don't have a response.

      req.user undefined //user object console log
      
      Unhandled Promise Rejection 
      {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: Cannot read properties of undefined (reading 'id')",
      "reason":{"errorType":"TypeError",
      "errorMessage":"Cannot read properties of undefined (reading 'id')",
      "stack":["TypeError: Cannot read properties of undefined (reading 'id')"," at get_all_profiles 
      (/var/task/server/controllers/userControllers.js:68:48)","    at Layer.handle [as handle_request] 
      (/var/task/server/node_modules/express/lib/router/layer.js:95:5)","    at next 
      (/var/task/server/node_modules/express/lib/router/route.js:144:13)","    at Route.dispatch 
      (/var/task/server/node_modules/express/lib/router/route.js:114:3)","    at Layer.handle [as handle_request] 
      (/var/task/server/node_modules/express/lib/router/layer.js:95:5)","    at /var/task/server/node_modules/express/lib/router/index.js:284:15","    at Function.process_params 
      (/var/task/server/node_modules/express/lib/router/index.js:346:12)","    at next 
      (/var/task/server/node_modules/express/lib/router/index.js:280:10)","    at Function.handle 
      (/var/task/server/node_modules/express/lib/router/index.js:175:3)","    at router 
      (/var/task/server/node_modules/express/lib/router/index.js:47:12)"]},"promise":{},"stack":
      ["Runtime.UnhandledPromiseRejection: TypeError: Cannot read properties of undefined (reading 'id')","    at process.<anonymous> (file:///var/runtime/index.mjs:1276:17)","   
      at process.emit (node:events:529:35)","    
      at emit (node:internal/process/promises:149:20)","   
      at processPromiseRejections (node:internal/process/promises:283:27)","    
      at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"]}
      
      Unknown application error occurred
      
      Runtime.Unknown
      

      I think the main problem here is the user related to Passport's authentication. When I log in, the /signin route's log says that my user is authenticated and shows me the object but disappears when is redirected to the dashboard, making req.user undefined and not authenticated.

      Why does this happens on Vercel when in my local host does work perfectly?

      This is also my Passport strategy:

      const passport = require('passport')
      const LocalStrategy = require('passport-local').Strategy
      const User = require('../models/User')
      const bcrypt=require('bcrypt')
      
      module.exports.start = async(passport)=>{
        passport.use(new LocalStrategy({
          usernameField: 'email', 
          passwordField: 'password', 
        },
        async (email, password, done) => {
      
            try {
              const user = await User.findOne({ email });
              if (!user) {
                return done(null, false, { message: 'User not found' });
              }
               const isPasswordValid = await bcrypt.compare(password, user.password);
              
              if (!isPasswordValid) {
                return done(null, false, { message: 'Contraseña incorrecta' });
              }else{
                //console.log(user)
                 return done(null, user);
              }
        
            } catch (error) {
              return done(error);
            }
          }
        ));
        
        passport.serializeUser((user, done) => {
          console.log("serialized", user)
          done(null, user._id);
        });
        
        passport.deserializeUser(async (id, done) => {
          console.log("deserialized")
          console.log(id)
          try {
            const user = await User.findById({_id : id});
            done(null, user);
          } catch (error) {
            done(error);
          }
        })
      }
      

      I call it in this way on index.js:

      const passport = require('passport')
      const local = require('./config/passport')
      const flash = require('connect-flash')
      
      local.start(passport)
      app.use(passport.initialize())
      app.use(passport.session())
      app.use(flash())
      


      Process URL in the same way as Express does to get request parameters in a get command

      I want to be able to get the parameters from a uri string in the exact same way as Express does. I can do it with regex or other string methods, but then I have a risk that it is not interpretted the same way as Express. I would prefer a way that even if Express has a bug and a URI gets interpretted wrongly, that the function does that as well.

      I have Ajax commands that execute a specific get/post command and use the referer to know where they originated eg. req.headers.referer which would be something like http://localhost:3000/data/theme-chalkboard/black

      I have a non standard get in Express, for example:

      app.get('/data/theme-:theme/:piece', (req, res, next) => {
      // server code
      }
      

      Where the parameters in question are:

      {
        theme: "chalkboard",
        piece: "black"
      }
      

      However I have other parts that also have similar incorporated variables within the route. The reason for this is because the route gets dynamically created and updated as the website is used by oneself and others. Because of this, I might need information on one page to be able to query it correctly on another.

      From the referer I get a URI string eg.

      http://localhost:3000/data/theme-chalkboard/black 
      or 
      http://localhost:3000/hg-1000
      

      Then I want to be able to first determine which of the following get commands it matches:

      app.get('/data/theme-:theme/:piece', (req, res, next) => {});
      or 
      app.get('/hg-:gameId', (req, res) => {});
      

      And lastly get the parameters in a JSON format, eg.

      {
        "theme": "chalkboard",
        "piece": "black"
      }
      

      or

      {
        "gameId": "1000"
      }
      

      If I have to add custom code to first determine each type of command and then to get the parameters as well it is still fine, as this would be similar to the regex idea that I am currently considering. The problems with this solution is that my regex might not always interpret the URI exactly like Express would and I would have to do this for each of the routes that could get a command. I would prefer a generic solution that acomplishes this if it exists.



      2024-01-20

      grep - RegEx multiple-criteria select

      Given a file containing this string:

      IT1*1*EA*VN*ABC@SAC*X*500@REF*ZZ*OK@IT1*1*CS*VN*ABC@SAC*X*500@REF*ZZ*BAR@IT1*1*EA*VN*ABC@SAC*X*500@REF*ZZ*BAR@IT1*1*EA*VN*ABC@SAC*X*500@REF*ZZ*OK@
      

      The goal is to extract the following:

      IT1*1*EA*VN*ABC@SAC*X*500@REF*ZZ*BAR@
      

      With the criteria being:

      1. The IT1 "line" must contain *EA*
      2. The REF line must contain BAR

      Some notes for consideration:

      • "@" can be thought of as a line break
      • A "group" of lines contains lines starting with IT1 and ending with REF
      • I am running GNU grep 3.7.

      The goal is to select the "group" of lines meeting the criteria.

      I tried the following:

      grep -oP "IT1[^@]*EA[^@]*@.*REF[^@]*BAR[^@]*@" file.txt
      

      But it captures characters from the beginning of the example.

      Also tried to use lookarounds:

      grep -oP "(?<=IT1[^@]*EA[^@]*@).*?(?=REF[^@]*BAR[^@]*@)" file.txt
      

      But my version of grep returns:

      grep: lookbehind assertion is not fixed length



      2024-01-19

      Azure WebJobs CD ereasing wwwroot content

      I'm publishing 2 web jobs to the respective paths:

      Azure AppService Configuration

      But, every time, the content inside site\wwwroot is erased, and I have an API project published there, so, every time I need to republish the API after.

      I can't find a solution anywhere about this, why is this happening?

      This is my web jobs CD:

      WebJob Cd Tasks

      I was expecting having to republish my API every time I publish my web job.



      Why am I getting" invalid as a react child" error?

      I'm encountering an error in React saying 'Objects are not valid as a React child (found: object with keys {})'. This occurs during the rendering phase, where React is expecting elements or an array of elements but is instead receiving an object. The error trace includes functions like reconcileChildFibers, updateHostComponent, and performUnitOfWork. How can I resolve this issue so that React correctly renders the intended components or data?

      I think the issue is with the below code:

      import React from "react";
      const Select = ({ name, label, options, error, ...rest }) => {
        return (
          <div className="form-group">
            <label htmlFor={name}>{label}</label>
            <select {...rest} name={name} id={name} className="form-control">
              <option value="" />
              {options.map((option) => (
                <option key={option._id} value={option._id}>
                  {option.name}
                </option>
              ))}
            </select>
            {error && <div className="alert alert-danger">{error}</div>}
          </div>
        );
      };
      
      export default Select;
      
      

      I removed the {} from the map function hoping it would resolve the issue but it did not.



      2024-01-18

      Azure Pipeline for SonarCloud analysis using Gradle is successful but no results are published

      I have tried to analyze a Java repository, build using Gradle wrapper, and publish the results in my SonarCloud organization. I am using an Azure DevOps Pipeline for the build, however, I cannot see any results in the SonarCloud account, even though my pipeline build is successful. I am using Sonarcloud Prepare task, Sonarcloud Run Analysis and Sonarcloud Publish, as well as Gradle build step with following settings:

      • task: Gradle@2 inputs: gradleWrapperFile: 'gradlew' options: '-P offlineVersion=$(Build.SourceBranchName)-SNAPSHOT' tasks: 'publish' publishJUnitResults: true testResultsFiles: '**/TEST-*.xml' javaHomeOption: 'JDKVersion' jdkVersionOption: '1.8' gradleOptions: '-Xmx3072m' env: RUNONCI: 'true' REPO_USER_NAME: '$(RepoUserName)' REPO_USER_PASSWD: '$(RepoUserPasswd)' SNAPSHOTURL:

      Could you please help me out?

      I do not receive any error, only 2 warnings:

      • When using Maven or Gradle, don't use the analyze task but instead tick the 'SonarQube' option in the Maven/Gradle task to run the scanner as part of the build.
      • No analyses found in this build! Please check your build configuration.

      My goal is to see the analysis results in the SonarCloud account. I have checked and the service connection I am using is verified and correct.



      2024-01-15

      queryClient.setQueryData() updating issues and inconsistences in next js application

      I am using @tanstack/react-query in my frontend application and I really enjoy it. I also use it as the state manager for everything that has to do with async network calls and data fetching. Right now, I am building a kanban board with drag and drop functionality and we intend to preserve the columns and the items arrangement to the backend whenver the user performs a drag and drop action.

      After every drag and drop action, I manipulate the array and update the indices of the columns or items being moved. Since I want the action to be instantaneous even before I get a response from the server, I modify the state on the frontend and display the updated data arrangement to mimic an instantaneous update to the user.

      To achieve this using react query, I get my query cache using queryClient.getQueryData(queryKey), manipulate the cache and then update the cache using queryClient.setQueryData(queryKey, updatedData). The issue I have is that it doesn't work and I don't understand why.

      Sometimes, it works and sometimes it doesn't. I am so confused and don't know why.

      const queryKey = ['fetchLists'];
      const { data, isLoading } = useFetchBoard(queryKey);
      const [board, setBoard] = useState<TBoard | null>(null);
      
      const queryClient = useQueryClient();
      
      const updateQueryData = (updatedBoard: TBoard) => {
        queryClient.setQueryData(queryKey, updatedBoard);
      }
      
      const getExistingBoard = (): TBoard => {
        return queryClient.getQueryData(queryKey) as TBoard
      };
      
      
      const handleOnDragEnd = () => {
       // Get existing board from query
       const existingBoard = getExistingBoard();
      
       if(existingBoard) {
        const newBoard = performIndicesChange(existingBoard, 1, 4);
      
        // Update queryData. This doesn't work.
        updateQueryData(newBoard);
      
        //Perform a setState. This weirdly works even though I am not using the `board` variable from // useState to populate my KanbanBoard
        setBoard(newBoard)
       }
      }
      
      return (
        <div>
          <KanbanBoard data={data} />
        </div>
      
      )
      
      
      

      Why does react query not detect the updated data to allow react rerender the frontend? Why does setBoard work even when I am not using board



      2024-01-12

      AppAttest -- Can a Swift program that uses DCAppAttestService be run on Linux?

      I need to be able to run the code that issues an Apple attest but preferably Linux. Or, at the very least, on an MacOS VPS.

      I expect there to be new customers daily, therefore this code will be run regularly, for each new client. As such, using an Apple physical device for this, if indeed required, will inconvenient:

      import DCAppAttest
      
      func generateKeyAndAttestation() {
          guard let attestationKey = DCAppAttestService.shared.generateKey() else {
              print("Error generating attestation key.")
              return
          }
      
          // Generate a nonce (you may need to use a more secure source for your actual use case)
          let nonce = Data.random(count: 32)
      
          // Prepare the data to be attested
          let dataToAttest = "Data to be attested".data(using: .utf8)!
      
          // Concatenate nonce and data
          var attestationData = nonce
          attestationData.append(dataToAttest)
      
          // Use DCAppAttestService to attest the data
          guard let attestation = DCAppAttestService.shared.attestData(attestationData, withKey: attestationKey) else {
              print("Error generating attestation.")
              return
          }
      
          // Print or use the attestation key and the resulting attestation
          print("Attestation Key: \(attestationKey)")
          print("Attestation: \(attestation)")
      }
      

      I haven't found a clear answer as to whether or not DCAppAttestService can be run only on MacOS/iOS or any other Apple OS?

      And whether or not it has to be a physical Apple device or will any VPS running one of the latest OSX do too?

      enter image description here

      I'm aware that validation, verification of attest-s can, indeed, be run on Linux. This will the 2nd step. My question, however, about the code that issues, generates attest-s initially -- the 1st step.


      https://developer.apple.com/documentation/devicecheck/dcappattestservice



      2024-01-11

      Reading a fixed width file with Rust

      I am trying to read a fixed width file with Rust, with the goal to load the data into a Polars dataframe, however, I can't parse the file correctly.
      I am trying to use the fixed_width crate as polars lacks the utility to parse such files.
      Unfortunately, the fixed_width documentation does not have any example where a file is read, all the examples read data from a string...

      Here is my failed attempt (the commented code works as it is a copy-paste from the docs) and obviously, the file contains same data as the string:

      use serde::{Serialize, Deserialize};
      use fixed_width::{FixedWidth, FieldSet, Reader};
      
      
      fn main() {
          let r_file = "path/to/file.r01";
          // let data = String::from("R   5001.00   1001.00                          513777.5 2093285.7   0.0\nR   5001.00   1002.00                          513786.6 2093281.6   0.0\nR   5001.00   1003.00                          513795.7 2093277.4   0.0\nR   5001.00   1004.00                          513708.8 2093273.3   0.0\n");
      
          #[derive(Serialize, Deserialize, Debug)]
          struct SpsRecord {
              pub line: f32,
              pub point: f32,
              pub easting: f32,
              pub northing: f32
          }
      
          impl FixedWidth for SpsRecord {
              fn fields() -> FieldSet {
                  FieldSet::Seq(vec![
                      FieldSet::new_field(1..11).name("line"),
                      FieldSet::new_field(11..21).name("point"),
                      FieldSet::new_field(46..55).name("easting"),
                      FieldSet::new_field(55..65).name("northing")
                  ])
              }
          }
      
          impl SpsRecord {
              fn from_file(path: &str) -> Result<Vec<Self>, fixed_width::Error> {
                  let mut reader = Reader::from_file(path)?;
                  let records: Result<Vec<Self>, fixed_width::Error> = reader
                      .byte_reader()
                      .filter_map(Result::ok)
                      .map(|bytes| fixed_width::from_bytes(&bytes))
                      .collect();
                  match records {
                      Ok(records) => Ok(records),
                      Err(err) => Err(fixed_width::Error::from(err))
                  }
              }
      
              // fn from_string(data: &str) -> Result<Vec<Self>, fixed_width::Error> {
              //     let mut reader = Reader::from_string(data).width(72);
              //     let records: Result<Vec<Self>, fixed_width::Error> = reader
              //         .byte_reader()
              //         .filter_map(Result::ok)
              //         .map(|bytes| fixed_width::from_bytes(&bytes))
              //         .collect();
              //     match records {
              //         Ok(records) => Ok(records),
              //         Err(err) => Err(fixed_width::Error::from(err))
              //     }
              // }
          }
      
          println!("Reading {}...", r_file);
          match SpsRecord::from_file(r_file) {
              Ok(records) => {
                  for record in records {
                      println!("{:?}", record);
                  }
              }
              Err(err) => {
                  eprintln!("{:#?}", err);
              }
          }
      
          // println!("Reading\n{}...", data);
          // match SpsRecord::from_string(&data) {
          //     Ok(records) => {
          //         for record in records {
          //             println!("{:?}", record);
          //         }
          //     }
          //     Err(err) => {
          //         eprintln!("{:#?}", err);
          //     }
          // } 
      }
      

      The code runs, prints the "Reading..." line and does absolutely nothing, so I don't know where to look.



      2024-01-10

      How do you idiomatically implement a nontrivial typestate pattern in Rust? [closed]

      I'm trying to build the FSM of a simple CPU, which consists of about 40 states, with loops, and many conditionals across many variables of the overall CPU state. This FSM operates like a simple Turing Machine; reading memory cells (think vector of u16), computing some results, and storing them back into memory.

      My question is: how is this implemented idiomatically in Rust?

      The way I've considered it, you would do something like this:

      1. Have a base enum representing the states.
      2. Have another enum for each state which represents transitions (but maybe all in the same enum?).
      3. Somehow you'd have to access the CPU state (value of all the different registers etc) to know how to emit the next state transition, but to be efficient about it, you'd need to be able to pass different subsets of the CPU state, yet somehow only mutate a single copy that represents the CPU state after the computation.
      4. You could probably build a vector of "state diffs" which you could apply all at once when you reach certain states, which would also be good for implementing a simple debugger.

      I'm new to rust, so modelling these sort of complex compositional type problems still doesn't come very naturally.

      If you want to see how things work so far, I have a repo here: https://github.com/ijustlovemath/lrc3



      2024-01-09

      MacOs Tkinter - App terminating 'Invalid parameter not satisfying: aString != nil'

      When im launching my app via CLI, it works without issue

      ./org_chart.app/Contents/MacOS/org_chart

      however when I launch via double click I met with the error

      *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: aString != nil'
      

      I used py2app to build the app. Im not sure where to begin debugging this, if someone could point me in the right direction?

      Thanks for your help!

      here's the full code for the small app

      import os, shutil
      import tkinter as tk
      from tkinter import filedialog, messagebox, Tk, Canvas, Entry, Text, Button, PhotoImage
      from tkinter import font as tkFont
      
      def build_org_chart():
      
          print("im making a chart")
        
          return 'Done chart created!'
      
      if __name__ == "__main__":
          window = Tk()
          window.title("Org Chart Spreadsheet Generator")
      
          # Variables to store file paths
          window.geometry("1012x506")
          window.configure(bg = "#00403D")
      
          # Define the font properties
          my_font = tkFont.Font(family="Montserrat SemiBold", size=16, weight="normal")
      
          canvas = Canvas(
              window,
              bg = "#00403D",
              height = 506,
              width = 1012,
              bd = 0,
              highlightthickness = 0,
              relief = "ridge"
          )
      
          canvas.place(x = 0, y = 0)
          canvas.create_rectangle(
              308.0,
              0.0,
              1012.0,
              506.0,
              fill="#FFFFFF",
              outline="")
      
          canvas.create_text(
              320.0,
              18.0,
              anchor="nw",
              text="Org Chart",
              fill="#000000",
              font=("Montserrat Bold", 64 * -1)
          )
      
          window.resizable(False, False)
          window.mainloop()
      

      Also now my app is so small its still crashing im thinking it could be something in the setup file too so ive added that code below

      import os
      from setuptools import setup
      
      def list_files(directory):
          base_path = os.path.abspath(directory)
          paths = []
          for root, directories, filenames in os.walk(base_path):
              for filename in filenames:
                  # Exclude .DS_Store files if you are on macOS
                  if filename != '.DS_Store':
                      paths.append(os.path.join(root, filename))
          return paths
      
      # Your assets folder
      assets_folder = 'assets'
      
      # Listing all files in the assets folder
      assets_files = list_files(assets_folder)
      
      APP = ['org_chart_min.py']
      DATA_FILES = [('assets', assets_files)]
      OPTIONS = {
          'argv_emulation': True,
      
          'packages': ['pandas', 'openpyxl','xlsxwriter'],
              'plist': {
              'CFBundleName': '_org_chart',
              'CFBundleDisplayName': ' Org Chart',
              'CFBundleGetInfoString': "Create a spreadsheet that populates our Lucid org chart template",
              'CFBundleIdentifier': 'com.yourdomain.orgchart',
              'CFBundleVersion': '0.1',
              'CFBundleShortVersionString': '0.1',
              'NSRequiresAquaSystemAppearance': True
          },
          'iconfile': 'org_chart.icns',
      }
      
      setup(
          app=APP,
          data_files=DATA_FILES,
          options={'py2app': OPTIONS},
          setup_requires=['py2app'],
      )
      


      2024-01-07

      Login redirects in Django

      I have a auth system with django-allauth library, and i have some login, logout functionally implemented and it works fine. But I want to implement a profile page on my own. With this I'm so confusing right with Django redirects.

      I have a class based view called HomeRequestHandler that inherits a LoginRequiredMixin:

      from django.contrib.auth.mixins import LoginRequiredMixin
      from django.views.generic import TemplateView
      
      
      class HomeRequestHandler(LoginRequiredMixin, TemplateView):
          template_name = "home.html"
      

      And in my urls i just call it to "":

      from django.views.generic import TemplateView
      from django.urls import path
      from . import views
      
      urlpatterns = [
          path("", views.HomeRequestHandler.as_view(), name="home"),
          path("profile/", TemplateView.as_view(template_name="account/profile.html"), name="profile"),
      ]
      

      In my settings.py, I have a constant for LOGIN_REDIRECT_URL:

      LOGIN_REDIRECT_URL = reverse_lazy('profile')
      

      When I try login, I am redirected to "/" even with LOGIN_REDIRECT_URL defined. But if I change one thing in my view:

      from django.contrib.auth.mixins import LoginRequiredMixin
      from django.views.generic import TemplateView
      
      
      class HomeRequestHandler(LoginRequiredMixin, TemplateView):
          template_name = "home.html"
          redirect_field_name = "redirect_to"
      

      It change my url http://localhost:8000/accounts/login/?next=/ to http://localhost:8000/accounts/login/?redirect_to=/ and now the constant works normally, why???



      2024-01-06

      Telerik Blazor responsive grid

      i'm using telerik blazor grid. i tried adaptive grid layout example Reference link Telerik Adaptive Grid but it does provide responsiveness on listing of elements. For example if there is static grid like one row with two columns, one column have any image and second column any text or form. is there any way to make responsive grid for all devices. image



      2024-01-04

      Access violation when calling stbi_load()?

      The following function throws an access violation exception on line with stbi_load, but I don't see any reasons for it

      unsigned int TextureFromFile(const char* path, const string& directory, bool gamma)
      {
      
          std::string filename = std::string(path);
          filename = directory + '/' + filename;
      
          unsigned int textureID;
          glGenTextures(1, &textureID);
      
          int width;
          int height;
          int nrComponents;
          unsigned char* data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
          if (data)
          {
              GLenum format;
              if (nrComponents == 1)
                  format = GL_RED;
              else if (nrComponents == 3)
                  format = GL_RGB;
              else if (nrComponents == 4)
                  format = GL_RGBA;
      
              glBindTexture(GL_TEXTURE_2D, textureID);
              glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
              glGenerateMipmap(GL_TEXTURE_2D);
      
              glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
              glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
              glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
              glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      
              stbi_image_free(data);
          }
          else
          {
              std::cout << "Texture failed to load at path: " << path << std::endl;
              stbi_image_free(data);
      
          }
          return textureID;
      
      
      }
      

      So, I tried messing with variables. I initialized width, height, nrComponents with some values, but to my surprise I've got another access violation exception, now for these variables, which seems really strange.



      Livewire: Bind refresh not working from server to client for input type

      I have a laravel livewire (v3) component that contains an input field. I'm trying to get the displayed field to refresh after the bound (bind-ed) property is updated server-side.

      Livewire component:

      <?php
      
      namespace App\Livewire\MyNamespace;
      
      use Livewire\Component;
      
      class Create extends Component
      {
      
          public function rules()
          {
              return [
                  'doSomething' => 'required',
              ];
          }
      
          public $doSomething = '';
      
          public function add()
          {
              $this->doSomething = 'Welcome';
              $this->dispatch('$refresh');
          }
      
          public function render()
          {
              return view('livewire.create');
          }
      }
      

      The view is simple:

      <div>
      <button class="btn btn-primary" wire:click="add">Press me</button>
      <input type="text" wire:model.live="doSomething">
      Label: 
      </div>
      

      When I press the button, the input field displayed isn't updated, but the text is rendered in the label - any ideas? Does an input binding only work one way, client to server?



      2024-01-03

      Make a Strong Wordlist white special character with python

      I wanted to make a password list For Brute Forceand . I need your help.

      An 8-digit password list where the characters 4, 8 and (p or P) should be used, and it consists only of numbers and lowercase and uppercase characters, and there are no special characters in it. Thanks for your advice on what software to use in Python and Windows to create this password list. tanks

      I still haven't found a way to use special characters for this.