Thursday, September 23, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Out of memory issue while running query in table with jsonb field in Postgresql-13

Posted: 23 Sep 2021 08:16 AM PDT

**QUERY:**   *SELECT first_table.claimno,      first_table.claseq,      first_table.clientname,      first_table.linseq,      first_table.batchdate,      first_table.deny_proc_code,      first_table.allow_proc_code,      first_table.predictions,      first_table.score,      second_table.deleted,      second_table.review     FROM (( SELECT t.id,              (t.data -> 'claimno'::text) AS claimno,              (t.data ->> 'claseq'::text) AS claseq,              (t.response ->> 'clientcode'::text) AS clientname,              to_timestamp((((t.response ->> 'timestamp'::text))::numeric)::double precision) AS batchdate,              (o.value ->> 'linseq'::text) AS linseq,              (o.value ->> 'deny_proc_code'::text) AS deny_proc_code,              (o.value ->> 'allow_proc_code'::text) AS allow_proc_code,              (k.value ->> 'action'::text) AS predictions,              ((k.value ->> 'score'::text))::numeric AS score             FROM dummy t,              LATERAL jsonb_array_elements((t.response -> 'lines'::text)) o(value),              LATERAL jsonb_array_elements(                  CASE                      WHEN (jsonb_typeof((o.value -> 'flags'::text)) ~~ 'array'::text) THEN (o.value -> 'flags'::text)                      ELSE '[{"key": "team_q:"}]'::jsonb                  END) k(value)) first_table       JOIN ( SELECT (k.value ->> 'deleted'::text) AS deleted,              (k.value ->> 'review'::text) AS review,              (k.value ->> 'claseq'::text) AS claseq,              (t.data -> 'claimno'::text) AS claimno,              (k.value ->> 'linseq'::text) AS linseq             FROM dummy t,              LATERAL jsonb_array_elements((t.data -> 'lines'::text)) o(value),              LATERAL jsonb_array_elements(                  CASE                      WHEN (jsonb_typeof((o.value -> 'flags'::text)) ~~ 'array'::text) THEN (o.value -> 'flags'::text)                      ELSE '[{"key": "team_q:"}]'::jsonb                  END) k(value)) second_table ON (((first_table.claseq = second_table.claseq) AND (first_table.linseq = second_table.linseq))));*  

ERROR MESSAGE: postgres=# WARNING: terminating connection because of crash of another server process DETAIL: The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory. HINT: In a moment you should be able to reconnect to the database and repeat your command. server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. The connection to the server was lost. Attempting reset: Failed

$dmsg [10881799.496693] [41883] 1983985914 41883 28630 272 59 0 0 sshd [10881799.497029] [41892] 1983985914 41892 29461 145 16 0 0 bash [10881799.497373] [42010] 0 42010 29173 304 63 0 0 sshd [10881799.497698] [42237] 0 42237 54438 477 63 0 0 dzdo [10881799.498037] [42238] 0 42238 49670 189 55 0 0 su [10881799.498366] [42239] 26 42239 29983 145 17 0 0 bash [10881799.498707] [42286] 1983984643 42286 28630 263 59 0 0 sshd [10881799.499036] [42287] 0 42287 29173 305 61 0 0 sshd [10881799.499384] [42297] 26 42297 46729 259 45 0 0 psql [10881799.499735] [42298] 26 42298 105479 1044 83 196 0 postmaster [10881799.500076] [42307] 1983984643 42307 28630 276 58 0 0 sshd [10881799.500448] [42308] 1983984643 42308 29461 109 16 0 0 bash [10881799.500796] [42319] 1983984643 42319 6061 141 18 0 0 sftp-server [10881799.501171] [42663] 0 42663 27023 24 10 0 0 tail [10881799.501538] [42794] 0 42794 30815 339 63 0 0 sshd [10881799.501896] [42830] 0 42830 30815 325 61 0 0 sshd [10881799.502277] [42831] 0 42831 29992 135 16 0 0 bash [10881799.502656] [43249] 0 43249 29173 305 62 0 0 sshd [10881799.503026] [43358] 0 43358 94257 4873 151 0 -900 rhsmd [10881799.503412] [43474] 1983985914 43474 28630 297 58 0 0 sshd [10881799.503793] [43484] 1983985914 43484 29461 129 15 0 0 bash [10881799.504163] [43832] 89 43832 23066 299 47 0 0 cleanup [10881799.504564] [43833] 89 43833 23030 297 48 0 0 trivial-rewrite [10881799.504957] [43840] 89 43840 23081 273 46 0 0 smtp [10881799.505342] [43927] 0 43927 54438 480 60 0 0 dzdo [10881799.505716] [43934] 0 43934 49670 192 55 0 0 su [10881799.506103] [43935] 26 43935 29983 146 16 0 0 bash [10881799.506480] [43998] 26 43998 46729 259 44 0 0 psql [10881799.506860] [43999] 26 43999 105475 1331 99 195 0 postmaster [10881799.507244] [44569] 26 44569 104789 807 77 244 0 postmaster [10881799.507616] Out of memory: Kill process 37366 (postmaster) score 474 or sacrifice child [10881799.508019] Killed process 37366 (postmaster), UID 26, total-vm:5169780kB, anon-rss:4639752kB, file-rss:656kB, shmem-rss:133972kB -bash-4.2$

android- support library BottomNavigationView not showing icons

