Friday, April 2, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


What is the simplest way to get XML attribute from URL with JavaScript?

Posted: 02 Apr 2021 07:28 AM PDT

I want to build a function that gets the content of an XML (Only the RATE) from a URL . It is my first time working with XML , and I am not really sure how to do it . I was trying some codes that I have found in tutorials online but it did not work . the XML looks like:

   <CURRENCIES>  <LAST_UPDATE>2021-04-01</LAST_UPDATE>  <CURRENCY>  <NAME>Dollar</NAME>  <UNIT>1</UNIT>  <CURRENCYCODE>USD</CURRENCYCODE>  <COUNTRY>USA</COUNTRY>  <RATE>3.333</RATE>  <CHANGE>-0.03</CHANGE>  </CURRENCY>  </CURRENCIES>  

I am only interested in the value of the RATE element , So I want the function to return the rate value only . Is there a way to do it in pure JavaScript?

VueJS : Add a tooltip component on legacy HTML base on class selector?

Posted: 02 Apr 2021 07:28 AM PDT

I would like to add VueTippy (the vue wrapper for Tippy.js) to text (HTML, stored in DB) which has a format like this :

My <a href="/slug/" class="mySelector">Text</a> around.  

I would like that when hovered I can display a tooltip for this link (dynamic, depending of link). And as this tooltip will have button & actions I would like to have a VueJS component.

But how can add my vue component to a simple link ? Thanks

Oracle - Convert and display sysdate in EST

Posted: 02 Apr 2021 07:28 AM PDT

Using oracle 11 , how to Convert and display sysdate in EST?
Server is in PST location

I tried this:

select from_tz(CAST(sysdate AS TIMESTAMP),'EST') from dual  /  

I don't get correct results..

R: 3D scatterplot with 2 groups not showing up in browser

Posted: 02 Apr 2021 07:28 AM PDT

Following the tutorial here, I want to create a 3d scatterplot with two colors (blue and orange) representing two different groups. Here is the snippet of my plot3d functions, where I am feeding the x y and z values data frame columns of type double:

par(mar=c(0,0,0,0))  plot3d(     x=population.zero$T, population.zero$M, z=population.zero$L,     col = "orange",     type = 's',     radius = .1,    xlab="Effective Temperature (K)", ylab=expression("Mass " (M['\u0298'])), zlab=expression("Luminosity " (L['\u0298'])))    plot3d(     x=population.one$T, population.one$M, z=population.one$L,     col = "blue",     type = 's',     radius = .1,    xlab="Effective Temperature (K)", ylab=expression("Mass " (M['\u0298'])), zlab=expression("Luminosity " (L['\u0298'])))    htmlwidgets::saveWidget(rglwidget(), "MLvsT")  

However, when I view this in the browser, none of the points show up.

enter image description here

Does anyone know what I am missing here?

(Bonus points: How do I make the figure in the browser appear larger?)

errno: 150 "Foreign key constraint is incorrectly formed Laravel 8

Posted: 02 Apr 2021 07:28 AM PDT

I want to create two tables with one to many relationships but when I run the commander PHP artisan serve an error was display: 1 C:\xampp\htdocs\Laravel\Data-management\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table data_management_bd.factures (errno: 150 "Foreign key constraint is incorrectly formed")")

2 C:\xampp\htdocs\Laravel\Data-management\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471 PDOStatement::execute()"

the migration of "factures" table :

public function up()      {          Schema::disableForeignKeyConstraints();            Schema::create('factures', function (Blueprint $table) {              $table->string('code_facture')->primary();              $table->date('date_facture');              $table->double('montant_facture');              $table->boolean('reglee');              $table->string('montant_en_lettre');              $table->string('code_fournisseur');              $table->timestamps();                            $table->foreign('code_fournisseur')                  ->references('code_fournisseur')                  ->on('fournisseurs')                  ->onDelete('restrict')                  ->onUpdate('restrict');          });      }  

the migration of "fournisseurs" table :

