Tuesday, August 31, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Javascript looping through a json object

Posted: 31 Aug 2021 08:02 AM PDT

I know this has probably been asked a million times but I spent the whole day and I cannot resolve my problem. So here it is. I have a json object in the following format

const json = [[{"Id":1,"Name":"Jeffreys Bay","ProvinceID":1},{"Id":2,"Name":"Heidelberg","ProvinceID":3}]]  

So I am trying to loop through this json object but just cannot be able to do. I simply can get iy working. For example:

for (let x in json) {          console.log(x + ': ' + json[x]);        }  

returns

core.js:6479 ERROR SyntaxError: Unexpected token o in JSON at position 1      at JSON.parse (<anonymous>)      at SafeSubscriber._next (location.page.ts:71)      at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)      at SafeSubscriber.next (Subscriber.js:122)      at Subscriber._next (Subscriber.js:72)      at Subscriber.next (Subscriber.js:49)      at MapSubscriber._next (map.js:35)      at MapSubscriber.next (Subscriber.js:49)      at FilterSubscriber._next (filter.js:33)      at FilterSubscriber.next (Subscriber.js:49)  

Please help me??

Pandas.read_csv() with special characters

Posted: 31 Aug 2021 08:02 AM PDT

I have a .csv file that includes special characters in a string such as ' when displaying them all these characters are not rendered properly(it removes the ' from the sentence).

Eg:

I'll it rendered ILL

faf'ou => fafou

I used encoding encoding='utf-8-sig and encoding='latin1' when i read the file, but i still have the same problem. I also used encoding='utf-8' But i got the error below

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 176: invalid start byte  

Nested RecyclerView not working with DiffUtils

Posted: 31 Aug 2021 08:02 AM PDT

Hi i am kind of new to Android and i have an issue that probably will get negative qutes for this :)
i was following a Tutorial and then i decided to build an app for a Youtube Api that retrieves playlists and videos inside the playlist. The structure as follow:
-i use tabLayout with fragments "Main Fragment: generates the viewpager" and displays one tab for playlist and one for all videos of the channel
-i have only one navigation graph for all my 6 Fragments (also worth to mention i use safeArgs to pass data between fragments through transition) -i have a ButtomNavigation also
anyway the main concern here i have 2 Adapters one for playlists(which i use inside the PlaylistFragment (consider as parent Fragment) to setup the recyclerView) and one for the items inside the playlist(which used for the PlaylistitemsFragment(child))
so normaly parent fragment displays the playlist and when navigated with itemclick it goes to corresponding videos inside this playlist
Main issue i've decided to nest the PlaylistItems inside the playlist horizontally so it would be the playlist vertically and their relatives items horizontally.
i did create a new Recycler View inside the main_item for the parent RecyclerView
inside my first adapter i did exactly the same everywhere i searched its kind of the same concept, but for some reasons when call the second adapter(playlistitems) it doesn't get to onCreateViewHolder or onBindViewHolder and eventually doesn't inflate the child RecyclerView and when i debugged i found the getItemCount doesn't return anything

  override fun getItemCount(): Int {      return differ.currentList.size  }          

I just dont understandt why the child recyclerview is generated but no inflated and why differ.currentList.size returns zero