Posted: 23 Sep 2021 08:16 AM PDT

I'm using android support design widget BottomNavigationView for making my bottom navigation items. It doesn't show the icons but it shows text and working fine. I am using the support library version com.google.android.material:material:1.4.0 and my xml code for bottomnavigationView is

<androidx.constraintlayout.widget.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:background="@color/white"      tools:context=".MainActivity">        <androidx.appcompat.widget.Toolbar          android:id="@+id/toolbar"          android:layout_width="match_parent"          android:layout_height="?attr/actionBarSize"          android:background="@drawable/gradient_bg"          app:layout_constraintEnd_toEndOf="parent"          app:layout_constraintStart_toStartOf="parent"          app:layout_constraintTop_toTopOf="parent">            <LinearLayout              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_marginStart="@dimen/_30sdp">                <ImageView                  android:layout_width="@dimen/_55sdp"                  android:layout_height="@dimen/_35sdp"                  android:src="@drawable/logo1" />            </LinearLayout>            <TextView              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_marginStart="@dimen/_54sdp"              android:gravity="center"              android:text=""              android:textColor="@color/white"              android:textSize="@dimen/_12sdp" />      </androidx.appcompat.widget.Toolbar>        <FrameLayout          android:id="@+id/container"          android:layout_width="match_parent"          android:layout_height="0dp"          app:layout_constraintBottom_toTopOf="@+id/layout"          app:layout_constraintEnd_toEndOf="parent"          app:layout_constraintStart_toStartOf="parent"          app:layout_constraintTop_toBottomOf="@+id/toolbar" />        <LinearLayout          android:id="@+id/layout"          android:layout_width="match_parent"          android:layout_height="@dimen/_45sdp"          android:layout_weight="0.90"          android:background="@color/app_col1"          app:layout_constraintBottom_toBottomOf="parent"          app:layout_constraintEnd_toEndOf="parent"          app:layout_constraintHorizontal_bias="0.5"          app:layout_constraintStart_toStartOf="parent"          android:gravity="center"          android:orientation="vertical">            <com.google.android.material.bottomnavigation.BottomNavigationView              android:id="@+id/bottom_nav_view"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:background="@color/app_col1"              app:itemIconTint="@color/white"              app:labelVisibilityMode="labeled"              android:layout_gravity="center"              android:theme="@style/Theme.App"              app:itemTextColor="@drawable/tab_color"              app:menu="@menu/bottom_navigation_menu"/>        </LinearLayout>    </androidx.constraintlayout.widget.ConstraintLayout>  

my menu xml code is below

<menu xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto">      <item          android:id="@+id/page_1"          android:enabled="true"          android:iconTint="@drawable/ic_baseline_home_24"          app:showAsAction="ifRoom"          android:title="Home"/>      <item          android:id="@+id/page_2"          android:iconTint="@drawable/ic_baseline_home_24"          app:showAsAction="withText"          android:title="Category"/>      <item          android:id="@+id/page_3"          app:showAsAction="ifRoom"          android:iconTint="@drawable/user"          android:title="Profile"/>  </menu>  

How can I solve this issue?..Thanks in advance.

Problem with postback timeout with web service c#

Posted: 23 Sep 2021 08:16 AM PDT

I have a problem with calling a web service method during postback. This method request about 10 minutes for the answer after this i need to do a javascript with script manager declaration. This javascript function isn't execute properly. There is any timeout in page load or in postback waiting? I've tried with asyncpostbacktimeout but it doesn't work for me.

FormControlProps.isInvalid?: boolean | undefined

Posted: 23 Sep 2021 08:16 AM PDT

I am trying to create a form using the React-Bootstrap form with formik and Yup for validation. I am getting typescript errors in invalid props, Type 'string | undefined' is not assignable to type 'boolean | undefined'. Type 'string' is not assignable to type 'boolean undefined'.ts(2322). Here is my code,

This is my formik,

  const formik = useFormik({      initialValues: {        title: "",        description: "",        language: "",        code: "",      },      validationSchema : PostSchema,      onSubmit: (values: Post, { resetForm }) => {        dispatch(createPost(values));      },    });  

This is my form,

<Form onSubmit={formik.handleSubmit}>    <Form.Group controlId="title">      <FormLabel>Title</FormLabel>        <Form.Control         type="text"         placeholder="Enter title"         value={formik.values.title}         onChange={formik.handleChange}         isInvalid={formik.errors.title}         />            <Form.Control.Feedback type="invalid">              {formik.errors.title}            </Form.Control.Feedback>     </Form.Group>          <Form.Group className="pt-3" controlId="description">            <FormLabel>Description</FormLabel>            <Form.Control              style={{ height: "100px" }}              as="textarea"              placeholder="Enter Code description"              value={formik.values.description}              onChange={formik.handleChange}              isInvalid={formik.errors.desc}            />          </Form.Group>          <Form.Control.Feedback type="invalid">            {formik.errors.description}          </Form.Control.Feedback>          <Form.Group className="mt-3" controlId="language">            <FormLabel>Select Language</FormLabel>            <Form.Control              as="select"              onChange={formik.handleChange}              isInvalid={formik.errors.language}            >              <option value="">Select Any language</option>              {allLang.map((item) => {                return (                  <option key={item._id} value={item.language}>                    {item.language}                  </option>                );              })}            </Form.Control>            <Form.Control.Feedback type="invalid">              {formik.errors.language}            </Form.Control.Feedback>          </Form.Group>          <Form.Group className="pt-3 mb-3" controlId="code">            <FormLabel>Code</FormLabel>            <Form.Control              as="textarea"              style={{ height: "200px" }}              placeholder="Enter Code"              value={formik.values.code}              onChange={formik.handleChange}              isInvalid={formik.errors.code}            />            <Form.Control.Feedback type="invalid">              {formik.errors.code}            </Form.Control.Feedback>          </Form.Group>          <Button variant="primary" type="submit">            Save Snippet          </Button>        </Form>  