public function up()      {            Schema::create('fournisseurs', function (Blueprint $table) {              //correspond à la clé étrangère de la table              $table->string('code_fournisseur')->primary();              $table->string('intitule_fournisseur');              $table->string('telephone_fournisseur');              $table->string('email_fournisseur');              $table->timestamps();          });      }  

The model "facture":

protected $fillable = [          'code_facture', 'date_facture','montant_facture','reglee',           'montant_en_lettre', 'code_fournisseur', 'created_at', 'updated_at'      ];        protected $guarded = ['code_facture', '_token'];      public $incrementing = false;      protected $primaryKey = 'code_facture';      protected $keyType = 'string';        public function fournisseur()      {           return $this->belongsTo(Fournisseur::class, 'code_fournisseur', 'code_facture');       }  

the model "fournisseur" :

protected $table = "fournisseurs";        protected $fillable = [         'code_fournisseur', 'intitule_fournisseur',         'telephone_fournisseur','email_fournisseur', 'created_at', 'updated_at'      ];            protected $guarded = ['code_fournisseur', '_token'];      public $incrementing = false;      protected $primaryKey = 'code_fournisseur';      protected $keyType = 'string';        public function factures()       {           return $this->hasMany(Facture::class, 'code_facture', 'code_fournisseur');       }  

Can someone help me I can't find the mistake in my code?

Windows 10: after gaining remote access, remotely start Quick Assist as .\Administrator without UAC, or temporarily disable UAC

Posted: 02 Apr 2021 07:28 AM PDT

I'd like a script to be used in this situation:

  1. gain remote access without admin privileges
  2. remotely start Quick Assist as .\Administrator and not have a UAC dialogue.

Step 1 is usually made with Quick Assist, sometimes made with Teams screen sharing.


I'm aware that I can locate quickassist.exe in File Explorer then use Shift and the context menu to Run as a different user, however I'd like a scripted approach.

Experiment A

This works, but there's a Yes/No UAC dialogue:

$isElevated = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)  if ( -not $isElevated ) {      Start-Process powershell.exe -Credential Administrator -NoNewWindow -ArgumentList {          Start-Process quickassist.exe -Verb RunAs ;      } ;  }  

Experiment B

I make multiple mistakes, don't know how to correct them. (I'm trying to learn PowerShell, gradually, but I'm easily confused whilst learning; slightly dyslexic.)

$isElevated = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)    if ( -not $isElevated ) {    Start-Process powershell.exe -Credential Administrator {      Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "PromptOnSecureDesktop" -Value 0 -Force;      };    Write-Host "UAC (user account control) is weakened for a Quick Assist session …" -ForegroundColor Red;      Start-Process powershell.exe -Credential Administrator -NoNewWindow -ArgumentList {Start-Process quickassist.exe -Verb RunAs -Wait};    Write-Host "… Quick Assist session complete …" -ForegroundColor Red;      Start-Process powershell.exe -Credential Administrator {      Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "PromptOnSecureDesktop" -Value 1 -Force;      };    Write-Host "… UAC is strengthened." -ForegroundColor Red;  }  
  • the two intended changes to the registry do not occur
  • the third credential dialogue appears too soon – I want it to not appear until after the end of the Quick Assist session.

Also, conceptually, there's probably no need to run Quick Assist as Administrator whilst UAC is temporarily weakened.

References

https://stackoverflow.com/a/2258134/38108 (2010-02-13) I see use of -Credential with Invoke-Command but when I try to do something similar, for changes to the registry, I make a mess.

https://stackoverflow.com/a/47516161/38108 (2017-11-27) self-elevating PowerShell scripts.

https://superuser.com/a/1524960/84988 (2020-02-12) and https://serverfault.com/a/1003238/91969 (2020-02-15) are interesting – the same script in both answers – however I need something like -Credential Administrator in lieu of -ComputerName.

https://stackoverflow.com/a/60292423/38108 (2020-03-07) via https://stackoverflow.com/a/60263039/38108

https://github.com/okieselbach/Intune/blob/master/DisablePromptOnSecureDesktop.ps1 (2020-11-13) via Quick Assist the built-in Remote Control in Windows 10 – Modern IT – Cloud – Workplace

Bradley Terry Models in R as a glm()

Posted: 02 Apr 2021 07:28 AM PDT

I am trying to deconstruct the BradleyTerry2::BTm() function as a glm and I am having trouble doing that.

The goal is to be able to run this as a glm so that I can replicate my results in Stata.

I have looked at the package documentation and source code https://github.com/hturner/BradleyTerry2 but am having trouble interpreting the BTm.R script.

For replication purposes, here is the flat lizard code used in the package documentation. How do I run the BTm() as a generalized linear model?

data("flatlizards", package = "BradleyTerry2")  lizModel <- BTm(1, winner, loser, ~ SVL[..] + (1|..),                  data = flatlizards)  summary(lizModel)  

Prior to posting this question, I have considered alternative packages taht do this such as prefmod and psychotools for hints but have been unsuccessful. I have also searched previous Stack Overflow threads and even looked into Cross Validated.

Thank you!

I have 3 tables joined on mbr ids dates vary throughout the table just want the specific month and year that the first table date range is for per mbr

Posted: 02 Apr 2021 07:28 AM PDT

I have 3 tables all have historical data; I am left joining on MBRID in the 3 tables. The base table has a monthly service date. members have been generated to look for errors in the monthly service table with closed dates prior to date of service. This data ranges months and years I need to find the members in two other tables for the correct month of service but only generate that month of data.

This is the code i am trying to use:

Select a.DT_OF_SRVC, a.MEMB_LIFE_ID, b.Report_Date,a.Active_Date as Claims_Active_DT, a.Closed_Date as Claims_CLD, c.CASE_ACTV_DT as BHCC_Act,c.CASE_CLOS_DT as BHCC_CLSD, a.LCC_Region, a.MEMB_LAST_NM, a.MEMB_FRST_NM, b.Active_Date, b.Assigned_LCC, b.Closed_Date, b.Region_Name,b.Current_Workflow_Status,a.Pay_Claim from MonthSErvice table a left join tbl_MemberLIfe_Historical_Master b on a.MEMB_LIFE_ID =b.[Member Life ID]
left join tbl_Mbr_Historical c on a.MEMB_LIFE_ID = c.MEMB_LIFE_ID Where a.Closed_Date <= DATEADD(MONTH,-1,DT_OF_SRVC) and b.Report_Date = DateAdd(Month,1,a.Dt_of_SRVC) and c.Report_Date =DateAdd(Month,1,a.DT_OF_SRVC) and Pay_Claim = 'Y' Group by b.Active_Date, a.LCC_Region, a.MEMB_LAST_NM, a.MEMB_FRST_NM, b.Assigned_LCC, b.Closed_Date, b.Region_Name,b.Current_Workflow_Status,a.Pay_Claim, a.MEMB_LIFE_ID, b.Report_Date, a.MEMB_LIFE_ID, b.Report_Date,a.DT_OF_SRVC,a.Active_Date, c.CASE_ACTV_DT, c.CASE_CLOS_DT, a.Closed_Date Order by DT_OF_SRVC desc

When I use this query it runs but no data retrieves

Javascript CORS problem when trying to access cross domain URL images

Posted: 02 Apr 2021 07:27 AM PDT

I have the following function to merge a smaller version of a picture onto a bigger version of itself:

function mergeImages(imgref) {      var canvas = document.createElement("canvas");      canvas.width = 500;      canvas.height = 500;      var ctx = canvas.getContext("2d");      ctx.rect(0, 0, canvas.width, canvas.height);      ctx.fillStyle = "#000";      ctx.fill();        var myImage = new Image();      var myImage2 = new Image();      myImage.crossOrigin = 'anonymous';      myImage2.crossOrigin = 'anonymous';      myImage.src = imgref;        myImage.onload = function () {          console.log('load1')          ctx.drawImage(myImage, 0, 0, 500, 500);          myImage2.src = imgref;          myImage2.onload = function () {              console.log('load2')              ctx.drawImage(myImage2, 100, 100, 400, 400);              var img = canvas.toDataURL("image/png");              return img;          }      }  }  

However I am getting the following error:

Access to image at 'http://xxxxxxx.com/testpicture.jpg' from origin 'http://localhost:53594' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I used the "anonymous" crossOrigin declaration that should resolve this but it seems not cause any effect.

Any idea?

Print out just filename from bash array

Posted: 02 Apr 2021 07:27 AM PDT

I have an array and loop printing out the filename+extension, but i just want to print the filename. How can I do that?

tffilearray=(`find ./ -maxdepth 1 -name "*.json"`)  for filepath in "${tffilearray[@]}"; do      echo $filepath  done  

OpenId OnRedirectToIdentityProvider custom 401 message

Posted: 02 Apr 2021 07:28 AM PDT

I'm using AddOpenIdConnect and need to modify the response in case the OnRedirectToIdentityProvider event is raised. Within this event the response status is modified to 401 and I would like to set a custom message. To write this custom message, I've created the SetResponseBody method.

The solution of this post is used to set the response status, but I need to modify the Body as well.

I'm calling the SetResponseBody method (a custom method which I implemented) in order to modify the response body as soon as the 'OnRedirectToIdentityProvider' event is raised from AddOpenIdConnect.'

As mentioned in one of the comments by @Panagiotis Kanavos in the post, this (SetResponseBody) doesn't seem to be a valid implementation. Could you provide an alternative?

Summarized: I would like to return a custom response besides the status code 401.

OnRedirectToIdentityProvider = async e =>  {      // e is of type RedirectContext      if (e.Request.Path.StartsWithSegments("/api")))      {                      if (e.Response.StatusCode == (int)HttpStatusCode.OK)          {              e.Response.StatusCode = (int)HttpStatusCode.Unauthorized;              // TestMessage is a const              // e.Response is readonly (get) so it's not possible to set it directly.              await ResponseRewriter.SetResponseBody(e.Response, TestMessage);          }          e.HandleResponse();      }      await Task.CompletedTask;  }  

with ResponseRewriter.SetResponseBody defined as follows

public static async Task SetResponseBody(HttpResponse response, string message)  {         var originalResponseBody = response.Body;      var responseBody = new MemoryStream();      response.Body = responseBody;      response.ContentType = "application/json";      dynamic body = new { Message = message };      string json = JsonSerializer.Serialize(body);      await response.WriteAsync(json);      response.Body.Seek(0, SeekOrigin.Begin);      await responseBody.CopyToAsync(originalResponseBody);           }  

Update Gradle in Flutter project

Posted: 02 Apr 2021 07:27 AM PDT

programmer friends!

I have this project in Flutter, but I can't build an apk, since a couple of weeks, because of the Gradle version. I've tried everything, but Flutter always returns the error below:

I already install every update I found, even though, it shows that the Gradle version is 4.10.2

I'll be very thankfull if anybody can help me. Thanks!

  • flutter build apk
...  FAILURE: Build failed with an exception.    * Where:  Build file 'C:\Users\israel.gomes\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\audioplayers-0.17.4\android\build.gradle' line: 25    * What went wrong:  A problem occurred evaluating root project 'audioplayers'.  > Failed to apply plugin [id 'kotlin-android']     > The current Gradle version 4.10.2 is not compatible with the Kotlin Gradle plugin. Please use Gradle 5.3 or newer, or the previous version of the Kotlin plugin.    * Try:  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.    * Get more help at https://help.gradle.org    BUILD FAILED in 1s      The plugin audioplayers could not be built due to the issue above.    

Here some information about the project status and environment----------------------

  • Already changed gradle-wrapper.properties (Current file):
distributionBase=GRADLE_USER_HOME  distributionPath=wrapper/dists  zipStoreBase=GRADLE_USER_HOME  zipStorePath=wrapper/dists  distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip  
  • android/build.gradle(Current file):
buildscript {      ext.kotlin_version = '1.3.50'      repositories {          google()          jcenter()      }        dependencies {          classpath 'com.android.tools.build:gradle:4.0.1'          classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"      }  }  .  .  .  
  • gradle --version
------------------------------------------------------------  Gradle 5.6.2  ------------------------------------------------------------    Build time:   2019-09-05 16:13:54 UTC  Revision:     55a5e53d855db8fc7b0e494412fc624051a8e781    Kotlin:       1.3.41  Groovy:       2.5.4  Ant:          Apache Ant(TM) version 1.9.14 compiled on March 12 2019  JVM:          1.8.0_261 (Oracle Corporation 25.261-b12)  OS:           Windows 10 10.0 amd64    
  • flutter doctor -v
[√] Flutter (Channel dev, 2.1.0-12.1.pre, on Microsoft Windows [versão 10.0.19042.867], locale pt-BR)      • Flutter version 2.1.0-12.1.pre at C:\Flutter      • Framework revision 8264cb3e8a (3 weeks ago), 2021-03-10 12:37:57 -0800      • Engine revision 711ab3fda0      • Dart version 2.13.0 (build 2.13.0-116.0.dev)    [√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)      • Android SDK at C:\Users\israel.gomes\AppData\Local\Android\Sdk      • Platform android-30, build-tools 30.0.2      • ANDROID_HOME = C:\Users\israel.gomes\AppData\Local\Android\Sdk      • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java      • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)      • All Android licenses accepted.    [√] Chrome - develop for the web      • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe    [√] Android Studio (version 4.0)      • Android Studio at C:\Program Files\Android\Android Studio      • Flutter plugin can be installed from:         https://plugins.jetbrains.com/plugin/9212-flutter      • Dart plugin can be installed from:         https://plugins.jetbrains.com/plugin/6351-dart      • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)    [√] IntelliJ IDEA Community Edition (version 2020.3)      • IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.3      • Flutter plugin version 55.0.4      • Dart plugin version 203.7759    [√] VS Code (version 1.54.3)      • VS Code at C:\Users\israel.gomes\AppData\Local\Programs\Microsoft VS Code      • Flutter extension version 3.20.0    [√] Connected device (3 available)      • Android SDK built for x86 (mobile) • emulator-5554 • android-x86    • Android 7.1.1 (API 25) (emulator)      • Chrome (web)                       • chrome        • web-javascript • Google Chrome 89.0.4389.114      • Edge (web)                         • edge          • web-javascript • Microsoft Edge 87.0.664.75    • No issues found!    

How to add public packages from github to my .Net solution

Posted: 02 Apr 2021 07:28 AM PDT

I am trying to add packages from https://github.com/orgs/DKE-Data/packages to my asp.net project. Here are the things I have tried

  1. Download the package.nupkg file and add the location to the package manager source but it does not allow me to install the package.
  2. Add the PackageReference to .csproj file and did a restore - did not work

As these packages are publicly available isn't there a straight forward approach to add them to my packages?

Appreciate any help here!

When seperating class file into .h and .cpp file how can I define it in the main file by including the .h file?

Posted: 02 Apr 2021 07:28 AM PDT

So I'm implementing a simple test class and such I'm separating files into : compte.h:

#ifndef COMPTE_H  #define COMPTE_H  #include <iostream>  class compte  {  public:      static int n;      int numCompte;      char* nom;      double solde;  public:      compte(const char* = NULL, const double & = 0);      ~compte();  };  

and a compte.cpp

#include <iostream>  #include <cstring>  #include "compte.h"  using namespace std;    int compte::n = 1000;        compte::compte(const char* nom, const double &solde)  {      this->solde = solde;      this->nom = new char[strlen(nom)];      strcpy(this->nom, nom);        numCompte = n++;  }  compte::~compte()  {      delete[] nom;  }  

however, when I include compte.h I get an unidentified reference to the member methods of the class, when I include compte.cpp it works, I just want to know what I can add to include the .h file instead of .cpp

Trying to overlay one div above another

Posted: 02 Apr 2021 07:27 AM PDT

Here in this code I am trying to overlay navigation bar above another navbar, but nothing seems to be working. What am I doing wrong? Even if I can make it overlay over the other they are not placed centered within the container.

* {    margin: 0;    padding: 0;    box-sizing: border-box;  }    .container {    width: 100%;    background-color: blue;    height: 70px;    position: relative;  }    #content {    max-width: 1200px;    background-color: blue;    display: flex;    margin: 0 auto;    position: absolute;    z-index: 9;  }    #content1 {    max-width: 1200px;    background-color: red;    display: flex;    margin: 0 auto;    z-index: 0;  }    .logo {    display: flex;    align-items: center;    color: white;    font-size: 23px;    font-weight: 900;    margin: 15px;    font-family: 'Roboto Slab', serif;  }    .container .nav {    display: flex;    padding: 10px 10px 10px 100px;    align-items: center;    height: 70px;  }    .nav li {    margin: 20px;    list-style-type: none;    color: white;    font-family: 'Roboto Slab', serif;    display: flex;  }    .nav {    margin-left: 150px;  }    .search {    background-color: red;    opacity: 0.90;    height: 70px;    display: flex;    align-items: center;    padding: 10px 10px 10px 390px;    color: white;  }
<div class="container">    <div id="content">      <div class="logo">Google</div>      <ul class="nav">        <li>Home</li>        <li>Services</li>        <li>Products</li>        <li>Feedback</li>      </ul>      <div class="search"><i class="fas fa-search"></i></div>    </div>    <div id="content1">      <div class="logo">Google</div>      <ul class="nav">        <li>Home</li>        <li>Services</li>        <li>Products</li>        <li>Feedback</li>      </ul>      <div class="search"><i class="fas fa-search"></i></div>    </div>  </div>

Just want to know how to overlay my nav bar above another nav bar and make it center within the container,

SQL Multi Conditional CASE WHEN issues [Part 2 - logic adjustments]

Posted: 02 Apr 2021 07:27 AM PDT

I have a follow up question to a question I posted yesterday. Today there are changes to the logic needed. SQL Multi Conditional CASE WHEN issues

Example data table is at the bottom of this post. The original code was written around the following logic:

  1. If there is only 1 order number - return the order date
  2. If there are >1 alike order numbers and any of those orders was paid with a credit card - return the most recent order date that was paid by credit card
  3. If there are >1 alike order numbers and none of the orders were paid with a credit card - return the most recent order date.

Credit to user Gordon Linoff who provided the following code which worked perfectly:

    select o.*  from (select o.*,               row_number() over (partition by order_number                                  order by (case when payment_method = 'Credit Card' then 1 else 2 end),                                           order_date desc                                 ) as seqnum        from orders o       ) o  where seqnum = 1;  

There have been updates to the requirements in the logic which have been expanded to the following:

  1. if orders = 1, then use timestamp from order
  2. if orders = 2 and one is a credit card, use date from oldest credit card order.
  3. if orders = 2 and none are credit card, use the RECENT order date.
  4. if orders > 2 and any are credit card, use date from oldest credit card order.
  5. if orders > 2 and none are credit card, use the OLDEST order date.

Can this be accomplished by modifying the CASE WHEN in Gordon's code? Or does it require more than that simple of a change.

Thank you!

Original Data Table in question:

Order Number Payment Method Order Date
120 Cash 01/01/2021
175 Credit Card 01/02/2021
209 Cash 01/03/2021
209 Credit Card 01/04/2021
209 Personal Check 01/05/2021
209 Credit Card 01/06/2021
209 Cash 01/07/2021
209 Personal Check 01/08/2021
277 Credit Card 01/09/2021
301 Cash 01/10/2021
333 Personal Check 01/11/2021
333 Cash 01/12/2021
333 Cash 01/13/2021
333 Personal Check 01/14/2021
400 Credit Card 01/15/2021
551 Credit Card 01/16/2021
551 Cash 01/17/2021
680 Personal Check 01/18/2021

insert multiple urls into inputfields from multiple values

Posted: 02 Apr 2021 07:27 AM PDT

I have a fetch get request that parse page and get some parametrs to generate new url and insert it into input fields
I have multiple values from value1, value2, value3
The question is that how i can generate multiple urls from this parametrs and insert it into fields(fields should generate dynamically)?
Now, window with form dont generates

If i put break into loop, code generate window with form but show only one url

As a result of this code should be Window with form and three input fields with urls

var url = 'google.com/page1'  fetch(url, {          method: 'GET',          credentials: 'include',      })      .then(function(response) {          return response.text()      })      .then(function(html) {              var parser = new DOMParser();              var doc = parser.parseFromString(html, "text/html");              var value4 = 'test4';              ...              if (condition) {                  var name = doc.querySelectorAll("someClass");                  for (var i = 0; i < name.length; i++) {                      var allNames = name[i].outerHTML;                      var value1 = allNames.match('MyregExp1')[0];                      var value2 = allNames.match('MyregExp2')[0];                      var value3 = allNames.match('MYregExp3')[0];                        var newUrl = `google.com/?${value1}&${value2}&${value3}&test=${value4}`;                      //brake                        console.log(value1);                      // something1                      // something2                      // something3                      // etc...                        console.log(value2);                      // something11                      // something22                      // something33                      // etc...                        console.log(value3);                      // something111                      // something222                      // something333                      // etc...                          console.log(newUrl);                      // google.com/?something1&something2&$something3&test=test4                      // google.com/?something11&something22&$something33&test=test4                      // google.com/?something111&something222&$something333&test=test4                      // etc...                    }                  if (allNames.length >= 2) {                        var newForm = Ext.create('Ext.form.Panel', {                          title: 'Form',                          width: 250,                          autoHeight: true,                          autoScroll: true,                          bodyPadding: 10,                          id: 'Form',                      });                          function newRadio() {                          var radio = new Ext.form.Radio({                              height: 40,                              labelWidth: 110,                              width: 20,                              name: 'url',                          });                          return radio;                      }                          function newTextArea(id) {                          var textArea = new Ext.form.TextArea({                              fieldLabel: i + '_url',                              height: 30,                              labelWidth: 110,                              width: 330,                              submitValue: false,                              readOnly: true,                              autoScroll: true,                              id: id                          });                          return textArea;                      }                          for (i = 0; i < name.length; i++) {                          var id = i;                          id = 'field_' + id;                          var cont = NewContainer();                          var field = newTextArea(id);                          var radioGr = newRadio();                          field.setValue(newUrl);                          newForm.add(cont);                      }                        function NewContainer() {                          var container = new Ext.container.Container({                              xtype: 'container',                              layout: 'hbox',                              items: [radioGr, field]                          });                          return container;                      }                        var win = new Ext.Window({                          title: "Window",                          layout: 'fit',                          modal: 'true',                          height: 500,                          width: 385,                          items: [newForm],                          buttons: [{                              text: "Confirm",                              handler: function() {                                  //something handler                              }                          }]                      });                      win.show();                      }              }

Events don't work laravel, in the queue, the process is in progress and gives an error

Posted: 02 Apr 2021 07:28 AM PDT

Created an event, it works locally, uploaded it to the server stopped working.

[2021-04-02 14:26:51] local.ERROR: Class 'Redis' not found {"exception":"[object] (Error(code: 0): Class 'Redis' not found at /vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php:75) [stacktrace]

how to connect Redis?

PrivatMessageEvent.php

<?php    namespace App\Events;    use Illuminate\Broadcasting\Channel;  use Illuminate\Broadcasting\InteractsWithSockets;  use Illuminate\Broadcasting\PresenceChannel;  use Illuminate\Broadcasting\PrivateChannel;  use Illuminate\Contracts\Broadcasting\ShouldBroadcast;  use Illuminate\Foundation\Events\Dispatchable;  use Illuminate\Queue\SerializesModels;    class PrivatMessageEvent implements ShouldBroadcast  {      use Dispatchable, InteractsWithSockets, SerializesModels;        public $data;        /**       * Create a new event instance.       *       * @return void       */      public function __construct($data)      {          $this->data = $data;      }        /**       * Get the channels the event should broadcast on.       *       * @return \Illuminate\Broadcasting\Channel|array       */      public function broadcastOn()      {          return new Channel('private-channel');      }  }  

When I start the queue, I can see that this event is in progress but gives an Failed.

Script blade template

 socket.on("private-channel:App\\Events\\PrivatMessageEvent", function (message) {                  appendMessageToReceiver(message);              });  

How to generate momentjs format from custom time object

Posted: 02 Apr 2021 07:27 AM PDT

Context:

Hi, I am trying to generate a momentjs format from the given start time and end time.

let sourceTime = {    "startTime": "0600", // 6 AM    "endTime": "2100" // 9 PM  }  

Using the above endTime property I am trying to get time in the format below :

2021-02-04T09:00 pm i.e This format https://momentjs.com/docs/#/displaying/format/ - "YYYY-MM-DDThh:mm a"

using this piece of code

let currentDate = moment().format('DD-MM-YYYY');  let savedFormat = moment(`${currentDate} ${sourceTime.endTime.substring(0, 2)}:${sourceTime.endTime.substring(2, 4)}`).format('YYYY-MM-DDThh:mm')  

Where I am adding the current date and end time in a customized way using a string literal to generate the desired format.

Problem:

I am getting 9:00 am instead of 9:00 pm.

2021-02-04T09:00 am

Not sure where am I'm doing wromg. Any suggestion would be helpful.

let sourceTime = {    "startTime": "0600", // 6 AM    "endTime": "2100" // 9 PM  }    let currentDate = moment().format('DD-MM-YYYY');  let savedFormat = moment(`${currentDate} ${sourceTime.endTime.substring(0, 2)}:${sourceTime.endTime.substring(2, 4)}`).format('YYYY-MM-DDThh:mm')    console.log(savedFormat);    //Shows am instead of pm  console.log(moment(savedFormat).format('YYYY-MM-DDThh:mm a'));  //OUTPUT
<script src="https://momentjs.com/downloads/moment.min.js"></script>

I want user website form details in pdf format in Gmail account

Posted: 02 Apr 2021 07:28 AM PDT

I am using contact form 7. I want user details in pdf format which means that when a user fills in the form on the website and submits it then I want the mail in pdf format. Is there any way to do that?

Best way to compare to 0 using Double/double

Posted: 02 Apr 2021 07:27 AM PDT

I am using double in Java to represent speed (construction speed, such as 0.56 percent per second). For some scenarios, I need to compare the current speed to 0 to know if the construction has been paused. So here comes the question : how to compare a double to 0?

I use the below method:

"0.0".equals(String.valueOf(speed))  

as the doc from API as below :

* <li>If <i>m</i> is zero, it is represented by the characters   * {@code "0.0"}; thus, negative zero produces the result   * {@code "-0.0"} and positive zero produces the result   * {@code "0.0"}.  

Is this the best way? Any other ways?


From comment:

double value1 = 0;  Double value2 = 0.0;  System.out.println(value1 == 0);  System.out.println(value2 == 0);  

How to prevent JFX Dialog to hide the application

Posted: 02 Apr 2021 07:28 AM PDT

I have a JFX program that should always be maximized covering the desktop, what happens to me is that when I start a dialog, like

 Alert dlg2 = new Alert(Alert.AlertType.ERROR);   dlg2.setHeaderText("my Dialog");   dlg2.setContentText("Error: unabvle to load");   System.err.println("Unable to load ");   dlg2.showAndWait();  

The application window hides showing just the alert over the desktop. I need to keep the application showing hiding windows's desktop

Is there a way to use Flyway on AS400?

Posted: 02 Apr 2021 07:28 AM PDT

I need to implement migration tool like Flyway in order to use Jenkins to deploy DB changes. I tried to add jt400.jar file and added configuration as follows:

flyway.url=jdbc:as400://192.168.171.251:446/DBDEV  flyway.driver=com.ibm.as400.access.AS400JDBCDriver  

as a driver and it would not connect with this message:

ERROR: No database found to handle jdbc:as400://192.168.171.251:446/DBDEV  

I also tried with using IBM DB2 driver and had configuration

flyway.url=jdbc:db2://192.168.171.251:50000/DBDEV  flyway.driver=com.ibm.db2.jcc.DB2Driver  

this time I am getting this kind of refusal message

ERROR:   Unable to obtain connection from database (jdbc:db2://192.168.171.251:50000/DBDEV) for user 'DEVUSER':   [jcc][t4][2043][11550][4.26.14] Exception java.net.ConnectException: Error opening socket to server   /192.168.171.251 on port 50,000 with message: Connection refused (Connection refused).   ERRORCODE=-4499, SQLSTATE=08001  

With this test migration I am trying to create a simple table by executing this sql

CREATE TABLE PERSON (      ID INT NOT NULL,      NAME VARCHAR(100) NOT NULL  );  

Anyone had this situation and solved it?

How to Roundoff 0.5 to nearest integer in python?

Posted: 02 Apr 2021 07:27 AM PDT

My input looks like below:

Name Sep     Oct  Amy  833.33  833.33  Eve  20774.5  0  

My Expected Output is:

Name Sep     Oct  Amy  833     833  Eve  20775   0  

When I apply np.ceil to round 0.5 to nearest integer, my output becomes:

Name Sep     Oct  Amy  834     834  Eve  20775   0  

How to apply np.ceil only to values having decimal greater than or equal to 0.5? Or is there any other way to get my desired output.

Kubernetes Unable to connect to the server: dial tcp x.x.x.x:6443: i/o timeout

Posted: 02 Apr 2021 07:28 AM PDT

I am using test kubenetes cluster (Kubeadm 1 master and 2 nodes setup), My public ip change time to time and when my public IP changed, I am unable to connect to cluster and i get below error

 Kubernetes Unable to connect to the server: dial tcp x.x.x.x:6443: i/o timeout  

I also have private IP 10.10.10.10 which is consistent all the time.

I have created kubernetes cluster using below command

 kubeadm init --control-plane-endpoint 10.10.10.10  

But still it failed because certificates are signed to public IP and below is the error

 The connection to the server x.x.x.x:6443 was refused - did you specify the right host or port?  

Can someone help to setup kubeadm, and should allow for all IP's something like 0.0.0.0 and I am fine for security view point since it is test setup. or any parament fix.

CocoaPods could not find compatible versions for pod "FirebaseCore"

Posted: 02 Apr 2021 07:27 AM PDT

When I try to build with Unity cloud build, I got this message:

and then

>     Installing cocoapods dependencies:  >64201:        ! .xcworkspace file could not be found.  >64202:        Analyzing dependencies  >64203:        [!] CocoaPods could not find compatible versions for pod "FirebaseCore":  >64204:          In Podfile:  >64205:            Firebase/Analytics (= 6.9.0) was resolved to 6.9.0, which depends on  >64206:              Firebase/Core (= 6.9.0) was resolved to 6.9.0, which depends on  >64207:                FirebaseAnalytics (= 6.1.2) was resolved to 6.1.2, which depends on  >64208:                  FirebaseCore (~> 6.3)  >64209:          >64210:            Firebase/Auth (= 6.9.0) was resolved to 6.9.0, which depends on  >64211:              Firebase/CoreOnly (= 6.9.0) was resolved to 6.9.0, which depends on  >64212:                FirebaseCore (= 6.3.0)  >64213:          >64214:            Firebase/Auth (= 6.9.0) was resolved to 6.9.0, which depends on  >64215:              FirebaseAuth (~> 6.2.3) was resolved to 6.2.3, which depends on  >64216:                FirebaseCore (~> 6.2)  >64217:          >64218:        CocoaPods could not find compatible versions for pod "GoogleAppMeasurement":  >64219:          In Podfile:  >64220:            Firebase/Analytics (= 6.9.0) was resolved to 6.9.0, which depends on  >64221:              Firebase/Core (= 6.9.0) was resolved to 6.9.0, which depends on  >64222:                FirebaseAnalytics (= 6.1.2) was resolved to 6.1.2, which depends on  >64223:                  GoogleAppMeasurement (= 6.1.2)  >64224:          >64225:            Google-Mobile-Ads-SDK (~> 7.42.1) was resolved to 7.42.2, which depends on  >64226:              GoogleAppMeasurement (~> 5.7)  

and then

/BUILD_PATH/jeko.lazaramobile1.appstore-ios/temp20200309-7398-19hbpik/Libraries/Plugins/iOS/GADUNativeCustomTemplateAd.h:5:9: 'GoogleMobileAds/GoogleMobileAds.h' file not found`  

my local builds failed too with missing "GoogleMobileAds/GoogleMobileAds.h"

on my Mac when I check my pod file it looks like :

    target 'UnityFramework' do    pod 'FBSDKCoreKit', '~> 5.5'    pod 'FBSDKLoginKit', '~> 5.5'    pod 'FBSDKShareKit', '~> 5.5'    pod 'Firebase/Analytics', '6.9.0'    pod 'Firebase/Auth', '6.9.0'    pod 'Firebase/Core', '6.9.0'    pod 'Google-Mobile-Ads-SDK', '~> 7.42.1'  end  

I can't figure out what has to be done here. Any help shall be appreciated greatly. I figure out that somehow my firebese.core is stuck to 6.2 or 6.3, but 6.9 is needed. I read that I have to include some framework search path, but this is manual approach and not the cocoapod way and I dont know where manualy to enter the path.

How do I create an enum from a Int in Kotlin?

Posted: 02 Apr 2021 07:27 AM PDT

I have this enum:

enum class Types(val value: Int) {      FOO(1)      BAR(2)      FOO_BAR(3)  }  

How do I create an instance of that enum using an Int?

I tried doing something like this:

val type = Types.valueOf(1)  

And I get the error:

Integer literal does not conform to the expected type String

How do you write code to do factorials in MIPS?

Posted: 02 Apr 2021 07:28 AM PDT

The problem states: Please write a loop to compute the factorial of a positive number currently stored in $t0 and store the result in $t1 in 4 instructions.

This is what I have so far I'm pretty sure it works but its in 6 instructions.

       li $t3, 1         move $t1, $t0         move $t2, $t0   LOOP: addi $t2, $t2, -1         mul $t1, $t1, $t2         bne $t2, $t3, LOOP  

Edit. Here's the solution

 li $t1 1    LOOP: mul $t1 $t1 $t0    addi $t0 $t0 -1    bgez $t0 LOOP   

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Posted: 02 Apr 2021 07:28 AM PDT

I have an error message on django 1.4:

dictionary update sequence element #0 has length 1; 2 is required

[EDIT]

It happened when I tried using a template tag like: `{% for v in values %}:

dictionary update sequence element #0 has length 1; 2 is required    Request Method:     GET  Request URL:    ...  Django Version:     1.4.5  Exception Type:     ValueError  Exception Value:        dictionary update sequence element #0 has length 1; 2 is required    Exception Location:     /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__, line 21  Python Executable:  /usr/bin/uwsgi-core  Python Version:     2.7.3  Python Path:        ['/var/www/',   '.',   '',   '/usr/lib/python2.7',   '/usr/lib/python2.7/plat-linux2',   '/usr/lib/python2.7/lib-tk',   '/usr/lib/python2.7/lib-old',   '/usr/lib/python2.7/lib-dynload',   '/usr/local/lib/python2.7/dist-packages',   '/usr/lib/python2.7/dist-packages',   '/usr/lib/python2.7/dist-packages/PIL',   '/usr/lib/pymodules/python2.7']    Server time:    sam, 13 Jul 2013 16:15:45 +0200  Error during template rendering    In template /var/www/templates/app/index.html, error at line 172  dictionary update sequence element #0 has length 1; 2 is required    172     {% for product in products %}    Traceback Switch to copy-and-paste view    /usr/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response                                response = callback(request, *callback_args, **callback_kwargs)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/contrib/auth/decorators.py in _wrapped_view                        return view_func(request, *args, **kwargs)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/views/decorators/http.py in inner                    return func(request, *args, **kwargs)        ...  ▶ Local vars  ./app/views.py in index                context_instance=RequestContext(request))        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/shortcuts/__init__.py in render_to_response            return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/loader.py in render_to_string                return t.render(context_instance)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/base.py in render                    return self._render(context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/base.py in _render                return self.nodelist.render(context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/base.py in render                        bit = self.render_node(node, context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/debug.py in render_node                    return node.render(context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render                return compiled_parent._render(context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/base.py in _render                return self.nodelist.render(context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/base.py in render                        bit = self.render_node(node, context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/debug.py in render_node                    return node.render(context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render                    result = block.nodelist.render(context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/base.py in render                        bit = self.render_node(node, context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/debug.py in render_node                    return node.render(context)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render                len_values = len(values)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/core/paginator.py in __len__                return len(self.object_list)        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/db/models/query.py in __len__                        self._result_cache = list(self.iterator())        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/db/models/query.py in iterator                            obj = model(*row[index_start:aggregate_start])        ...  ▶ Local vars  /usr/lib/python2.7/dist-packages/django/db/models/base.py in __init__                        setattr(self, field.attname, val)        ...  ▶ Local vars  /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __set__                    value = self.field._attribute_class(value, self.field, obj)        ...  ▶ Local vars  /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__                super(HStoreDictionary, self).__init__(value, **params)        ...  ▶ Local vars  

It happens too when I try to access on a hstore queryset:

[edit]

Traceback (most recent call last):  File "manage.py", line 14, in <module>      execute_manager(settings)    File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 459, in execute_manager      utility.execute()    File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute      self.fetch_command(subcommand).run_from_argv(self.argv)    File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv      self.execute(*args, **options.__dict__)    File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute      output = self.handle(*args, **options)    File "/home/name/workspace/project/app/data/commands/my_command.py", line 60, in handle      item_id = tmp[0].id,    File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 207, in __getitem__      return list(qs)[0]    File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 87, in __len__      self._result_cache.extend(self._iter)    File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 301, in iterator      obj = model(*row[index_start:aggregate_start])    File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 300, in __init__      setattr(self, field.attname, val)    File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 38, in __set__      value = self.field._attribute_class(value, self.field, obj)    File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 21, in __init__      super(HStoreDictionary, self).__init__(value, **params)    ValueError: dictionary update sequence element #0 has length 1; 2 is required  

the code is:

tmp = Item.objects.where(HE("kv").contains({'key':value}))    if tmp.count() > 0:        item_id = tmp[0].id,  

I'm just trying to access the value. I don't understand the "update sequence" message. When I use a cursor instead of hstore queryset, the function works. The error comes on template rendering too. I just restarted uwsgi and everything works well, but the error comes back later.

[edit]

Has someone an idea?

Change "on" color of a Switch

Posted: 02 Apr 2021 07:28 AM PDT

I'm using a standard Switch control with the holo.light theme in a ICS app.

I want to change the highlighted or on state color of the Toggle Button from the standard light blue to green.

This should be easy, but I can't seem to work out how to do it.

No comments:

Post a Comment