class PlaylistAdapter() : RecyclerView.Adapter<PlaylistAdapter.PlaylistViewHolder>() {      private lateinit var parentContext: Context      inner class PlaylistViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)    private val differCallBack = object : DiffUtil.ItemCallback<PlaylistsItem1>() {      //Override  }    val differ = AsyncListDiffer(this, differCallBack)    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistViewHolder {      parentContext = parent.context      val layoutInflater = LayoutInflater.from(parentContext)      return PlaylistViewHolder(layoutInflater.inflate(R.layout.main_row, parent, false))  }    override fun onBindViewHolder(holder: PlaylistViewHolder, position: Int) {      val currentItem = differ.currentList[position]        holder.itemView.apply {          tvOverline.text = currentItem.snippet.publishedAt          tvTitle.text = currentItem.snippet.title          tvDescription.text = currentItem.snippet.description                    try {              Glide.with(this).load(currentItem.snippet.thumbnails.medium.url).into(thumbnail_playlist)            }catch (e : Exception){              e.printStackTrace()          }          cardViewMain.setOnClickListener {              onItemClickListener?.let {                  it(currentItem)              }          }      }        val videoAdapter = PlaylistItemAdapter()      holder.itemView.rv_main_playlist.apply {          val videoLayoutManager = LinearLayoutManager(parentContext,              RecyclerView.HORIZONTAL,false)              //videoLayoutManager.initialPrefetchItemCount = 4          layoutManager = videoLayoutManager          adapter = videoAdapter            setRecycledViewPool(RecyclerView.RecycledViewPool())      }      if (holder.itemView.rv_main_playlist.itemDecorationCount == 0) {          val itemDecorator = DividerItemDecoration(parentContext, DividerItemDecoration.HORIZONTAL)          itemDecorator.setDrawable(ContextCompat.getDrawable(parentContext, R.drawable.divider_vertical_trans)!!)          holder.itemView.rv_main_playlist.addItemDecoration(itemDecorator)      }  }    override fun getItemCount(): Int {      return differ.currentList.size  }    private var onItemClickListener: ((PlaylistsItem1) -> Unit)? = null    fun setOnItemClickListener(listener: (PlaylistsItem1) -> Unit) {      onItemClickListener = listener  }}  

class PlaylistItemAdapter() :  RecyclerView.Adapter<PlaylistItemAdapter.PlaylistItemViewHolder>() {    val TAG = "PlaylistItemAdapter"    private lateinit var parentContext: Context    inner class PlaylistItemViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView)    private val differCallBack = object : DiffUtil.ItemCallback<PlaylistItem2>(){          //overrriden functions  }    val differ = AsyncListDiffer(this,differCallBack)      override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistItemViewHolder {      parentContext = parent.context      return PlaylistItemViewHolder(          LayoutInflater.from(parent.context).          inflate(R.layout.playlist_item_row,              parent,false))  }      override fun onBindViewHolder(holder: PlaylistItemViewHolder, position: Int) {      val currentItem = differ.currentList[position]      holder.itemView.apply {          tvOverline2.text = currentItem.snippet.publishedAt          tvTitle2.text = currentItem.snippet.title          tvDescription2.text = currentItem.snippet.description          try {              Glide.with(this).load(currentItem.snippet.thumbnails.medium.url).into(ivItemThumbnail)          }catch (e : Exception){              e.printStackTrace()          }          imageView.setOnClickListener {              onItemClickListener?.let { it(currentItem) }          }        }  }  override fun getItemCount(): Int {      return differ.currentList.size  }  private var onItemClickListener:((PlaylistItem2)->Unit)? = null    fun setOnItemClickListener(listener:(PlaylistItem2) -> Unit){      onItemClickListener = listener  }}  

class MainActivity :AppCompatActivity() {  lateinit var viewModel : YtViewModel  private lateinit var navController: NavController  private  val TAG = "MainActivity"  override fun onCreate(savedInstanceState: Bundle?) {      super.onCreate(savedInstanceState)      setContentView(R.layout.activity_main)        val navHostFragment =          supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment      navController = navHostFragment.findNavController()        setSupportActionBar(toolbarMain)        setupActionBarWithNavController(navController)        val repository = YtRepository(YtDatabase(this))        val viewModelFactory = YtViewModelFactory(repository)        viewModel = ViewModelProvider(this,viewModelFactory).get(YtViewModel::class.java)        bottomNavigationView.setupWithNavController(navHostFragment.findNavController())          }    override fun onSupportNavigateUp(): Boolean {      return navController.navigateUp() || super.onSupportNavigateUp()  }}  

I'm unable to retrieve a list of users from the API to the client app(Angular). I am new to angular

Posted: 31 Aug 2021 08:01 AM PDT

When I view the Network tab I one of the users is in red(color). On the console there's is an error 401(Unauthorized). Here is the code for the different files; the memberService.ts, member-list-component.ts. There us no error when it comes to compiling.

memberService.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';  import { Injectable } from '@angular/core';    import { environment } from 'src/environments/environment';  import { Member } from '../_models/member';    const htttpOptions ={    headers: new HttpHeaders({    Authorization: 'Bearer'+JSON.parse(localStorage.getItem('user')).token    })  }  @Injectable({    providedIn: 'root'  })  export class MembersService {    baseUrl = environment.apiUrl;      constructor(private http: HttpClient) { }    getMembers()    {      return this.http.get<Member[]>(this.baseUrl+ 'users', htttpOptions);    }      getMember(username :string){      return this.http.get<Member>(this.baseUrl + 'users/' + username, htttpOptions);    }      }  

member-list-component.ts

import { MembersService } from './../../_services/members.service';  import { Component, OnInit } from '@angular/core';  import { Member } from 'src/app/_models/member';    @Component({    selector: 'app-member-list',    templateUrl: './member-list.component.html',    styleUrls: ['./member-list.component.css']  })  export class MemberListComponent implements OnInit {    members: Member[];      constructor(private MemberService: MembersService) { }      ngOnInit(): void {      this.loadMembers();    }    loadMembers()    {      this.MemberService.getMembers().subscribe(members=>{        this.members = members;      })    }    }  

I get it that my access is an authorized but one thing to note is that Postman returns a list of users to me as shown below. console tab when inspecting console tab

Network Tab information 1.0 Network Tab information 1.0

Network Tab information 2.0 Network Tab information 2.0

PostMan returns my list of Users successfully so the API is Ok. I don't know why the client side isn't doing that as well PostMan Results

Return the current value from FormGroup.ValueChanges Observable

Posted: 31 Aug 2021 08:01 AM PDT

I have a case that requires to pass the valueChanges of form group to a service to do some logic there on every changes, but I'm stuck with how to pass the current value of the form group with same observable.

I can't pass the current value to the service, because the service should subscribe to it later and do some logic depending on it.

this.myService.handleChanges(this.form.valueChanges)  

Kindly, how to do that? Thanks.

VBA to loop through range then run code updating worksheet reference

Posted: 31 Aug 2021 08:01 AM PDT

sorry I am a newbie looking for help. I am having a complete mind block so reaching out for some help.

I have a document that contains a couple of macros; 1st extracts data from a data sheet (datasheet) and copies to a specific worksheet (reportsheet) when the criteria is met. The 2nd macro will save this as a PDF, create an email and send to the person.

I have 100+ sheets and would require to duplicate these macros 100 times.

I want to combine these into 1 macro, however, i would like to loop through a range ("B6:B123") and if in that range the cell <> 0 then the macro need to run but the reportsheet reference i'd like to update dynamically using the adjacent cell value (Dx) that would trigger these to run.

Macro 1

Sub Search_extract_135()    Dim datasheet As Worksheet  Dim reportsheet As Worksheet  Dim ocname As String  Dim finalrow As Integer  Dim i As Integer    Set datasheet = Sheet121 ' stays constant  Set reportsheet = Sheet135 'need to update based on range that <>0 then taking cell reference as    ocname = reportsheet.Range("A1").Value 'stays constant    reportsheet.Range("A1:U499").EntireRow.Hidden = False  reportsheet.Range("A5:U499").ClearContents    datasheet.Select  finalrow = Cells(Rows.Count, 1).End(xlUp).Row    For i = 2 To finalrow      If Cells(i, 1) = ocname Then      Range(Cells(i, 1), Cells(i, 21)).Copy      reportsheet.Select      Range("A500").End(xlUp).Offset(1, 0).PasteSpecial xlPasteAll      datasheet.Select      End If        Next i    reportsheet.Select  Range("A4").Select  Call HideRows  

End Sub

Macro 2

Sub Send_Email_135()  Dim wPath As String, wFile As String, wMonth As String, strPath As String, wSheet As Worksheet                Set wSheet = Sheet135      wMonth = Sheets("Journal").Range("K2")      wPath = ThisWorkbook.Path ThisWorkbook.Path      wFile = wSheet.Range("A1") & ".pdf"      wSheet.Range("A1:U500").ExportAsFixedFormat Type:=xlTypePDF, Filename:=wPath & "-" & wFile, _          Quality:=xlQualityStandard, IncludeDocProperties:=True, _          IgnorePrintAreas:=False, OpenAfterPublish:=False      strPath = wPath & "-" & wFile        Set dam = CreateObject("Outlook.Application").CreateItem(0)      '      dam.To = wSheet.Range("A2")      dam.cc = wSheet.Range("A3")      dam.Subject = "Statement " & wMonth      dam.Body = "Hi" & vbNewLine & vbNewLine & "Please find attached your statement." & Chr(13) & Chr(13) & "Regards," & Chr(13) & "xxxxx"        dam.Attachments.Add strPath      dam.Send      MsgBox "Email sent"    End Sub  

I am hoping this makes sense.

will try to summarise below;

The format of the excel document has names in column A, numeric values in column B and SheetCode in column D. When cell within Range("B6:B123") <> 0 then run the 2 macros above but need reportsheet from macro 1 & wSheet from macro 2 to use the same value in column D to references the specific worksheet code for the person that doesn't equal 0.

If this isn't going to work i will create multiple macros.

Thank you in advance.

Create a new table in the database

Posted: 31 Aug 2021 08:02 AM PDT

I have a form in a php file. When sending the form, I call a test.php file that checks the validity of the data received and inserts them into a table of my database. I would also like to create a new table in the database, with the name $category_ $username. The file is the following:

<?php    if(isset($_POST['mySubmit'])) {      $db = mysqli_connect('localhost','root','','DBsito');      if (!$db)      {          die('Could not connect to database: ' . mysqli_error());      }        $db_select = mysqli_select_db($db, 'DBsito');        //Salva il nome del file      $imagename = $_FILES['icona']['name'];      //tipo del file      $imagetype = $_FILES['icona']['type'];      $imagetemp = $_FILES['icona']['tmp_name'];            //Path dell'upload      $imagePath = "img/upload/";            if(is_uploaded_file($imagetemp)) {          if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {              echo "Sussecfully uploaded your image.";          }          else {              echo "Failed to move your image.";          }                }      else {          echo "Failed to upload your image.";      }        $categoria = mysqli_real_escape_string($db, $_POST['categoria']);      $username = mysqli_real_escape_string($db, $_POST['utente']);        $result = mysqli_query($db, "SELECT categoria.nome_categoria, categoria.user_utente FROM categoria WHERE BINARY categoria.nome_categoria = BINARY '$categoria' AND BINARY categoria.user_utente = BINARY '$username' ");        if(!empty($categoria) && mysqli_num_rows($result)) {          $name_error = "Categoria già esistente!";        }      else if (!empty($categoria)){          $query = "INSERT INTO categoria (nome_categoria, user_utente, icona) values ('$categoria','$username', '$imagename')";          $db->query("CREATE TABLE '$categoria'_'$username'");            // sql to create table          $sql = "CREATE TABLE $categoria'_'$username (          )";                    if ($db->query($sql) === TRUE) {          echo "Table MyGuests created successfully";          } else {          echo "Error creating table: " . $db->error;          }            if(!mysqli_query($db, $query)){              die("DAMMIT");          }          else{               { header("Location: confermaCategoria.php"); }          }          mysqli_query($db, $query);      }      else {          $name_error = "";      }      mysqli_close($db);    }  ?>  

The data is inserted into the existing table in the database, but I cannot create the new table. How can I do? Where am I wrong?

ImportError: cannot import name '_imaging' from 'PIL' (/usr/lib/python3/dist-packages/PIL/__init__.py)

Posted: 31 Aug 2021 08:02 AM PDT

in pycharm I'm trying to configure odoo 14, python 3.8,

ImportError: cannot import name '_imaging' from 'PIL' (/usr/lib/python3/dist-packages/PIL/init.py)

receiving the above error in the console. how to overcome this error.

Thank you

How to retrieve all of my hard drive partitions after installing Ubuntu?

Posted: 31 Aug 2021 08:01 AM PDT

I installed ubuntu. However, while installing it, I chose "Something else", and I didn't choose erase all of the data, but I found after opening it that I don't have my data on it, so how to retrieve these data again ?

GUIzero: "'int' object is not subscriptable" with variables that are forced to be strings

Posted: 31 Aug 2021 08:02 AM PDT

I am working on a piece of GUIzero code intended to attach the values of a 2D array to a selection of textbox widgets. However, despite the fact that all variables in the widget value equations are forced to be strings, it still is telling me that a value is an integer.

    leaderboard_array = ["***", 0]*5      leaderboard_box1 = Text(leaderboard_window)      leaderboard_box1.value = str(str(leaderboard_array[0][0]) + ": " + str(leaderboard_array[0][1]))      leaderboard_box2 = Text(leaderboard_window)      leaderboard_box2.value = str(str(leaderboard_array[1][0]) + ": " + str(leaderboard_array[1][1]))      leaderboard_box3 = Text(leaderboard_window)      leaderboard_box3.value = str(str(leaderboard_array[2][0]) + ": " + str(leaderboard_array[2][1]))      leaderboard_box4 = Text(leaderboard_window)      leaderboard_box4.value = str(str(leaderboard_array[3][0]) + ": " + str(leaderboard_array[3][1]))      leaderboard_box5 = Text(leaderboard_window)      leaderboard_box5.value = str(str(leaderboard_array[4][0]) + ": " + str(leaderboard_array[4][1]))  

The exact error code is this: leaderboard_box2.value = str(str(leaderboard_array[1][0]) + ": " + str(leaderboard_array[1][1])) TypeError: 'int' object is not subscriptable

React-Redux increment / decrement issue

Posted: 31 Aug 2021 08:01 AM PDT

I'm doing some React-Redux practice and I've noticed a behaviour I can't understand: it works or not depending if i use + 1 / - 1 or ++ / -- operators.

This is my reducer:

const counterReducer = (state = { counter: 0 }, action) => {    switch (action.type) {      case "INCREMENT":        return {          counter: state.counter + 1,        };      case "DECREMENT":        return {          counter: state.counter - 1,        };      default:        return state;    }  };  

and it works fine.

but if i change the incement and decrement to:

const counterReducer = (state = { counter: 0 }, action) => {    switch (action.type) {      case "INCREMENT":        return {          counter: state.counter++,        };      case "DECREMENT":        return {          counter: state.counter--,        };      default:        return state;    }  };  

It will still fire the acrion without updating the Redux state.

django __date return None in MySQL

Posted: 31 Aug 2021 08:01 AM PDT

Simple question:

Model.objects.values('some_datetime_field__date',)

returns the correct values of dates with sqlite, but it returns Nones in MySQL 5.7

Python bar chart with dataframe

Posted: 31 Aug 2021 08:01 AM PDT

I have the following dataframe:

df = pd.DataFrame(dict(      A=[1, 0, 0, 1],      B=[0, 1, 1, 1],      C=[1, 0, 0, 0]  ))  

How to plot a barplot where I sea number of 1s and 0s in one graph see: enter image description here

How to switch the monetization flag of a YouTube live streaming programmatically without closing the stream

Posted: 31 Aug 2021 08:01 AM PDT

I am interested in switching the monetization flag of my YouTube live streaming programmatically without closing or interrupting the live streaming on my YouTube channel. Can this be achieved using the YouTube API? What is the right way to handle this automatically using a custom scheduler ? Thanks in advance.

select smalldatetime between two strings

Posted: 31 Aug 2021 08:02 AM PDT

DROP TABLE IF EXISTS b;    CREATE TABLE b(      MajDate smalldatetime  );    INSERT INTO b(MajDate) VALUES  (try_convert(smalldatetime,'2016-11-30 11:23:00')),  (try_convert(smalldatetime,'2021-07-07 11:07:00')),  (try_convert(smalldatetime,'2021-07-07 11:07:00'))    select   b.MajDate,  CASE WHEN b.MajDate BETWEEN '2021-07-01 00:00:00' AND '2021-08-01 00:00:00'          THEN 'YES'      ELSE 'NO'  END AS InRange  From b;  

What am I doing wrong ?

enter image description here

Desired Output: Column InRange should contain YES for two last rows.

Deploying when NPM package is outdated

Posted: 31 Aug 2021 08:01 AM PDT

I want to deploy an Angular 12 app that uses d3-org-chart, which in turn imports d3-flextree. When I start my project using ng build it generates the following error:

./node_modules/d3-flextree/src/flextree.js:247:19-26 - Error: Should not import the named export 'version' (imported as 'version') from default-exporting module (only default export is available soon)  

I can see that the error was fixed in the project GitHub repository in this commit, and I made the same change locally and it works fine.

Another developer has raised an issue on the project page to get the NPM package updated.

My issue is that the code was fixed in github, but not updated on NPM. So when I use npm install, or when I deploy my app in a docker container which then runs ng build it pulls down the outdated NPM version and the error occurs, preventing startup.

Obviously, this will be fixed when the maintainer updates the NPM package, but until this happens what is the least ugly solution to enable me to deploy my docker container without the error?

Class Object creation with python, How to specify a specific type as entry? [duplicate]

Posted: 31 Aug 2021 08:02 AM PDT

I would like to create a class in Python. Is it possible to specify the type of argument given in init ? Otherwise raise an error or smth like this ?

I would like to create this type of class : where ligne_225 is a list data is a dataframe

class Poste_HTB_HTA:    def __init__(self, ligne_225,data):      self.ligne_225 = ligne_225        self.data = data        def ligne_225(self):      return self.ligne_225  

Extend the angular service worker with inportScripts()?

Posted: 31 Aug 2021 08:02 AM PDT

First I start with angular, thank you for being lenient if I misrepresent my problem

I want to turn my app into PWA For this, I followed the angular documentation that follows: https://blog.angular-university.io/angular-service-worker/

I managed to create the ngsw-worker.js and ngsw.json files in the dist folder by doing an "ng-build" as explained in the tutorial in step 4

At the same time, I created a custom Service worker called custom-service-worker.js file. I want to integrate angular sw (ngsw-worker.js) into my Service worker For this, I use importScripts() like this: enter image description here

But I have the following error: enter image description here

Here is the tree of my project:

enter image description here

I forgot the angular.json file :

enter image description here

What's wrong with that ?

How can I customize tkinter dropdown menu?

Posted: 31 Aug 2021 08:02 AM PDT

I want to create a dropdown menu in tkinter of custom width and height and certain styling options like fore background etc. but when I am running my this code it is giving AttributeError: 'NoneType' object has no attribute 'config' and when I run my code without config it gives 'TypeError: 'dict_keys' object is not subscriptable

These are my both two codes please help me in this problem.

from tkinter import *  from tkinter import ttk  import tkinter    root=Tk()    root.geometry('500x500')    seletion=StringVar()    def show():      label=Label(root,text=seletion.get()).pack(pady=10)       drop=OptionMenu(root,seletion,'one','two','three',width=10).pack(pady=10)  button=Button(root,text='show',command=show).pack(pady=10)  root.mainloop()  

Second code:

from tkinter import *  from tkinter import ttk  import tkinter    root=Tk()    root.geometry('500x500')    seletion=StringVar()    def show():      label=Label(root,text=seletion.get()).pack(pady=10)      pass    drop=OptionMenu(root,seletion,'one','two','three').pack(pady=10)  button=Button(root,text='show',command=show).pack(pady=10)  drop.config(width=10)  root.mainloop()  

How to convert WAVE file with 3 channels to MP3 file (using LameMP3FileWriter)?

Posted: 31 Aug 2021 08:02 AM PDT

I'm currently working on an application which records audio from devices. One device gives us a IWaveIn with 1 channel and the other of 2 channels, resulting in a WAVE file of 3 channels using new MultiplexingWaveProvider(waveIns.Select(waveIn => new WaveInProvider(waveIn)));

But when I try to convert it using LameMP3FileWriter, it complains about only supporting up to 2 channels:

System.ArgumentException: Unsupported number of channels 3  Parameternaam: format     bij NAudio.Lame.LameMP3FileWriter..ctor(Stream outStream, WaveFormat format, LameConfig config)     bij NAudio.Lame.LameMP3FileWriter..ctor(Stream outStream, WaveFormat format, LAMEPreset quality, ID3TagData id3)  

using (var readStream = GetReadStream(file))  using (var reader = new WaveFileReader(readStream))  using (var writeStream = GetWriteStream(convertedFileName))  using (var writer = new LameMP3FileWriter(writeStream, reader.WaveFormat, LAMEPreset.ABR_128))  {      reader.CopyTo(writer);  }  

Would anyone have an idea how I can fix this?

Either:

  • Force the 2 channel waveIn to be 1 channel so I can use MixingWaveProvider32 instead of MultiplexingWaveProvider
  • Force the 1 channel waveIn to be 2 channel so I can use MixingWaveProvider32 instead of MultiplexingWaveProvider
  • Somehow be able to convert a 3 channel WAVE file to MP3

Is it possible to access a value from a script with a function?

Posted: 31 Aug 2021 08:02 AM PDT

I need to save the email from this script:

<script>    window.renderOptIn = function() {      window.gapi.load('surveyoptin', function() {        window.gapi.surveyoptin.render(          {            "merchant_id": 0000,            "order_id": "100101205",            "email": "tester@example.com",            "delivery_country": "XX",            "estimated_delivery_date": "2021-09-03"          });      });    }  </script>  

Is there a way to do that? It's physically in the code but I can't think of a way to get it.

Context:

It's e-commerce related. The script is on the "thank-you" page. I need to save the email to a variable so I can use it for google's enhanced conversion tracking.

HTML keep checkbox checked after form submit

Posted: 31 Aug 2021 08:02 AM PDT

I have some checkboxes in my code, that activate input fields after getting checked. For default they are disabled, so that the user chooses, which input field to activate and so which filter to activate or not. After the submit of the form the checkbox is always disabled again. Does anybody know how to keep them activated after submit, but also make them disabled by default?

<div>      <input type="checkbox" onclick="var input = document.getElementById('Filter');   if(this.checked){ input.disabled = false; input.focus();}else{input.disabled=true;}" />      <span class="text-white">Filter</span>      <input id="Filter" name="Filter" disabled="disabled" />  </div>  

How to copy 2D array Using loops, copy all of the scores for exam 1 and 2 into the new 2D array. (Do not include the -1 values)

Posted: 31 Aug 2021 08:02 AM PDT

import java.util.Arrays;  public class Review {     public static void main(String[] args) {                //First, declare and initialize a 4x3 2D array of doubles called `scores` which will contain the exam data for four students. The rows will represent the student and the columns will represent the exam number. You already know the first exam scores (80.4, 96.2, 100.0, 78.9). Use initializer lists to store the first exam scores in the first column and -1 for the remaining exams. Use the provided print statement to print the result in the console.        double[][] scores = {{80.4, -1, -1}, {96.2, -1, -1}, {100.0, -1, -1}, {78.9, -1, -1}};              System.out.println(Arrays.deepToString(scores));              //The next set of exams have occurred. Using 4 lines of code, manually enter the scores (89.7, 90.5, 93.6, 88.1) for the second exam (column 1). Use the provided print statement to print the updated 2D array as well.        scores[0][1] = 89.7;        scores[1][1] = 90.5;        scores[2][1] = 93.6;        scores[3][1] = 88.1;              System.out.println(Arrays.deepToString(scores));                      //You have realized that you will only be keeping track of 2 exam grades instead of 3. Declare and initialize an empty 4x2 2D array of double values  called newScores        double[][] newScores = new double[4][2];              //Using loops, copy all of the scores for exam 1 and 2 into the new 2D array. (do not include the -1 values)        for(int i = 0; i < scores[0].length; i++) {          for(int j = 0; j < scores.length; j++) {            newScores[i][0] = scores[i][1];          }        }              System.out.println(Arrays.deepToString(newScores));              //You have allowed the students to complete an extra credit activity to contribute towards their scores. For all exam grades less than 90, add 2 additional points to the grade in `newScores`                System.out.println(Arrays.deepToString(newScores));        }     }  

Here's the question I have and what I have tried. Using loops, copy all of the scores for exam 1 and 2 into the new 2D array. (Do not include the -1 values)

//Using loops, copy all of the scores for exam 1 and 2 into the new 2D array. (do not include the -1 values)    for(int i = 0; i < scores[0].length; i++) {       for(int j = 0; j < scores.length; j++) {          newScores[i][0] = scores[i][1];       }     }       System.out.println(Arrays.deepToString(newScores));  

Here's the hint. Remember to copy values over using: twoDArrayOne[i][j] = twoDArrayTwo[i][j]; when in a nested loop.

Here's the output am getting from the console.

[[80.4, -1.0, -1.0], [96.2, -1.0, -1.0], [100.0, -1.0, -1.0], [78.9, -1.0, -1.0]]  [[80.4, 89.7, -1.0], [96.2, 90.5, -1.0], [100.0, 93.6, -1.0], [78.9, 88.1, -1.0]]  [[89.7, 0.0], [90.5, 0.0], [93.6, 0.0], [0.0, 0.0]]  [[89.7, 0.0], [90.5, 0.0], [93.6, 0.0], [0.0, 0.0]]  

How to run binary using path with backslash stored in variable?

Posted: 31 Aug 2021 08:02 AM PDT

$ cat test.sh  #! /bin/bash    if [ -f /home/amnesia/Persistent/yubikey-manager-qt.AppImage ]; then    ykman="/home/amnesia/Persistent/yubikey-manager-qt.AppImage ykman"  elif [ -f /Applications/YubiKey\ Manager.app/Contents/MacOS/ykman ]; then    ykman="/Applications/YubiKey\ Manager.app/Contents/MacOS/ykman"  else    printf "$bold$red%s$normal\n" "Could not find YubiKey Manager binary"    exit 1  fi    $ykman list    $ test.sh  ./test.sh: line 12: /Applications/YubiKey\: No such file or directory  

./test.sh: line 12: /Applications/YubiKey: No such file or directory

How can I fix above error?

Using following approach solves issue on macOS but breaks things on Tails because of ykman AppImage requirement.

$ cat test.sh  #! /bin/bash    if [ -f /home/amnesia/Persistent/yubikey-manager-qt.AppImage ]; then    ykman="/home/amnesia/Persistent/yubikey-manager-qt.AppImage ykman"  elif [ -f /Applications/YubiKey\ Manager.app/Contents/MacOS/ykman ]; then    ykman="/Applications/YubiKey Manager.app/Contents/MacOS/ykman"  else    printf "$bold$red%s$normal\n" "Could not find YubiKey Manager binary"    exit 1  fi    "$ykman" list  

Thanks for helping out!

Material.io Tabs: where to put the tab content?

Posted: 31 Aug 2021 08:01 AM PDT

I'm trying to use material.io tabs in a project, anyway the html structure is not well documented:

https://material.io/components/tabs/web#design-api-documentation

<div class="mdc-tab-bar" role="tablist">    <div class="mdc-tab-scroller">      <div class="mdc-tab-scroller__scroll-area">        <div class="mdc-tab-scroller__scroll-content">          <button class="mdc-tab mdc-tab--active" role="tab" aria-selected="true" tabindex="0">            <span class="mdc-tab__content">              <span class="mdc-tab__icon material-icons" aria-hidden="true">favorite</span>              <span class="mdc-tab__text-label">Favorites</span>            </span>            <span class="mdc-tab-indicator mdc-tab-indicator--active">              <span class="mdc-tab-indicator__content mdc-tab-indicator__content--underline"></span>            </span>            <span class="mdc-tab__ripple"></span>          </button>        </div>      </div>    </div>  </div>  

where am i supposed to put the tab body content? It seems they shows only how to build a tab bar but not the whole functionality?

Adjusting height of mat-form-field Angular Material

Posted: 31 Aug 2021 08:01 AM PDT

I am running into an issue with a simple adjust of a mat-form-field that holds my autocomplete input. From the image you can see if it's outside the mat-toolbar height, but I have not found a simple way to adjust the height of the entire input so it can stay inside the toolbar area. Width works fine. Height does not.

input outside toolbar

enter image description here

My html code is as follows:

 <mat-toolbar  >        <span style="width:200px">Test</span>           <label>{{prodPointId}}</label>          <form class="example-form"  >              <mat-form-field  appearance="outline"  margin=" 10px" class="example-full-width searchField" >                  <mat-label>Search...</mat-label>                  <input type="text"   matInput [formControl]="myControl" [matAutocomplete]="auto" [(ngModel)]="value" >                <button mat-button *ngIf="value" matSuffix mat-icon-button aria-label="Clear" (click)="value=''">                    <mat-icon>close</mat-icon>                  </button>                <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">                  <mat-option                        *ngFor="let option of filteredOptions | async"                       [value]="option.prodPointName"                       (click)="pointSelected(option.prodPointId)"                       [routerLink]="['/coredata', option.prodPointId]" >                      <mat-icon>home</mat-icon>                      {{option.prodPointCode}} : {{option.prodPointName}}                   </mat-option>                </mat-autocomplete>                            </mat-form-field>            </form>                      </mat-toolbar>  

When I pull up chrome dev tools I attempted to adjust the height in the CSS for the component using div.mat-form-field and several other options, but nothing has seemed to work. Looking at the documentation at Angular Material, I haven't found anything that shows me how to control this simple styling adjustment. What am I missing. Is it so simple and I just overthinking it? Thanks!

Junit 5 - No ParameterResolver registered for parameter

Posted: 31 Aug 2021 08:02 AM PDT

Source : JUnit 5, Eclipse 4.8 , Selenium

I can write up and execute Selenium script without any special test framework but I wanted to use Junit 5 (because we have dependency with other tools) and I have never seen such error "org.junit.jupiter.api.extension.ParameterResolutionException" while working with Junit 4. Currently it's Junit 5 and I googled it to get some sort of idea but can not resolve the issue.

Test Script :

package login;  import static org.junit.jupiter.api.Assertions.assertEquals;  import org.junit.jupiter.api.AfterEach;  import org.junit.jupiter.api.BeforeEach;  import org.junit.jupiter.api.Test;  import org.openqa.selenium.By;  import org.openqa.selenium.WebDriver;  import org.openqa.selenium.WebElement;        public  class loginTest  {        public  WebDriver driver = null   ;          public loginTest(WebDriver driver)      {          this.driver=driver;      }          @BeforeEach      public void setUp() throws Exception       {            driver.get("google.com");          System.out.println("Page title is: " + driver.getTitle());      }        @Test      public void test() {              // some action here I have in original script          System.out.println("Page title is: " + driver.getTitle());        }        @AfterEach      public void tearDown() throws Exception       {          driver.quit();      }  }  

Stack trace:

org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [org.openqa.selenium.WebDriver arg0] in executable [public login.loginTest(org.openqa.selenium.WebDriver)].      at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:191)      at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:174)      at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:135)      at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:61)      at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:208)      at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:195)      at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$0(ClassTestDescriptor.java:185)      at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$1(ClassTestDescriptor.java:189)      at java.util.Optional.orElseGet(Unknown Source)      at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$2(ClassTestDescriptor.java:188)      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:81)      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:58)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.prepare(HierarchicalTestExecutor.java:89)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:74)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)      at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)      at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)      at java.util.Iterator.forEachRemaining(Unknown Source)      at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)      at java.util.stream.AbstractPipeline.copyInto(Unknown Source)      at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)      at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)      at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)      at java.util.stream.AbstractPipeline.evaluate(Unknown Source)      at java.util.stream.ReferencePipeline.forEach(Unknown Source)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)      at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)      at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)      at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)      at java.util.Iterator.forEachRemaining(Unknown Source)      at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)      at java.util.stream.AbstractPipeline.copyInto(Unknown Source)      at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)      at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)      at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)      at java.util.stream.AbstractPipeline.evaluate(Unknown Source)      at java.util.stream.ReferencePipeline.forEach(Unknown Source)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)      at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)      at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)      at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:86)      at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)  