Here is my schema and interface,

export interface Post {    _id?: string;    title?: string;    description?: string;    language?: string;    code?: string;    userId?: string;  }    export const PostSchema = Yup.object().shape({    title: Yup.string().required("Required"),    description: Yup.string().required("Required"),    language: Yup.string().required("Required"),    code: Yup.string().required("Required"),  });  

If I am commenting out invalid prop, everything is working fine but validation message is not appearing, it is basically saying, Type 'string | undefined' is not assignable to type 'boolean | undefined'.ts(2322) FormControl.d.ts(18, 5): The expected type comes from property 'isInvalid' which is declared here on type 'IntrinsicAttributes & Omit<Pick<DetailedHTMLProps<TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>, "key" | keyof TextareaHTMLAttributes<...>> & { ...; }, BsPrefixProps<...> & FormControlProps> & BsPrefixProps<...> & FormControlProps & { ...; }'

Angular 8 problem with CORS in Chrome and in Production

Posted: 23 Sep 2021 08:16 AM PDT

as the title says, Two days ago Chrome has release the version 94.. and Now I'm having problems with CORS, but only in that version of chrome and in production environment. What can be the problem ?? It's only happening in Chrome, with that latest version and in production environment. I know that I can add a proxy, but I want to know wich can be the issue. Thanks in advance

Postman: POST request of nested JSON via form-data not working (while via raw-data ok)

Posted: 23 Sep 2021 08:16 AM PDT

I want to POST the following JSON-object via Postman:

{      "title": "test_title",      "date": "2021-12-31",      "attachments": [          {              "name": "test_attachment"          }      ]  }  

This works perfectly fine, when using Postman's raw input form for the request-body: I get a "201 Created"-response back.

However, when using the form-data to POST the data, I get the error "Invalid data. Expected a dictionary, but got str." (see also screenshot below) What am I doing wrong here? I tried all kind of other versions to enter the attachment-key:value pair but nothing worked so far enter image description here

Python list (and other objects) change when indexed inside a function

Posted: 23 Sep 2021 08:16 AM PDT

My (limited) understanding of Python is that objects defined outside a function should remain the same even if modified inside a function, i.e.

def fun():      i=1      return('done')    i=0  fun()  i==0 ## True  

However, lists (and other objects like numpy arrays) change when indexed inside a function:

def fun():      img[0] = img[0] + 100       return('done')    img = [0, 1]  fun()  img == [0, 1] ## False  

Obviously I am missing a core concept with respect to how global and local variables are handled inside functions but can't seem to find any information online. Could someone please explain why objects change inside functions when indexed. Also, could someone describe how to avoid this "feature" so that when I index objects (lists, arrays, etc...) within a function, I don't inadvertently change the objects defined outside that functions? Thanks!

Docker-compose image building error -> [Errno 2] No such file or directory on building

Posted: 23 Sep 2021 08:16 AM PDT

I have a microservice and I am trying to run it via docker-compose. You can see my directory structure below.

When I build that image inside GUI directory using docker build, It runs smoothly. But when I use docker-compose it gives this error:

[Errno 2] No such file or directory on building.

What is the problem here?

Directory Structure

my_project
|__docker-compose.yml
|__GUI
|____dockerfile
|____gui.py\

docker-compose.yml

version: "3"  services:    service_gui:      build:         context: .        dockerfile: ./GUI/dockerfile      ports:        - 8080:8080  

dockerfile

FROM continuumio/miniconda3  WORKDIR /app  COPY . .    RUN pip install dash  EXPOSE 8080  ENTRYPOINT [ "python","gui.py"]  

ValueError: You are trying to load a weight file containing 3 layers into a model with 4 layers

Posted: 23 Sep 2021 08:16 AM PDT

I am running the following code block:

model.add(LSTM(700, input_shape=(X_modified.shape[1], X_modified.shape[2]), return_sequences=True))  model.add(Dropout(0.2))  model.add(LSTM(700, return_sequences=True))  model.add(Dropout(0.2))  model.add(LSTM(700))  model.add(Dropout(0.2))  model.add(Dense(Y_modified.shape[1], activation='softmax'))    # load the network weights saved in the folder model_weights  filename = r'weight-06-0.9927.hdf5'  model.load_weights(filename)  model.compile(loss='categorical_crossentropy', optimizer='adam')    # define how model checkpoints are saved  filepath = r'weight-06-0.9927.hdf5-ctd20-{epoch:02d}-{loss:.4f}.hdf5'  checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')  callbacks_list = [checkpoint]  

