Thursday, August 19, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to combine three foreach as one in javascript?

Posted: 19 Aug 2021 08:03 AM PDT

I am modifying the objects in an array as below.

  books.forEach(doc => { delete doc._id });    books.forEach(doc => doc.isbn = doc.isbn.toString() );    books.forEach(doc => doc.isbn13 = doc.isbn13.toString() );  

is there a faster way to combine these two as one?

K means Clustering for unlabeled dataset

Posted: 19 Aug 2021 08:03 AM PDT

I have been working on an Unlabeled dataset. I used Kmeaans and clustered the dataset into 3 clusters. The problem is I cant plot the data to see how it looks. Also, I added the cluster value as a column in the data for both test and train, i am now struggling to get the accuracy correct.

X_train dataser

train dataset with 3 classifiers

I am very new in c#, while am working with Hashtable I found an error "the name ht.add does not exist in the current context"

Posted: 19 Aug 2021 08:03 AM PDT

Severity Code Description Project File Line Suppression State Error IDE1007 The name 'HT' does not exist in the current context. Collection C:\Users\HP\source\repos\Demp Project\Collection\HashDemo.cs 14 Active

public class HashDemo  {      Hashtable HT = new Hashtable();      HT.Add(1,"s");        HT.Add(3, "n");        HT.Add(4, "j");        HT.Add(2, "a");        HT.Add(5, "u");           }  

Populating an Array by always adding to the deepest array of the base array

Posted: 19 Aug 2021 08:03 AM PDT

i am currently trying to build a specific array structure and populate that array with data on the way.

This is the starting array i have:

[  0 => [      'id' => 1,      'name' => "element",      'orderLevels' => [          [             0 => 168          ],          [             0 => 17          ]      ],  ]  

];

What i want to do now, is to go within the orderLevels key of the array, and for each of the arrays within orderLevels i want to put an array which looks something like this:

[  'id' => 5,  'name' => "element 3",  'orderLevels' => [      [          0 => 170      ],      [          0 => 200      ],      [          0 => 300      ]  ]  

]

As you can see, i basically want to add the same datastructure as before into the deeper, leaf node arrays.

I get this exact data from a function, so how to get the data is not relevant.

In the end i would like to have something like:

[  0 => [      'id' => 1,      'name' => "element",      'orderLevels' => [          [              [                  0 => 168,                  1 => [                      'id' => 5,                      'name' => "element 3",                      'orderLevels' => [                          [                              0 => 170                          ],                          [                              0 => 200                          ],                          [                              0 => 300                          ]                      ]                  ]              ],              [                  1 => 17,                  1 => [                      'id' => 5,                      'name' => "element 4",                      'orderLevels' => [                          [                              0 => 170                          ],                          [                              0 => 200                          ],                          [                              0 => 300                          ]                      ]                  ]              ]          ]      ],  ]  

];

This should be able to expand even further down, but always only caring for the leaf node arrays.

What i did already try, was to use array_walk_recursive to try and populate the array in aformentioned way. I got a decent result, but in the end it always deleted my ids within the subarrays, which should be expanded.

The code looks something like this:

foreach ($sortimentOrder[0] as $item) {       array_walk_recursive($sortimentOrder[0]['orderLevels'], $func, ['id' => $data[0], 'name' => $data[1], 'orderLevels' => $orderLevelData]);  }    $func = function (&$item, $key, $newStuff) {       $item = $newStuff;    };  

If someone may be able to help me out with this one i would be grateful to you.

I never did something like this before, so sorry if this question is not as hard as i think it is.

Write groupby data into text file

Posted: 19 Aug 2021 08:03 AM PDT

I am trying to print groupby data into tabular format into a text file but not able do it. Please help

Code snippet below

from tabulate import tabulate import pandas as pd

dict = {"Name: [Martha', 'Tim', 'Rob', 'Georgia'],

'Maths': [87, 91, 97, 95],

"English":[83, 89, 84, 86],

'Hindi': [84, 91, 84, 73]

} df = pd.DataFrame(dict)

print (tabulate(df, headers = 'keys', tablefmt= 'psql')) tabular_data-tabulate(df, headers = 'keys', tablefmt = 'psql')

grouped_data-df.groupby(['Name'])

tabular_data_grouped-tabulate(grouped_data, headers = 'keys', tablefmt= 'psql')

try:

output_file_name="OutSample.txt"

output_file = open(output_file_name, 'w') print("path for output file-----> ", output_file_name)

print("processing...")

output_file.write(df.to_string(header=['Student Name', 'Maths', 'English', 'Hindi']))

output_file.write("\n")

output_file.write(tabular_data)

output_file.write("\n")

output_file.write(tabular_data_grouped)

output_file.write("\n")

output_file.close

except IOError: print("err")

Output Sample: Output file

please am having an error in hosting my django app to heroku

Posted: 19 Aug 2021 08:03 AM PDT

am deploying my Django website for the first time and am having this error Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command Heroku logs --tail this is what it is showing me in my terminal

get random picture from firebase-realtime-database