Selenium adding items from a Web element list to a string array list

Posted: 31 Aug 2021 08:01 AM PDT

I'm doing some automated testing and I'm trying to save some items from a web element list to a string array, there should be some parsing involved but I'm not sure how, see code snippet below

public void I_should_see_the_following_folders(DataTable expectedData) throws Throwable {      int tbl1; int tbl2;      List<List<String>> featureTable = expectedData.raw();      WebElement folders = driver.findElement(By.id("folders"));      List <WebElement> emailFolders = folders.findElements(By.className("folder-name"));        List<String> foo = new ArrayList<String>();      for (List<String> featuresList : expectedData.raw())          foo.add(featuresList.get(0));            tbl1 = emailFolders.size();          tbl2 = featureTable.size();        List<String> webList = new ArrayList<String>();      for(int i=0;i<tbl1;i++){          webList.add(emailFolders.get(0));      }        }  

what I'm trying to do is take a datatable list of items, convert it into a string array and then take a list of items from the webpage and also store it into a string array and then compare each array to determine if the elements are present and are the same in not particular order.

I think I got the data table array list to work, but need some help with the web elements array list.

Thanks!!!

Can not identify the object in QTP

Posted: 31 Aug 2021 08:01 AM PDT

I'm using QTP 9.2. While running script i got this error repeatedly

Cannot identify the object "Login1$Password" (of class WebEdit). Verify that this object's properties match an object currently displayed in your application.

When i run the script for first time it runs perfectly but now this error occurred. I have tried all the possible solution check object properties through object repository and object spy and enable smart identification result shows:

object not unique (3 objects found) or object not found..

Modal Popup On usercontrol in WPF

Posted: 31 Aug 2021 08:01 AM PDT

How can I open a modal popup on a user control (not on a mainwindow) in wpf using mvvm pattern?

I hope my question is clear to all as I want to open popup on usercontrol not on window.

No comments:

Post a Comment