I am receiving the following error:

  File "C:\Users\text.py", line 68, in <module>      model.load_weights(filename)      File "C:\Users\anaconda3\lib\site-packages\keras\engine\training.py", line 2361, in load_weights      hdf5_format.load_weights_from_hdf5_group(f, self.layers)      File "C:\Users\anaconda3\lib\site-packages\keras\saving\hdf5_format.py", line 688, in load_weights_from_hdf5_group      raise ValueError('You are trying to load a weight file '    ValueError: You are trying to load a weight file containing 3 layers into a model with 4 layers.  

The error is definitely regarding the weight file somehow, but I am not sure what needs to be done.

Python - Remove named index in multidimensional array

Posted: 23 Sep 2021 08:16 AM PDT

I build the following named array : array[userid][type] = 'value', where userid is a number, and type can be : email, name, phone... So an entry can be array[123][email]='123@xyz.com'

I want to delete email named index array[userid]["email"] (not only the value), if email value contains a specific word. So keep only array[123][name] and array[123][phone]

I see the following function, but it works with index numbers, not names : del employeeTable[][]

Can you help me to do that ?

Thank you

Is there a way to use React Hooks in a ReactJS.Net project

Posted: 23 Sep 2021 08:16 AM PDT

I have created an ASP.NET web Application(.NET framework) and have integrated React to it using ReactJS.NET package.

Now, when I try to use hooks in the functional components, it is not working. Can someone share any github sources or links where Hooks were used in ReactJS.NET project

Reload Form when select change

Posted: 23 Sep 2021 08:15 AM PDT

Is there a way to reload a form data in django when I change a select? I am trying to filter a select depending on the option selected in another without using ajax. What comes to mind is to use the __init__ of the form but I need to reload the form with the option selected in the first select and filtered the second.

Github generate Electron - how inject into main.js

Posted: 23 Sep 2021 08:15 AM PDT

I am using Github online to generate Electron binaries. Unfortunately the Electron app opens automatically with Developer Tools open. To avoid that, I would like to inject something like the following in the main.js:

   webPreferences: {     devTools: false     }  

As the main.js is loaded automatically I cannot do that directly. Is there any way to inject code into the main.js, or any other solution to avoid that Developer Tools open automatically on startup?

Count rows in csv file equal to a string value in Python

Posted: 23 Sep 2021 08:16 AM PDT

What is the easiest way to count the number of values in a single column that have a specific string value? (not using a for loop)

eg. Count all the 'Yes' responses not the 'No' responses and put the number into a variable

The dataset is [2764686 rows x 11 columns] The name of the column I'm interested in is ANSWER and I've imported:

import numpy as np  import pandas as pd  import matplotlib.pyplot as plt  

I've tried three avenues with no luck: 1.

active_bs3 = np.sum(dataset, axis=ANSWER)   print(active_bs3)  
active_bs4 = dataset.ANSWER.value_counts().Yes  print(active_bs4)  

(The above was based on an example I found on internet df.sex.value_counts().Male so I'd appreciate an explanation of why the above doesn't work)

3.

active_bs4 = dataset['ANSWER'].value_counts().Yes  print(active_bs4)  

How to rename all keys in dict?

Posted: 23 Sep 2021 08:16 AM PDT

I want to rename the dict keys in python. There are 2 keys 'Curry_Vegetables_Set1 (59).JPG131850' and 'Curry_Vegetables_Set1 (62).JPG104359' which i want to rename with replace1 value. Please help to rename. Below is the dict sample:

file = {'Curry_Vegetables_Set1 (59).JPG131850': {'filename': '1.5_Curry_Vegetables_59.jpg',    'size': 131850,    'regions': [{'shape_attributes': {'name': 'polygon',       'all_points_x': [510, 563,622,],       'all_points_y': [459,  523, 505,]},      'region_attributes': {'food': 'curry_vegetable'}}],    'file_attributes': {}},   'Curry_Vegetables_Set1 (62).JPG104359': {'filename': '1.5_Curry_Vegetables_62.jpg',    'size': 104359,    'regions': [{'shape_attributes': {'name': 'polygon',       'all_points_x': [471,490,528,],       'all_points_y': [496,476,493]},      'region_attributes': {'food': 'curry_vegetable'}}],    'file_attributes': {}},}  

I tried the code below,

for key,value in file.items():      name = key.split('.')      num = name[0].split('(')        image_num = num[1][:-1]         replace1 = '1.5_Curry_Vegetables_'+image_num+'.'+name[1]             # replace old keys with replace1      file[replace1] = file[key]  

but it gives error as:

RuntimeError: dictionary changed size during iteration  

Why arguments is given ...arguments in the arguments place like this?

Posted: 23 Sep 2021 08:16 AM PDT

My point is this:

function sum(...arguments) {      if (arguments.length === 1) {          const [firstArg] = arguments;          if (firstArg instanceof Array) {              return sum(...firstArg)          }      }  return arguments.reduce((a, b) => a + b);  }  

What is this ... are doing infront of arguments. And also please help me know that why const [firstArg] is given and how this is working. And please explain me instanceof in easy words. My native language is not english. Thank you so much.

How can I remove special characters in values that in list of Python dictionary

Posted: 23 Sep 2021 08:16 AM PDT

I am trying to remove all the '/api/1/employees/' and /api/1/seats/ from the python dictionary. What is the easiest way to do so. My dictionary is looking like this at the moment -

dict1 = {5051: ['/api/1/employees/4027', '5051', '/api/1/seats/19014'], 5052: ['/api/1/employees/4048', '5052', '/api/1/seats/19013'], 5053: ['/api/1/employees/4117', '5053', '/api/1/seats/19012'], 5054: ['/api/1/employees/15027', '5054', '/api/1/seats/9765']}  

I am expecting below dict

dict1 = {5051: ['4027', '5051', '19014'], 5052: ['4048', '5052', '19013'], 5053: ['4117', '5053', '19012'], 5054: ['15027', '5054', '9765']}  

Fatal error: Unexpectedly found nil while unwrapping an Optional value , firebase [duplicate]

Posted: 23 Sep 2021 08:16 AM PDT

I am trying to get the data from the firebase firestore and am using the SDWebImage package to display images and am getting the link(from dropbox) for that image from firebase but, when am force unwrapping the URL(string: imageUrl) I get an error saying

Fatal error: Unexpectedly found nil while unwrapping an Optional value

Please pardon me if it's a silly thing, I am new to programming.

import Foundation  import Firebase  class BlogManager: ObservableObject {    @Published var blogDataFirebase = [BlogData]()    private var db = Firestore.firestore()    init() {      fetchData()  }    func fetchData(){            db.collection("blog").addSnapshotListener { (snap, err) in          DispatchQueue.main.async {              if err != nil {                  print((err?.localizedDescription)!)                  return              } else {                  for i in snap!.documentChanges  {                                            let headline = i.document.get("headline") as? String ?? ""                      let subheadline = i.document.get("subheadline") as? String ?? ""                      let image = i.document.get("image") as? String ?? ""                      let body = i.document.get("body") as? String ?? ""                                                                  self.blogDataFirebase.append(BlogData(id: .init(), image: URL(string: image)!, headline: headline, subhadline: subheadline, body: body))                  }              }          }      }  }  

BlogManagerScreenshot

Firebase data model

firebase data model image

(Error 1366 SQL) Incorrect DECIMAL value '()'

Posted: 23 Sep 2021 08:16 AM PDT

I am developing a SP for a WindRose and when I try to run the SP, the SQL shows me this error.

(Error 1366 SQL) Incorrect DECIMAL value '()' for column "" at row -1

This problem appears after modifying the table where I collect the data. Before I made this SP for another table and it worked fine, but I had to change the table because this is the one receiving the live data.

CREATE TEMPORARY TABLE viento_count(angulo DECIMAL, val1 INT, val2 INT, val3 INT, val4 INT, val5 INT, val6 INT);            myloop: LOOP            IF angle > 350 THEN          LEAVE myloop;      END IF;        SET angle1 = angle;      SET angle2 = angle + 15;      SET angle_grf = angle + 15/2;                  SET valor1 = (SELECT COUNT(*) FROM vw_wind_counter WHERE speedy <= 3 AND (device_id = codigo_estacion) AND (data_time BETWEEN fecha_consulta_first_day AND fecha_consulta_last_day) AND direccion > angle1 AND direccion <= angle2);      SET valor2 = (SELECT COUNT(*) FROM vw_wind_counter WHERE speedy > 3 AND speedy <= 6 AND (device_id = codigo_estacion) AND (data_time BETWEEN fecha_consulta_first_day AND fecha_consulta_last_day) AND direccion > angle1 AND direccion <= angle2);      SET valor3 = (SELECT COUNT(*) FROM vw_wind_counter WHERE speedy > 6 AND speedy <= 9 AND (device_id = codigo_estacion) AND (data_time BETWEEN fecha_consulta_first_day AND fecha_consulta_last_day) AND direccion > angle1 AND direccion <= angle2);      SET valor4 = (SELECT COUNT(*) FROM vw_wind_counter WHERE speedy > 9 AND speedy <= 13 AND (device_id = codigo_estacion) AND (data_time BETWEEN fecha_consulta_first_day AND fecha_consulta_last_day) AND direccion > angle1 AND direccion <= angle2);      SET valor5 = (SELECT COUNT(*) FROM vw_wind_counter WHERE speedy > 13 AND speedy <= 18 AND (device_id = codigo_estacion) AND (data_time BETWEEN fecha_consulta_first_day AND fecha_consulta_last_day) AND direccion > angle1 AND direccion <= angle2);      SET valor6 = (SELECT COUNT(*) FROM vw_wind_counter WHERE speedy > 18 AND (device_id = codigo_estacion) AND (data_time BETWEEN fecha_consulta_first_day AND fecha_consulta_last_day) AND direccion > angle1 AND direccion <= angle2);            INSERT INTO viento_count SELECT angle_grf AS angulo, valor1 AS val1, valor2 AS val2, valor3 AS val3, valor4 AS val4, valor5 AS val5, valor6 AS val6;            SET angle = angle + 15;            END LOOP myloop;            SELECT * FROM viento_count;      DROP TEMPORARY TABLE viento_count;    

Currently, I get the data from a view (vw_wind_counter), where I CAST the speed and direction data to DECIMAL values. I've saw another threads about this problem, but many of them is about wrong data insertion.

Returning function correctly to use in other functions

Posted: 23 Sep 2021 08:15 AM PDT

Hi there I have a program that I have been using for about a year now with no issues however now I want to make some changes. There is some code that I would like to remove from main function and rather put it in its own function however i am not sure on the correct way to return 2 of the variables and use them in other functions I have tried a few ways already and this is the last resort. The variables i need to return are listads_buy_str and listads_sell_str. The point of this is to continuously re-read the google sheet instead of rerunning the program every time

    while i4a <= 2:      adlink = spreadsheet.cell(line1, 1).value      if adlink != '':          listads_buy.append(adlink)      line1 = line1 + 1      i4a +=1      listads_buy_str = listads_buy[0]  for ad in listads_buy[1:]:      if ad is not None:          listads_buy_str = listads_buy_str + ',' + str(ad)    i4a = 0  line1 = 18  listads_sell = []  while i4a <= 4:      adlink = spreadsheet.cell(line1, 1).value      if adlink != '':          listads_sell.append(adlink)      line1 = line1 + 1      i4a +=1      listads_sell_str = listads_sell[0]  for ad in listads_sell[1:]:      listads_sell_str = str(listads_sell_str) + ',' + str(ad)  

Not able to access the object type returned by a plsql function

Posted: 23 Sep 2021 08:16 AM PDT

I have created an object type as:

Create or replace type t1 as object   (    Account_id varchar2(20),    Account_date date);  

And wrote a function inside package body p1 that returns this object:

Function account_details(ac_id in account_table.account_id%type)  return t1 is    v_t1 t1;    Begin   Select t1(account_id,             Account_date)          Into v_t1          From account_table          Where account_id=ac_id;  Return v_t1;    End account_details;  

Package compiles successfully but when I try to execute the function and get values returned by it:

Select p1.account_details(1234) from dual;  

I get the output as:

[P1.t1]

How do I get the values of this object returned.This object will always have only one record returned from the function always.

Will I be able to get some help here?

How it is possible to perform a post request in this occasion? Laravel 5.8

Posted: 23 Sep 2021 08:16 AM PDT

I need to post the value of $i (class toClick) to controller. I can't figure out how. I am not that experienced and I've done it before using form, select, options and input but now I cant have a form as I need this section to be styled in a certain way.

The value of $i has a major role in loading the next page, I tried ajax and javascript but I've done plenty of mistakes as I am not experienced in any of them.

Blade:

    <div class="row mt-5 mr-5 ml-5">          <?php for($i=2021; $i>=1950; $i--){ ?>              <div class="col-3 d-flex flex-column align-items-center mb-3 mt-5">                  <div class="w-50 mb-5 rounded-circle" style="height: 150px;">                      <div class="bg-dark w-100 h-100 mb-5 border rounded-circle toClick" id="<?php echo $i ?>" onmouseover="onMouseOver(this)" onmouseout="onMouseOut(this)" onclick="onClick(this)">                          <img src='/imgs/jpg/years/<?php echo $i ?>.jpg' style="object-fit:cover" class="w-100 h-100 border rounded-circle">                      </div>                  </div>              </div>          <?php } ?>       </div>  

My ajax try:

$(document).ready(function(){      $(".toClick").click(function(event){          event.preventDefault();            var round = $(this).attr("id");          var rnd = currentNumOfRounds;          // alert(round+rnd);          $.ajax({              type: "POST",              url: "/searches/se_racestandingsround",              data: {round: round,               rnd: rnd,              token: _token              },               }          },            });      });  });  

My javascript progress so far:

function onClick(year){      var rnd = currentNumOfRounds;      var x = year.id;      alert(x+" "+rnd);  }  

My controller:

    public function se_racestandingsround(){            $roundPick = $_POST['round'];          $rnd = $_POST['rnd'];          print_r($roundPick." ".$rnd);  }    

You can see I also try to pass a variable "rnd". That variable is not in the div, it's on a js part of my view and is not as important as "round". I do not mind of using a specific way doing the post request. I just need to pass the value on my controller to load the next page.

React axios-auth-refresh Handle Refresh token API Error

Posted: 23 Sep 2021 08:16 AM PDT

I am using axios-auth-refresh library.

My use case is,

  1. If the request (Let's say getCourse) is getting 401 Error, I will Invoke RefreshToken API.

  2. With the response of RefreshToken API, I will again consume the original request.

  3. If Refresh token is expired, I will throw 'Refresh Token Invalid' in 403 Http Status code.

  4. If I get 403 in RefreshToken API, I will show a sweet alert for 5 seconds and remove all the local storage and reload the window(Signout).

My problem is when RefreshToken API response is expired, The error response of Original API(getCourse) is sent to the getCourse invoke call. But I don't want to send getCourse failure API response if RefreshToken API is failed.

enter image description here Here is my code,

import axios from "axios";  import createAuthRefreshInterceptor from 'axios-auth-refresh';    const API = axios.create({ baseURL });    API.interceptors.request.use(      (config) => {        config.headers["Authorization"] = getToken() || "";        return config;      },      (error) => {        return Promise.reject(error);      }    );        // Function that will be called to refresh authorization  const refreshAuthLogic = async failedRequest => {      // console.log('failedRequest', failedRequest);      return API.post("/refresh-token", {        token: getRefreshToken("refresh_token"),      })      .then((response) => {        const { token, refreshToken } = response.data;        setToken(token);        setRefreshToken(refreshToken);        // err.response.config.headers["Authorization"] = "Bearer " + token;        return Promise.resolve();      })      .catch((err) => {        // console.log('error', err)        removeLocalStorageData();        fireSessionTimeoutAlert(err);        return Promise.reject(err);      });          }        // Instantiate the interceptor  createAuthRefreshInterceptor(API, refreshAuthLogic);  

Why My original requests don't waiting until I get the catch response of RefreshToken API?

Old Postgresql Volume Mounted with Container but not showing the Databases

Posted: 23 Sep 2021 08:16 AM PDT

I have deleted the old postgresql container having 4 databases in it. Those 4 databases were kept persisted in volume. Later I made another container and mounted the previous old postgresql volume (having 4 databases) with this new container of postgresql, The volume was successfully mounted but when i exec that container and opened the psql shell inside this new container and typed \l it is not showing the previous 4 databases stored in old volume. I have performed the following steps to make the new container and mount with new volume:

  1. Created the new Container

    sudo docker run --name postgresql-container -p 5432:5432 -e  POSTGRES_PASSWORD=somePassword -d postgres  
  2. postgresql old volume (having 4 databases) attached with new container

    sudo docker container run -itd -v  bf6c9d65bce874795c1b3af1071008a6115b3f63400efb8af655bb9a1ae0f08a:/var/lib/postgresql/data  postgres  

In step 2 the volume was successfully attached with container, i have inspected the container with following command:

sudo docker container inspect  fb1f0924f127c6ae3aa49d2c4ee1331697cc5a4930d6c7eae9944defd6c6ef5b  

You can see the volume is correctly mounted in below json format

"Mounts": [              {                  "Type": "volume",                  "Name": "c792a1d5214bcb2ef57eab1b07b41871a0fdf0159d0efa545b0c0e71dee7ba58",                  "Source": "/var/lib/docker/volumes/c792a1d5214bcb2ef57eab1b07b41871a0fdf0159d0efa545b0c0e71dee7ba58/_data",                  "Destination": "/var/lib/postgresql/data",                  "Driver": "local",                  "Mode": "z",                  "RW": true,                  "Propagation": ""              }          ],  

When i run this new container with the following and inspect the database it does not show the previous stored databases in volumes:

sudo docker exec -it  fb1f0924f127c6ae3aa49d2c4ee1331697cc5a4930d6c7eae9944defd6c6ef5b bash  

where am i doing it wrong?

How to change navigation bar & back button colour iOS 15

Posted: 23 Sep 2021 08:15 AM PDT

I have UIkit project and I want to change navigation bar colour and back button colour.It is working fine on previous versions. but not in iOS 15. I put following code on AppDelegate,It is change the Title colour but not back button item colour.How to fix it?

if #available(iOS 15.0, *) {     let appearance = UINavigationBarAppearance()     let navigationBar = UINavigationBar()     appearance.configureWithOpaqueBackground()     appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]     appearance.backgroundColor = .red     navigationBar.tintColor = .white     navigationBar.standardAppearance = appearance;     UINavigationBar.appearance().scrollEdgeAppearance = appearance  }else{     let navBarAppearnce = UINavigationBar.appearance()     navBarAppearnce.tintColor = .white     navBarAppearnce.barTintColor = .red     navBarAppearnce.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]  }  

Output

The 'Access-Control-Allow-Origin' header contains multiple values ', *', but only one is allowed in spring boot stomp configuration

Posted: 23 Sep 2021 08:16 AM PDT

I was configuration stomp in spring boot, I was set setAllowedOrigins but when connect to Sockjs by chrome has errors, how do i resolve this problem?

@Override  public void registerStompEndpoints(StompEndpointRegistry registry) {            registry      .addEndpoint("/agent")      .setAllowedOrigins(Arrays.stream(domainAllowed.split(",")).toArray(String[]::new))      //.setAllowedOrigins("*")      .withSockJS();            logger.info("out register");  }    @Bean  public CorsConfigurationSource corsConfigurationSource() {            logger.info("thong tin domain allowed: "+ domainAllowed);            CorsConfiguration configuration = new CorsConfiguration();      configuration.setAllowedOrigins(Arrays.stream(domainAllowed.split(",")).map(String::trim).collect(Collectors.toList()));      configuration.setAllowCredentials(true);      configuration.setMaxAge(-1L);      configuration.setAllowedMethods(Arrays.asList("*"));      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();      source.registerCorsConfiguration("/**", configuration);      return source;  }  

Access to XMLHttpRequest at 'https://cli.ovp.vn/agent/info?t=1632386394912' from origin '' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'https://domain.work, *', but only one is allowed.

stomp.min.js:8 Whoops! Lost connection to

Power Query - Creating a History table from a Part Change Register

Posted: 23 Sep 2021 08:16 AM PDT

Hoping a Power Query Ninja might assist in solving this…

Reference attachment, I have 2 tables the first [ChangeRegTBL] is a dynamic table (which currently is some 7500+ lines long) which appends changes we've implemented into a build/assembly line. In certain instances, those part number changes are changed again into a new number once again…and in some instances 7-8 times!.

What I'm after is a table (shown in ref attachment as [ ChangeHistTBL] ) which lists a history of every Part Old and what its superseded Part New is and if changed more than once a count and finally a history table summarising Date, Change Request and Part Detail.

Now I've had multiple goes with many merges etc…but it's just messy, slow and certainly doesn't deal with a dynamic table.

Trying to get to grips with the List. Accumulate function…as I feel the solution is within this

Cheers

enter image description here

Ok, I can't seem to add a workbook as an attachment, but can send this if required!

enter image description here

How to dynamically change color of clicked elements using color-picker

Posted: 23 Sep 2021 08:16 AM PDT

I wanted to change color according to user preference dynamically like when a user selects a color then it is applied synchronously to the element .

Like when an element is clicked color picker opens and then it works like developer tools color-picker , when a color is chosen from the picker it is applied to element and if user wants to change the color again in same picker than that also applied

Tried to went through following questions but couldn't find answer :

Change background colors dynamically using input event

how to dynamically select a color from a color picker by using jQuery?

HTML Input Color Picker, Apply Changes In Sync With Color Picker Selection

I wanted to code work like this in below snippet, whichever element is clicked than colors are changes of that element.

In original code html is like this : <div id="clockOuterCircle"><div id="clockStyleCircle"></div></div> which can be solved by bubbling/capturing

var reed = document.getElementById("clockOuterCircle");  var reed1 = document.getElementById("clockStyleCircle");  reed.addEventListener('click', deed)  reed1.addEventListener('click', deed)    function deed() {    var reed2 = document.getElementById("colorClock");    reed2.click();    var reed3 = reed2.value;    // reed1.addEventListener('change', function() {    this.style.backgroundColor = reed3;    document.getElementById("demo").innerHTML = reed3;    //})  }
#clockStyleCircle {    position: absolute;    width: 16vw;    height: 16vw;    text-align: center;    padding: 0%;    top: 28.5%;    left: 28.5%;    border-radius: 50%;    border: 3px solid black;    background-color: rgb(255, 233, 35);  }    #clockOuterCircle {    display: flex;    justify-content: center;    align-items: center;    width: 42vw;    height: 42vw;    margin: auto;    border-radius: 50%;    border: 4px solid rgb(255, 62, 62);    background-color: rgb(253, 133, 133);    user-select: none;  }
<div id="clockStyleCircle"></div>  <div id="clockOuterCircle"></div>  <div id="demo"></div>  <input type="color" name="colorClock" id="colorClock">

Possible answer of dynamically changing color can be like this in below snippet, like using
input event separately on each element.

var reed = document.getElementById("clockOuterCircle");  var reed1 = document.getElementById("clockStyleCircle");  reed.addEventListener('click', deed)  reed1.addEventListener('click', deed)    //function deed() {  //  var reed2 = document.getElementById("colorClock");  //  reed2.click();  //  var reed3 = reed2.value;  // reed1.addEventListener('change', function() {  // this.style.backgroundColor = reed3;  // document.getElementById("demo").innerHTML = reed3;  //})  //}    reed2 = document.getElementById("colorClock");  reed2.addEventListener('input', deed)    function deed() {    var reed3 = reed2.value;    reed.style.backgroundColor = reed3;  }    reed4 = document.getElementById("colorClock2");  reed4.addEventListener('input', deed1)    function deed1() {    var reed5 = reed4.value;    reed1.style.backgroundColor = reed5;  }
#clockStyleCircle {    position: absolute;    width: 16vw;    height: 16vw;    text-align: center;    padding: 0%;    top: 28.5%;    left: 28.5%;    border-radius: 50%;    border: 3px solid black;    background-color: rgb(255, 233, 35);  }    #clockOuterCircle {    display: flex;    justify-content: center;    align-items: center;    width: 42vw;    height: 42vw;    margin: auto;    border-radius: 50%;    border: 4px solid rgb(255, 62, 62);    background-color: rgb(253, 133, 133);    user-select: none;  }
<div id="clockStyleCircle"></div>  <div id="clockOuterCircle"></div>  <div id="demo"></div>  <input type="color" name="colorClock" id="colorClock">  <input type="color" name="colorClock" id="colorClock2">

But in above method color is not changing of clicked element instead a fixed element color is changed which is defined beforehand . So have to apply code to different elements separately, as there are many elements so wanted to apply both ways

Thanks for the help in advance.

Xamarin Forms 5.0.0.2012 Hot Reload Not Working

Posted: 23 Sep 2021 08:16 AM PDT

I have updated the project as per the Visual Studio prompt to Xamarin Forms 5.0.0.2012. When I deploy my Xamarin Forms app I see in the hot reload section of Vs 2019 that Hot Reload is initialising. When I make changes to the XAML and save I see that Hot Reload in connected and appears to be sending the XAML changes. However, there are no changes applied to the running app's screen. I have tried two diffrent Emulator versions and my own Samsung S8 device running Android 9.Tried scanning S.O. for answers but none.

Microsoft Visual Studio Community 2019 Preview  Version 16.10.0 Preview 1.0  Xamarin   16.10.000.21 (main@240d4e4)  Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.    Xamarin Designer   16.10.0.0 (remotes/origin/8affbf0abc24122abd5517b2b52f1073cb52bd7b@8affbf0ab)  Visual Studio extension to enable Xamarin Designer tools in Visual Studio.  

How to removeEventListener that is addEventListener with anonymous function?

Posted: 23 Sep 2021 08:16 AM PDT

function doSomethingWith(param)  {      document.body.addEventListener(          'scroll',          function()          {              document.write(param);          },          false      ); // An event that I want to remove later  }  setTimeout(      function()      {          document.body.removeEventListener('scroll', HANDLER ,false);              // What HANDLER should I specify to remove the anonymous handler above?      },      3000  );  doSomethingWith('Test. ');  

No comments:

Post a Comment