Posted: 19 Aug 2021 08:03 AM PDT

        reference = FirebaseDatabase.getInstance().getReference().child("ADS");         @Override              public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {                  progressBar.setVisibility(View.GONE);  list= new ArrayList<>();  for (DataSnapshot shot : snapshot.getChildren()){      String data = shot.getValue().toString();            
  • Database structure

enter image description here

I want to randomly get data from ADS.

OpenGL Render an .obj file using fast_obj.h

Posted: 19 Aug 2021 08:03 AM PDT

I need to use fast_obj.h library for render an .obj file. I handled camera movement and phong shading but can't figure it out how to use this fast_obj.h library. I can send to you this libary and tell little bit what i did understand. To use this libary; we send .obj file path to fast_obj_read() function. And this function reads the all position,texcoords and normals etc from the file.

fastObjMesh* mesh = fast_obj_read(PATH);  if (!mesh) printf("Error loading %s: file not found\n", PATH); // If path isnt correct, send a message.  mesh->positions; // float array for positions.  mesh->texcoords; // float array for texcoords.  mesh->normals;  // float array for normals.  

And my struct type for sending data to:

struct Vertex {  glm::vec3 position;   glm::vec3 color;  glm::vec2 texcoord;  glm::vec3 normal; };  

And here; how i send data for draw a quad:

    GLuint VAO; // Vertex  array Object. ID for the whole model.  glCreateVertexArrays(1, &VAO);  glBindVertexArray(VAO);    GLuint VBO; // Vertex Buffer Object.  glGenBuffers(1, &VBO);   glBindBuffer(GL_ARRAY_BUFFER, VBO);  glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);      GLuint EBO; // Element Buffer Object.   glGenBuffers(1, &EBO);  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indicies),indicies,GL_STATIC_DRAW);      // Set Vertex attrib points and enable.  // Find the attribute location for position.     glVertexAttribPointer(0, 3, GL_FLOAT,GL_FALSE,sizeof(Vertex),(GLvoid*)offsetof(Vertex, position));  glEnableVertexAttribArray(0);    // Find the attribute location for color.  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, color));  glEnableVertexAttribArray(1);    // Find the attribute location for texcoord.  glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, texcoord));  glEnableVertexAttribArray(2);    // Find the attribute location for normal.  glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal));  glEnableVertexAttribArray(3);    glBindVertexArray(0);  

Drawing a quad is fine. I need to draw that obj file with using the libary. How can i send these arrays to my own struct?

Python writing dataframe entries to text file

Posted: 19 Aug 2021 08:04 AM PDT

I have this data frame that I created from excel using pandas. I want to create a separate text file for each Test column(Test,Test2,Test3,Test4) which does not contain as None.

                 Carrier                  Country          PLMN    Test  Test1   Test2 Test3     Test4 Direction     Launch  1           PTI Pacifica                    Guam   USAGU/310110     GSM   GPRS   3G CS    PS   LTE M2M  Outbound 2021-05-06  3                    UNN                  Brunei    BRNDS/52811     GSM   GPRS   3G CS    PS   LTE M2M  Outbound 2021-05-06  5                Verizon                     USA   USAVZ/311480  LTE-M    None    None  None        

The text filename should contain Carrier+Test+Date

The contents of the file should contain:

Carrier: PTI Pacifica               Country: Guam  PLMN: USAGU/310110       Test: GSM  Launch: 2021-05-06  

I am stuck and not sure how to proceed

Specify local path to virtual env in Rproject which is on git

Posted: 19 Aug 2021 08:03 AM PDT

I'm checking out an R project from a repository which uses some python scripts as well. The repo recommends installing a virtual environment with all packages which I did.

Now in Rstudio, I can specify the path to the interpreter from the venv I created and it works, however the_project.Rproj is on source control (and I believe rightfully so) but that's where my python interpreter is now specified.

Where should I specify the python interpreter in an R project which is on source control?

Special Array: An array is special if every even index contains an even number and every odd index contains an odd number

Posted: 19 Aug 2021 08:03 AM PDT

what is the problem of this code? it's showing false. this should be true.

function isSpecialArray(arr) {      for(i=0; i<arr.length; i++){                    return ((arr[i % 2 == 0]) % 2 == 0) && ((arr[i % 2 !==0]) % 2 !== 0)      }     }    console.log(isSpecialArray([2, 7, 4, 9, 6, 1, 6, 3])) // false??  

Appended one accessor but resource has more than one, how is this possible? - Laravel

Posted: 19 Aug 2021 08:03 AM PDT

I am trying to use an accessor on a model to return the status whether a relationship exists.

My User model:

class User {      protected $appends = ['has_profile'];          public function profile()    {      return $this->hasOne(Profile::class)    }      public function getHasProfileAttribute()    {      $exists = $this->profile;        if($exists){        return 1;      }      else{        return 0;      }    }  }  

The problem is when the User model is loaded via User::find(1)->get();, the profile property is also loaded into JSON resource whereas, I only want the has_profile attribute in my JSON return. How should I query the relationship existence without loading it, or should I unload the relationship?

What I Get

"data": {          "id": 270,          "name": "John Doe",          "mobile_number": "01234567890",          "created_at": "2021-08-19T06:55:33.000000Z",          "updated_at": "2021-08-19T06:55:33.000000Z",          "deleted_at": null,          "has_profile": 1,          "profile": {                   "id": 1,                   "details": "Details"                   }      }  

What I want

"data": {          "id": 270,          "name": "John Doe"          "mobile_number": "01234567890",          "created_at": "2021-08-19T06:55:33.000000Z",          "updated_at": "2021-08-19T06:55:33.000000Z",          "deleted_at": null,          "has_profile": 1      }  

How to display JSON data which is in Array list format

Posted: 19 Aug 2021 08:03 AM PDT

I need a quick help for the syntax to display JSON data which are in array list format(I guess) I'm able to display Status & Message but struggling with syntax when I want to display Name Image which are inside Data[]. What syntax I should use to display those data ?

My JSON response

    {      "Status": "1",      "Message": "3 records found.",      "Data": [          {              "Name": "Brain surgery",              "EncId": "B909+U0FIAHIs+sl3IYTvQ==",              "Image": "",              "Extra1": "abdsjh dsgjhgdd gsjjkdkds dddsjkhdj djdjkdh dshjdkhkd dhdhdk sjkghdjkdhkhd dhkdkhdkjhd hkjhkdhd kdjkdjdkjd dhkdkjhdjh ddkdkhd dhdhhd . dgjgdjd dgdgjds",              "Extra2": "",              "ResultFor": "p6r4bAAI4ybdJySoV+PqGQ=="          },          {              "Name": "Dr Ram Das",              "EncId": "fXVmzecGStqrhx1PmIgwlQ==",              "Image": "http://medbo.digitalicon.in/Doctor/U7MK2MZGD0QVQ7E8IR7N.jpg",              "Extra1": "ENT",              "Extra2": "kj",              "ResultFor": "xPCleDOirQpArdOv0uUR9g=="          },          {              "Name": "Kidney Routine Test with Sonography and Serology.",              "EncId": "U4exk+vfMGrn7cjNUa/PBw==",              "Image": "",              "Extra1": "",              "Extra2": "",              "ResultFor": "aZsjjLg3WIBbTg05/15o2w=="          }      ]  }  

My model class

class SearchApiResponse {      SearchApiResponse({          required this.status,          required this.message,          required this.data,      });        String status;      String message;      List<SearchData> data;        factory SearchApiResponse.fromJson(Map<String, dynamic> json) => SearchApiResponse(          status: json["Status"],          message: json["Message"],          data: List<SearchData>.from(json["Data"].map((x) => SearchData.fromJson(x))),      );        Map<String, dynamic> toJson() => {          "Status": status,          "Message": message,          "Data": List<dynamic>.from(data.map((x) => x.toJson())),      };  }    class SearchData {      SearchData({          required this.name,          required this.encId,          required this.image,          required this.extra1,          required this.extra2,          required this.resultFor,      });        String name;      String encId;      String image;      String extra1;      String extra2;      String resultFor;        factory SearchData.fromJson(Map<String, dynamic> json) => SearchData(          name: json["Name"],          encId: json["EncId"],          image: json["Image"],          extra1: json["Extra1"],          extra2: json["Extra2"],          resultFor: json["ResultFor"],      );        Map<String, dynamic> toJson() => {          "Name": name,          "EncId": encId,          "Image": image,          "Extra1": extra1,          "Extra2": extra2,          "ResultFor": resultFor,      };  }  

And Here I can successfully display Status & the message but how to display others which are inside Data[] ?

class AfterSearchPage extends StatefulWidget {    final SearchApiResponse rresponse;    const AfterSearchPage({required this.rresponse});      @override    _AfterSearchPageState createState() => _AfterSearchPageState();  }    class _AfterSearchPageState extends State<AfterSearchPage> {    var responseRef;    //  _SecondState(this.responseRef);    @override    Widget build(BuildContext context) {      return Scaffold(        body: SafeArea(          child: Center(            child: Column(              mainAxisAlignment: MainAxisAlignment.center,              children: [                Text("Status: ${widget.rresponse.status}"),                Text("Message: ${widget.rresponse.message}"),                Text("Name: ${widget.rresponse.data.name}"),//==??????????????????????????????????????Error                 SizedBox(                  height: 50,                ),                  OutlinedButton.icon(                    onPressed: () {                      Navigator.push(                        context,                        MaterialPageRoute(                          builder: (context) => Home2(),                        ),                      );                    },                    icon: Icon(                      Icons.exit_to_app,                      size: 18,                    ),                    label: Text("GoTo Home")),              ],            ),          ),        ),      );    }  }  

Make submit button available only when certain fields are filled according to option

Posted: 19 Aug 2021 08:03 AM PDT

I am trying to make the "submit" button available when certain fields are filled with respect to options. For example, in the code below, if I chose option a or b or c, I should fill all fields and therefore enable the submit button. however, if I chose option d, I should fill the first field and unlock the submit button.

        <html>          <style>          p {            font-family:Arial Narrow;font-style:italic:;color:black:font-size:30px;;          }                </style>          <header>      <script>      function updatex(){      var e = document.getElementById("inst");      const button = document.getElementById("submit");      const inp_p1 = document.getElementById("p1");      const inp_p2 = document.getElementById("p2");      const inp_p3 = document.getElementById("p3");      const container = document.getElementById("container");      if (e.value=="option a"){      document.getElementById('p1').removeAttribute('disabled');      document.getElementById('p2').removeAttribute('disabled');      document.getElementById('p3').removeAttribute('disabled');      document.getElementById('1st').innerHTML="rd";      document.getElementById('p1').min = 0;      document.getElementById('p1').max = 6;      document.getElementById('2nd').innerHTML="imm";      document.getElementById('p2').removeAttribute('min');      document.getElementById('p2').removeAttribute('max');      document.getElementById('3rd').innerHTML="rs1";      document.getElementById('p3').min = 0;      document.getElementById('p3').max = 6;      container.addEventListner('input',() =>{        if (inp_p1.value.length > 0 && inp_p2.value.length > 0 && inp_p3.value.length > 0)        {          button.removeAttribute('disabled');        }        else {          button.setAttribute('disabled', 'disabled');        }      }      );        }      if (e.value=="option b"){      document.getElementById('p1').removeAttribute('disabled');      document.getElementById('p2').removeAttribute('disabled');      document.getElementById('p3').removeAttribute('disabled');      document.getElementById('1st').innerHTML="rs2";      document.getElementById('p1').min = 0;      document.getElementById('p1').max = 6;      document.getElementById('2nd').innerHTML="imm";      document.getElementById('p2').removeAttribute('min');      document.getElementById('p2').removeAttribute('max');      document.getElementById('3rd').innerHTML="rs1";      document.getElementById('p3').min = 0;      document.getElementById('p3').max = 6;        }      if (e.value=="option c"){      document.getElementById('p1').removeAttribute('disabled');      document.getElementById('p2').removeAttribute('disabled');      document.getElementById('p3').removeAttribute('disabled');      document.getElementById('1st').innerHTML="rs1";      document.getElementById('p1').min = 0;      document.getElementById('p1').max = 6;      document.getElementById('2nd').innerHTML="rs2";      document.getElementById('p2').min = 0;      document.getElementById('p2').max = 6;      document.getElementById('3rd').innerHTML="imm";      document.getElementById('p3').removeAttribute('min');      document.getElementById('p3').removeAttribute('max');        }      if (e.value=="option d"){      document.getElementById('p1').removeAttribute('disabled');      document.getElementById('p2').setAttribute('disabled', true);      document.getElementById('p3').setAttribute('disabled', true);      document.getElementById('1st').innerHTML="rs1";      document.getElementById('p1').min = 0;      document.getElementById('p1').max = 6;      document.getElementById('2nd').innerHTML='<br>';      document.getElementById('3rd').innerHTML='<br>';        }            }      </script>          <center>          <p> choices </p>          </center>          </header>          <body>            choice:             <form action = "" method = "POST">              <table>                <tr>                  <td><br></td>                  <td><div id=1st></div></td>                  <td><div id=2nd></div></td>                  <td><div id=3rd></div></td>                </tr>                <tr>                  <td>            <select name="inst" id="inst" onchange="javascript:updatex();">              <option value="">Please select</option>              <option value="option a">A</option>              <option value="option b">B</option>              <option value="option c">C</option>              <option value="option d">D</option>                          </select>          </td>          <td> <div id = "container" onchange="javascript:updatex();">             <input type = "number" name="p1" id = "p1" disabled = true>           </td>           <td>             <input type = "number" name="p2" id = "p2" disabled = true>           </td>           <td>             <input type = "number" name="p3" id = "p3" disabled = true> </div>           </td>           <td>           </tr>         </table>              <button type = "submit" id = "submit" name = "shoot" disabled> Submit </button>            </form>      </body>      </html>

Maven run plugin goal and preceding phases

Posted: 19 Aug 2021 08:03 AM PDT

Usually when we run a plugin goal in maven directly from the command line, the build phases preceding the one the plugin goal is bound to will not be run.

How can we run the plugin goal and all its preceding build phases?

How to make subpage with new URL for every post automaticly [NodeJS]

Posted: 19 Aug 2021 08:03 AM PDT

I have an infinitely scrolling home page that gets posts from a MySQL database with fetch requests and inserts them with javascript.

for(var a = 0; a < reslength; a++){          html += `<div class="post">`;              html += `<div class="meta">`;                  html += `<div class="op">` + results[a].username + `</div>`;                  html += `<div class="date">` + results[a].time + `</div>`;              html += `</div>`;          html += `<h2 class="post-title">` + results[a].title + `</h2>`;          html += `<div class="content">`;              html += `<p class="post-content">` + results[a].content + `</p>`;          html += `</div>`;            html += `<div class="attachment-container">...</div></div>`;          };          document.querySelector('.container').insertAdjacentHTML('beforeend', JSON.parse(JSON.stringify(html)));      }  

How would I make it so that if you click on the posts it would serve a dedicated page for the post with its own custom URL (the plan is to have replies and stats there).

I'm guessing I need to already have an URL prepared to have it wrapped around the JS? How do you do this automatically for every post?

Crontab Django Management command seems to start but nothing happens

Posted: 19 Aug 2021 08:03 AM PDT

I have defined a django management command that imports some data into my application database. I run it using a crontab. Sidenote: everything is inside a docker container. This command works perfectly when I use it manually in my container's shell. However, when crontab tries to run it, nothing happens.

My crontab line is the following :

* * * * * nice -n 19 /usr/local/bin/python3 /code/manage.py my_command "a string argument for my command" # a comment to find the cron easily  

(I put my code into /code because it seemed a good idea at the time.)

I know that crontab calls my command, because /var/log/syslog displays when it is executed. I cannot fathom the reason why nothing happens.

As a test in the "handle" method of my command, I wrote print("handling command") as the first line then added >> /code/cron.log at the end of my crontab line. The text didn't appear in the file.

Any idea ?

EDIT

I added some "print" statements in manage.py and they appeared in the log file. These prints work until the execute_from_command_line(sys.argv) statement. Which means something goes wrong in this function (imported from django.core.management).

I'll keep on investigating.

How do I set a custom value with animation on this React Circular Progress Bar?

Posted: 19 Aug 2021 08:03 AM PDT

I'm looking at this repo for a progress bar, and this code in particular is given as an example for a bar with animated bar and text transitions:

<Example label="Fully controlled text animation using react-move">        <AnimatedProgressProvider          valueStart={0}          valueEnd={66}          duration={1.4}          easingFunction={easeQuadInOut}          repeat        >          {value => {            const roundedValue = Math.round(value);            return (              <CircularProgressbar                value={value}                text={`${roundedValue}%`}                /* This is important to include, because if you're fully managing the          animation yourself, you'll want to disable the CSS animation. */                styles={buildStyles({ pathTransition: "none" })}              />            );          }}        </AnimatedProgressProvider>      </Example>  

With AnimatedProgressProvider.js being the following:

import React from "react";  import { Animate } from "react-move";    class AnimatedProgressProvider extends React.Component {    interval = undefined;      state = {      isAnimated: false    };      static defaultProps = {      valueStart: 0    };      componentDidMount() {      if (this.props.repeat) {        this.interval = window.setInterval(() => {          this.setState({            isAnimated: !this.state.isAnimated          });        }, this.props.duration * 1000);      } else {        this.setState({          isAnimated: !this.state.isAnimated        });      }    }      componentWillUnmount() {      window.clearInterval(this.interval);    }      render() {      return (        <Animate          start={() => ({            value: this.props.valueStart          })}          update={() => ({            value: [              this.state.isAnimated ? this.props.valueEnd : this.props.valueStart            ],            timing: {              duration: this.props.duration * 1000,              ease: this.props.easingFunction            }          })}        >          {({ value }) => this.props.children(value)}        </Animate>      );    }  }    export default AnimatedProgressProvider;  

This is obviously just an animated demo of the actual implementation with hard coded values. But I'm struggling to figure out how I would plug my own values into this and only have it animate and update when my value updates.

So lets say I have an API call for a value and when that value changes I want this to update. How would I do that?

How to find out why a sequelize express app times out (POST status 504)

Posted: 19 Aug 2021 08:04 AM PDT

There is one specific route that times out.

const express = require("express");  const router = express.Router();    router.post("/route", postRoute);  ... other routes    module.exports = router;    async function postRoute(req, res) {    console.log("TEST");    ...    return res.json({success: true});  }    

Within an EC2 instance the express app is started using forever NODE_ENV=production forever start -c "npx babel-node" index.js.

Using forever list we can find the log file, but this log file does not contain a log entry "TEST" as expected.

When making a request to [host]/rout (which misses 'e') tells us the route is not found. So we are certain our route is found, but does not execute any coding from the function postRoute as console.log("TEST") never gets executed...

  • Is there any log file within our EC2 instance that says why it is timing out?
  • Anyone has an idea how this is possible as this specific route works well locally, but not in production?

Here is the error path within the React client

POST [host]/route 504(anonymous)    @   trycatch.ts:281  (anonymous) @   instrument.ts:309  (anonymous) @   xhr.js:177  e.exports   @   xhr.js:13  e.exports   @   dispatchRequest.js:50  Promise.then (async)          c.request   @   Axios.js:61  (anonymous) @   bind.js:9  (anonymous) @   index.js:36  l   @   runtime.js:63  (anonymous) @   runtime.js:294  (anonymous) @   runtime.js:119  n   @   asyncToGenerator.js:3  u   @   asyncToGenerator.js:25  (anonymous) @   asyncToGenerator.js:32  (anonymous) @   asyncToGenerator.js:21  (anonymous) @   index.js:14  y   @   api.js:43  r.handleSubmit  @   GeneralLedgerAccounts.js:222  We  @   react-dom.production.min.js:52  Je  @   react-dom.production.min.js:52  (anonymous) @   react-dom.production.min.js:53  kn  @   react-dom.production.min.js:100  Tn  @   react-dom.production.min.js:101  (anonymous) @   react-dom.production.min.js:113  Fe  @   react-dom.production.min.js:292  (anonymous) @   react-dom.production.min.js:50  Rn  @   react-dom.production.min.js:105  Qt  @   react-dom.production.min.js:75  Zt  @   react-dom.production.min.js:74  t.unstable_runWithPriority  @   scheduler.production.min.js:18  Wi  @   react-dom.production.min.js:122  Ue  @   react-dom.production.min.js:292  Xt  @   react-dom.production.min.js:73  n   @   helpers.ts:87  

Using Git token for Google Colab

Posted: 19 Aug 2021 08:03 AM PDT

I'm trying to add my Git path to CoLab, I used to do it in a similar way to this code:

try:      %tensorflow_version 2.x      if not os.path.exists("abc-collective-movement"):            password = mytokenhere          #os.environ['git_user'] = user + ':' + password #old method                    !git clone https://$user1@github.com/user2/repo            sys.path.append('repo')  

where I've now replaced my old Git password with my new Git token (and I use the correct user1/user2 names), but when I go to import like from folder1 import code1 I get no module named folder as if my path has not been added. Help, please?

Select based on column of field names

Posted: 19 Aug 2021 08:03 AM PDT

I want to be able to union multiple tables to get a common picture of what a user did across all tables in my db. All of my tables have 'Terminal' and 'CreateDate' as the common fields.

The ultimate goal of this is to pivot the tables and union them without actually using PIVOT or UNPIVOT because I do not want to call out EVERY column in EVERY table manually in my SQL. I though about using sys.columns and sys.tables to somehow select all fields from a table dynamically but can't seem to wrap my brain around it. So the schema would be something like below.

Table DateTime Field Data
userhistory 12/31/2020 11:35:16 PM logonoff on
event 1/1/2021 12:00:00 AM emergencyType Fire
event 1/1/2021 12:00:00 AM createDate 1/1/2021 12:00:00 AM
event 1/1/2021 12:00:00 AM respondingAgency FD
unithistory 1/1/2021 12:01:30 AM respondingUnit FireTruck1
unithistory 1/1/2021 12:01:30 AM createDate 1/1/2021 12:01:30 AM
unithistory 1/1/2021 12:01:30 AM unitStatus Dispatched
unithistory 1/1/2021 12:02:30 AM respondingUnit FireTruck1
unithistory 1/1/2021 12:02:30 AM createDate 1/1/2021 12:02:30 AM
unithistory 1/1/2021 12:02:30 AM unitStatus Canceled
event 1/1/2021 12:02:35 PM closeDate 1/1/2021 12:02:35 PM
userhistory 1/1/2021 12:02:36 PM logonoff off

I've created a stored procedure that allows me to see the table name and datetime. All of my tables have a datetime field but a varying number of fields. Here is SP:

    CREATE PROCEDURE [dbo].[TerminalHistoryTimeline]        @Terminal varchar(100),       @StartDate datetime2(0),      @EndDate datetime2(0)        AS        BEGIN            SET NOCOUNT ON;        select 'tableA' TableName, createDate  from tableA where terminal = @Terminal and createDate between @StartDate2 and @EndDate2       union all      select 'tableB' TableName, createDate  from tableB where terminal = @Terminal and createDate between @StartDate2 and @EndDate2       union all      select 'tableC' TableName, createDate  from tableC where terminal = @Terminal and createDate between @StartDate2 and @EndDate2         option(recompile)        END  

I guess I'm unsure of how to add in my 'Field' and 'Data' columns to this SP

Name surname regex for prevent single characters

Posted: 19 Aug 2021 08:03 AM PDT

I've been checking strings with this regex until now.

^[a-zA-ZöÖşŞçÇüÜıİğĞ.]{1,}(?:\s{1}[a-zA-ZöÖşŞçÇüÜıİğĞ.]{1,})+$

This is a regex that allows the following examples.

  • Robert Downey
  • R. Downey
  • Robert D.

But I want prevent both word from being single charackter like this.

  • R D
  • R. D.

I want name surname like below

  • R Downey => This is ok.

  • Robert D=> This is ok.

  • R. Downey=> This is ok.

  • Robert D.=> This is ok.

  • R D => This is NOT ok.

  • R. D. => This is NOT ok.

How can I handle it?

Where can I find a full description of the "format" field for NumPy objects that includes 'Z' for "complex"?

Posted: 19 Aug 2021 08:03 AM PDT

When I look at the "format" field for a complex double NumPy object, I see "Zd":

>>> import numpy as np  >>> ac = np.array([[1,2]], dtype=complex)  >>> memoryview(ac).format  'Zd'  

However, I don't see "Z" mentioned in the official Python documentation for "struct", and I have also been unable to find it in the NumPy documentation, though it's possibly I simply missed it because I couldn't think of anything more likely to find relevant hits than the terms "complex", "Z", and "format", all of which bring up a lot of irrelevant information. Could anyone point me to relevant documentation and/or give me their own description?

PHP: Best practise / API Function to consolidate SQL data 1:N to a 2d array

Posted: 19 Aug 2021 08:03 AM PDT

I often come across a situation where I have a 1:N relation, e.g. a table of items and another table with additional metadata / attributes for every item.

Consider this example:

users  +-----------+-----------+  | user_id   | username  |  +-----------+-----------+  | 1         |  max      |  | 2         |  john     |  | 3         |  elton    |  | 4         |  tom      |  | 5         |  dave     |  +-----------+-----------+    user_profile_data  +-----+-----------+-----------+  | uid | field_id  | field_val |  +-----+-----------+-----------+  |  1  | 1         |  a        |  |  1  | 2         |  b        |  |  2  | 1         |  c        |  |  2  | 2         |  d        |  |  3  | 1         |  e        |  |  3  | 2         |  f        |  |  3  | 3         |  g        |  |  4  | 1         |  h        |  |  4  | 4         |  i        |  +-----+-----------+-----------+  

Now I have two questions: I want to select extended user-data, every (uid, field_id) combination is unique, usually I do it this way:

SELECT u.user_id, u.username, upd.field_id, upd.field_val  FROM users u  LEFT JOIN user_profile_data upd ON u.user_id = upd.uid  

I get a row for every user/field combination and would need to "re-sort" in php because usually I want to have an array which contains every User with a Subarray of extended attributes, for example like this:

$users = array(1 => array('username' => max, 'data' => array(1 => 'a', 2 => 'b')), 2 => array('username' => 'john', ...));  

Is there a standardized way of simplifying this and/or what's the best-practise in such cases? Is there already something build-in in PHP (not an external SQL framework)?

Thanks

Using linkify option on Django_tables2 columns to create links

Posted: 19 Aug 2021 08:04 AM PDT

I want to add a link to my listview using linkify in the Columns of the API Reference. I am using Django 2 with Django_tables2 v 2.0.0b3

I have a URL with two context variables name, which is passed from the ListView and the slug field species:

URL.py

app_name = 'main'    urlpatterns = [  #The list view  path('genus/<slug:name>/species/', views.SpeciesListView.as_view(), name='species_list'),  # The Detail view  path('genus/<name>/species/<slug:species>', views.SpeciesDetailView.as_view(), name='species'),  ]  

The DetailView is currently accessible if I manually type the URL.

I want to use the option where I can enter a tuple with (viewname, args/kwargs).

For the tables.py I tried:

class SpeciesTable(tables.Table):      species =tables.Column(linkify=('main:species', {'name': name,'slug':species}))  

This gave a NameError: name 'species' is not defined.

species =tables.Column(linkify=('main:species', {'name': kwargs['name'],'slug':kwargs['species']}))  

This gave a NameError: name 'kwargs' is not defined.

I also tried changing the following variables to strings:

species =tables.Column(linkify=('main:species', {'name': 'name','slug':'species'}))  species =tables.Column(linkify=('main:species', {'name': 'name','slug':'object.species'}))  

These attempts gave a NoReverseMatch Reverse for 'species' with keyword arguments '{'name': 'name', 'slug': 'species'}' not found. 1 pattern(s) tried: ['genus\\/(?P<name>[^/]+)\\/species\\/(?P<species>[-a-zA-Z0-9_]+)$']

Formatting it as any of the following will give a SyntaxError:

species =tables.Column(kwargs={'main:species','name': name,'slug':species})  species =tables.Column(args={'main:species','name': name,'slug':species})  species =tables.Column(kwargs:{'main:species','name': name,'slug':species})  species =tables.Column(args:{'main:species','name': name,'slug':species})  

How would I add a link similar to {% url "main:species" name=name species =object.species %}? Currently there are no example in the docs to do this.

Dropping time from datetime <[M8] in Pandas

Posted: 19 Aug 2021 08:04 AM PDT

So I have a 'Date' column in my data frame where the dates have the format like this

0    1998-08-26 04:00:00   

If I only want the Year month and day how do I drop the trivial hour?

.TotalSeconds in C# XNA

Posted: 19 Aug 2021 08:03 AM PDT

Following my recent Asked Question (which was answered; thanks very much for the help!) I have progressed a little further but hit another brick wall. I'm fairly new to C#, and can't seem to get past an error message I'm recieving: "'NullReferenceException was unhandled' Object reference not set to an instance of an object". I am attempting to create some sort of timer that counts up slowly from 1 to 50, every 2 seconds. The code I am using is below. If what I've provided isn't sufficient, let me know and I will edit.

namespace RealTimeStrategyGame  {      class ResourceCounter      {      Vector2 position;      Texture2D sprite;      Rectangle boundingbox;      bool over, clicked;      SpriteFont font;      GameTime gameTime;      int pSourceCount = 1;      int limit = 50;      float countDuration = 2f; //every  2s.      float currentTime = 0f;            public ResourceCounter(Vector2 pos, GameTime gameTime)      {          position = pos;          over = false;          clicked = false;          gameTime = new GameTime();            currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()             if (currentTime >= countDuration)          {              pSourceCount++;              //any actions to perform          }          if (pSourceCount >= limit)          {              pSourceCount = 0;//Reset the counter;            }          }            }  }  

Magento - Apply Tax On Custom Quote Totals Field

Posted: 19 Aug 2021 08:03 AM PDT

I have created a surcharge module for Magento which adds a custom total field to the quote. The surcharge is input into Magento including tax. I have successfully got the module adding the surcharge to the quote and the grand total is correct on the checkout page.

My issue comes when trying to apply tax to the surcharge so that it gets included and displayed in the tax field on the checkout page. Currently it only includes the tax for the products and the shipping.

I have managed to calculate the tax for the surcharge but cant't get the tax applied to the quote so that it is displayed in the tax field but also don't think my approach is quite correct either. Any help would be much appreciated.

class ********_Deposits_Model_Quote_Address_Total_Surcharge extends Mage_Sales_Model_Quote_Address_Total_Abstract {     protected $_config = null;     public function __construct()   {      $this->setCode('surcharge_price');      $this->_config      = Mage::getSingleton('tax/config');      $this->_store = Mage::app()->getStore();   }     protected function _calculateTax(Mage_Sales_Model_Quote_Address $address)  {      $calculator     = Mage::getSingleton('tax/calculation');      $inclTax        = $this->_config->priceIncludesTax($this->_store);        $taxRateRequest = $calculator->getRateRequest(          $address,          $address->getQuote()->getBillingAddress(),          $address->getQuote()->getCustomerTaxClassId(),          $this->_store      );        $taxRateRequest->setProductClassId(Mage::getStoreConfig('********/surcharges/tax_class', $this->_store));        $rate = $calculator->getRate($taxRateRequest);        $baseTax = $tax = $calculator->calcTaxAmount($address->getBaseSurchargePriceAmount(), $rate, $inclTax, true);      }    /**   * Collect address subtotal   *   * @param   ********_Surcharges_Model_Quote_Address $address   * @return  ********_Surcharges_Model_Quote_Address_Total_Surcharge   */  public function collect(Mage_Sales_Model_Quote_Address $address)  {        parent::collect($address);        $this->_setAmount(0)->_setBaseAmount(0);        // If Surcharges Is Enabled Then Calculate Away :-)      if(Mage::getStoreConfig('********/surcharges/surcharge_enabled')) {          $items = $this->_getAddressItems($address);        if (!count($items)) {            return $this;        }          // Calculate Total Surcharge For Items In Quote (Base Prices!)        $surcharge = 0.0;        foreach ($items as $item) {          $price = $item->getData('base_surcharge_price', null);          if(isset($price)) {            $surcharge += $item->getData('base_surcharge_price') * $item->getQty();          }        }         $this->_setAmount($surcharge);       $this->_setBaseAmount($surcharge);         $this->_calculateTax($address);      }          return $this;  }    public function fetch(Mage_Sales_Model_Quote_Address $address)  {      if(Mage::getStoreConfig('********/surcharges/surcharge_enabled')) {      $surcharge = $address->getSurchargePriceAmount();      if(isset($surcharge) && $surcharge > 0) {        $address->addTotal(array(            'code'  => $this->getCode(),            'title' => Mage::getStoreConfig('********/surcharges/surcharge_label'),            'value' => $surcharge        ));      }    }      return $this;  }    public function getLabel()  {      return Mage::getStoreConfig('********/surcharges/surcharge_label');  }  

"Rate This App"-link in Google Play store app on the phone

Posted: 19 Aug 2021 08:03 AM PDT

I'd like to put a "Rate This App"-link in an Android App to open up the app-listing in the user's Google Play store app on their phone.

  1. What code do I have to write to create the market:// or http://-link open in the Google Play store app on the phone?
  2. Where do you put the code?
  3. Does anyone have a sample implementation of this?
  4. Do you have to specify the screen where the market:// or http:// link will be placed, and which is the best to use - market:// or http://?

Custom totals collector: Reorder totals in totals overview in checkout

Posted: 19 Aug 2021 08:03 AM PDT

I have created a custom totals collector to grant qualified customers a discount of 3% of the cart's subtotal. The code of my collector looks like the following:

class My_Module_Model_DiscountCollector      extends Mage_Sales_Model_Quote_Address_Total_Abstract  {      // ...      public function collect(Mage_Sales_Model_Quote_Address $address)      {          if($this->userIsQualified())          {              parent::collect($address);                // $this->_inclTax tells the collector to either calculate the actual discount amount               // based on the subtotal including or excluding tax              $baseCalcValue = ($this->_inclTax) ? $address->getBaseSubtotalTotalInclTax() : $address->getBaseSubtotal();              $calcValue = ($this->_inclTax) ? $address->getSubtotalInclTax() : $address->getSubtotal();                $baseDiscountAmount = $baseCalcValue * 0.03;              $discountAmount = $calcValue * 0.03;                $this->_setBaseAmount(-$baseDiscountAmount);              $this->_setAmount(-$discountAmount);          }          return $this;      }      public function fetch(Mage_Sales_Model_Quote_Address $address)      {          if($this->userIsQualified())          {              $discountAmount = (($this->_inclTax) ? $address->getSubtotalInclTax() : $address->getSubtotal()) * 0.03;              $address->addTotal(                  array(                      "code"  => $this->getCode(),                      "title" => "My Discount (3%)",                      "value" => -$discountAmount                  )              );          }          return $this;      }      // ...  }  

My problem is to change the order of the totals in the totals listing (for example when viewing the cart). The current order is "Subtotal, Shipping, My Discount, ..., Grand Total", but I would prefer "Subtotal, My Discount, Shipping, ...". Currently my config.xml looks something like this:

<config>      <!-- ... --->      <global>          <!-- ... -->          <sales>              <quote>                  <totals>                      <my_discount>                          <class>My_Module_Model_DiscountCollector</class                          <after>shipping</after>                          <!--<before>grand_total</before>-->                          <!--<after>shipping</after>-->                          <!--<before>shipping</before>-->                      </my_discount>                  </totals>              </quote>          </sales>          <!-- ... -->      </global>  </config>  

I tried different settings for the "before"- and "after"-elements, but that didn't affect the order the totals are listed in, it only affected the calculation of the grand_total. It's weird, but my total is only included in the calculation of the grand_total with the settings above. For example, if I set "after" to "subtotal" or if I set "before" to "grand_total", my total doesn't affect the calculation of the grand_total at all. Maybe someone can explain that to me.

So how do I change the order of the totals? Why are the results so weird when I set "after" to anything else but "shipping"? Have I misunderstood the function of those two config-elements?

No comments:

Post a Comment