Tuesday, August 31, 2021

OSCHINA 社区最新专区文章

OSCHINA 社区最新专区文章


LibreELEC 10.0.0 发布,放弃对老款树莓派的支持

Posted: 30 Aug 2021 02:20 PM PDT

LibreELEC 10.0.0 正式发布,为 LibreELEC 用户带来 Kodi (Matrix) v19.1。正在使用 LibreELEC 10 Beta 或 RC1 的用户会自动更新到最新版本。LibreELEC 9.2 则将不会自动更新,用户需要手动更新。 树莓派 0-3 LibreELEC 10.0.0 没有 Raspberry Pi 0-3 版本。RPi 的图形驱动仍在完全重写的过程中,此外,目前的开发工作主...

提供api接口可以二次开发的无人机都有哪些?(飞行平台)

Posted: 30 Aug 2021 07:06 PM PDT

我想往无人机里写自己的开发的程序,控制飞行。。。 但是感觉大疆的那种飞行平台太贵了,有没有便宜一些的呢? 求大佬告知,,,我给您磕头了!

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.

V2EX - 技术

V2EX - 技术


八月最后一天, win11 下的 android 还没来

Posted: 31 Aug 2021 04:54 AM PDT

会不会就和 win10x 一样被砍掉了?

请大家帮忙投票, A 是我画好的 UI, B 是领导找的参考

Posted: 31 Aug 2021 04:54 AM PDT

领导非说 B 好看,让我参考,我参考出来的结果就是 A,他要和 B 一摸一样,不要五花八门的颜色,搞不懂...请大家帮忙投票。 A: https://z3.ax1x.com/2021/08/31/hUvDTP.jpg https://z3.ax1x.com/2021/08/31/hUv0eI.jpg https://z3.ax1x.com/2021/08/31/hUvsFf.jpg https://z3.ax1x.com/2021/08/31/hUvdOA.jpg B: https://z3.ax1x.com/2021/08/31/hUvayd.jpg https://z3.ax1x.com/2021/08/31/hUvBwt.jpg

百度这样的网站最外层是什么设备在承载运营商路由过来的流量呢?

Posted: 31 Aug 2021 04:52 AM PDT

4 层交换机?

c++在公司里一般是做什么的啊

Posted: 31 Aug 2021 04:49 AM PDT

那些 windows 桌面应用是用什么语言、框架开发的?

Posted: 31 Aug 2021 04:42 AM PDT

比如常见的 QQ 、微信、360 、百度网盘、还有抖音的直播伴侣

最近想写个 2D 游戏的引擎,我有很多问号。请问下如何入门基础 OpenGL, 以及不久的未来是不是 vulkan 会取代 OpenGL,想找个起点,我想明天开始补些知识

Posted: 31 Aug 2021 04:10 AM PDT

你们都是我大哥

请教在联通智慧安全、联通数科的同学

Posted: 31 Aug 2021 04:05 AM PDT

rt-请问有在联通智慧安全的童靴吗?

我好友 web 岗社招过了收到了 offer,工作地点在北京阜成门,听说现在都统规到新成立的联通数科旗下了,请问有经验的在联通里面搞技术的,里面工作如何?

跟他聊天,说起来他们薪资发放的方式好 TM 奇怪,HR 谈薪时会说明一些补助和奖金,如果真能发放的话,算年资还是可以的,但是合同上只是一个简单的 月资 X12,这个数目跟年资包相差不少,所以来求教诸位有在 联通或者其他国企有类似经历的老哥们,一般薪资会发放足额吗? 此外,联通智慧安全,web 岗工作强度咋样?加班严重吗?加班有没有加班费啊

服务端渲染(SSR)怎么区分 JS 代码块是在浏览器执行,还是在 Server 端执行?

Posted: 31 Aug 2021 04:03 AM PDT

刚开始看前端框架,对服务端渲染(SSR)很感兴趣。 想问一下哪位仁兄能否解答一下这个问题,在启动 SSR 后

npm run dev:ssr 

Angular 是怎么区分哪一部分的 JS 在浏览器端执行,哪一部分在 Server 端执行的?

很可能是我作为后端程序员对 SSR 的认识存在偏颇。多多指教!

如果不考虑现实,你最想去哪?想怎么生活。

Posted: 31 Aug 2021 04:00 AM PDT

如题:如果不考虑现实,你最想去哪?想怎么生活。

Magisk 开发者吴泓霖(John Wu)在 medium 上发文了,称会继续维护 Magisk

Posted: 31 Aug 2021 03:49 AM PDT

有没有开源的云手机方案

Posted: 31 Aug 2021 03:32 AM PDT

在 X 宝上看到一个设备, 叫 Station P1
是瑞星微 RK3399 的处理器,ARM64 架构的,然后它可以创建 10 台虚拟安卓设备,算是一个私有化云手机了.
暂且不论性能,请问它是什么原理?
有没有开源的方案?

SQLModel

Posted: 31 Aug 2021 02:50 AM PDT

国内有 ghcr.io 的镜像加速吗?

Posted: 31 Aug 2021 02:44 AM PDT

类似 https://hub-mirror.c.163.com 这种的免费服务有吗?

大家容灾是怎么做的?

Posted: 31 Aug 2021 02:22 AM PDT

工作不到半年,公司给的服务器出现了一次硬盘挂掉、一次系统宕机,想问问各位的容灾是怎么做的。

请问怎么修改图片 exif 信息里面 主题 分级 标记 标注 这些属性呢

Posted: 31 Aug 2021 01:58 AM PDT

7-M-V-W-HIH-MN-O-QXE5.png

我用了 piexif 这个库去修改,貌似没有能修改这些属性的方法,这几个属性好像也不属于 exif 信息

android 的第三方应用商店安装到 system 分区就可以自动安装与更新应用了吗?

Posted: 31 Aug 2021 01:24 AM PDT

PE 系统无国内应用市场,某些 app 没有在 play 上架.

目前装的是 oppo 应用商店,但是安装与更新 app 都需要手动点一下安装,太麻烦了,所以想尝试自动安装与更新.

如何写一个好的技术方案

Posted: 31 Aug 2021 01:09 AM PDT

以设计一个 V2EX 的某个新功能,例如节点订阅需求的技术方案为例子。那么这个技术方案应该分位几部分呢?

  1. 需求描述
    1.1 背景
    1.2 业务场景

  2. 设计原则 /方案取舍

  3. 总体设计
    3.1 核心流程(数据流)/模块关系
    3.2 核心实现
    3.2.1 数据结构定义
    3.2.2 接口协议定义

  4. 排期

个人理解这些是必备的描述,除此之外还需要更多和业务相关的设计

IntelliJ IDEA 格式化代码问题

Posted: 31 Aug 2021 12:32 AM PDT

代码仓库中有一个名为db.changelog-master.xml的文件,里面包含如下内容:

<changeSet id="2021-08-25-001" author="Jason Law-current_feature">     <sql>         alter table shop_dish_revenue             add dish_specification varchar(50) not null comment '菜品规格' after dish_code;     </sql> </changeSet> 

但在我同事的电脑上格式化代码的话,会变成下面这样,为什么呢?怎么可以格式化成上面那样?

<changeSet id="2021-08-25-001" author="Jason Law-current_feature">     <sql>         alter table shop_dish_revenue         add dish_specification varchar(50) not null comment '菜品规格' after dish_code;     </sql> </changeSet> 

为什么阿里云的路由的第一跳不是网关?

Posted: 31 Aug 2021 12:08 AM PDT

阿里云的服务器,CentOS 7,用 routel 查看得到的路由表里面 default 的 gateway 是一个 172 开头的内网 ip,也就是我的网关,但是用 traceroute 测试到任何一个公网的 ip 的路由,开头的几跳里面都没有我的网关,而是 10 开头的内网 ip,我的路由表中也没有任何 10 开头的 ip 。

例如: 我的路由表的 default:

         target            gateway          source    proto    scope    dev tbl         default      172.17.x.x                                     eth0   

traceroute 的前几跳

traceroute to bing.com (13.107.21.200), 30 hops max, 60 byte packets  1  10.12.4.46 (10.12.4.46)  1.334 ms 10.4.40.10 (10.4.40.10)  1.323 ms 10.12.16.42 (10.12.16.42)  1.172 ms  2  10.4.44.65 (10.4.44.65)  4.187 ms 10.12.4.73 (10.12.4.73)  4.159 ms *  3  10.54.130.5 (10.54.130.5)  4.114 ms 11.217.0.18 (11.217.0.18)  2.181 ms 11.217.0.50 (11.217.0.50)  2.161 ms 

所以这里路由表为什么不起作用了呢?

intellij idea 光标所在的单词会全部高亮,如何取消

Posted: 31 Aug 2021 12:03 AM PDT

前几天改了一通 idea 的设置,今天发现光标所在某个单词,整个文件中相同的会被高亮,有朋友知道这个哪个设置项控制的嘛

关于前端工程化与 K8S 结合的一些疑问

Posted: 30 Aug 2021 11:13 PM PDT

目前所有静态资源除了 html 已上传到 OSS,并做了 CDN,有个疑问:如何去访问 HTML 文件

  1. 反向代理通过 NFS 访问
  2. 前端容器启动一个 node server, 反向代理通过 http 访问

两个本质上还是远程访问的形式,或者有没有其他更好的方式

kube-prometheus-0.7 部署出错问题求助

Posted: 30 Aug 2021 10:39 PM PDT

hUdgY9.png 系统环境是 CentOS7.9 + K8s v1.19.14 ,根据官方兼容性说明下载安装的是 kube-prometheus-release-0.7 版本,老是报错,安装包是 https://github.com/prometheus-operator/kube-prometheus/archive/refs/heads/release-0.7.zip

cd /root/kube-prometheus-release-0.7/manifests kubectl create -f setup 
[root@k8s-master manifests]# kubectl get pod -o wide -n monitoring NAME                                   READY   STATUS             RESTARTS   AGE   IP            NODE        NOMINATED NODE   READINESS GATES prometheus-operator-7649c7454f-q9m29   1/2     CrashLoopBackOff   6          10m   10.201.1.58   k8s-node1   <none>           <none> 

查看日志:

[root@k8s-master manifests]# kubectl logs prometheus-operator-7649c7454f-q9m29 --all-containers -n monitoring level=info ts=2021-08-31T03:16:07.410585761Z caller=main.go:235 msg="Starting Prometheus Operator" version="(version=0.44.1, branch=refs/tags/pkg/apis/monitoring/v0.44.1, revision=d8b7d3766225908d0239fd0d78258892cd0fc384)" level=info ts=2021-08-31T03:16:07.410684044Z caller=main.go:236 build_context="(go=go1.14.12, user=simonpasquier, date=20201209-17:17:30)" ts=2021-08-31T03:16:07.415831751Z caller=main.go:107 msg="Starting insecure server on [::]:8080" ts=2021-08-31T03:16:10.422020132Z caller=main.go:422 msg="Unhandled error received. Exiting..." err="communicating with server failed: Get \"https://10.96.0.1:443/version?timeout=32s\": dial tcp 10.96.0.1:443: connect: connection timed out" I0831 03:10:09.496650       1 main.go:190] Valid token audiences: I0831 03:10:09.496764       1 main.go:262] Generating self signed cert as no cert is provided I0831 03:10:10.447004       1 main.go:311] Starting TCP socket on :8443 I0831 03:10:10.447347       1 main.go:318] Listening securely on :8443 

根据报错测试几个节点上 10.96.0.1:443 这个地址都可以访问

[root@k8s-master manifests]# curl -k https://10.96.0.1:443/version?timeout=32s {   "major": "1",   "minor": "19",   "gitVersion": "v1.19.14",   "gitCommit": "0fd2b5afdfe3134d6e1531365fdb37dd11f54d1c",   "gitTreeState": "clean",   "buildDate": "2021-08-11T18:02:17Z",   "goVersion": "go1.15.15",   "compiler": "gc",   "platform": "linux/amd64"  

iptables 信息:

[root@k8s-master manifests]# iptables -L -n Chain INPUT (policy ACCEPT) target     prot opt source               destination KUBE-SERVICES  all  --  0.0.0.0/0            0.0.0.0/0            ctstate NEW /* kubernetes service portals */ KUBE-EXTERNAL-SERVICES  all  --  0.0.0.0/0            0.0.0.0/0            ctstate NEW /* kubernetes externally-visible service portals */ KUBE-FIREWALL  all  --  0.0.0.0/0            0.0.0.0/0  Chain FORWARD (policy ACCEPT) target     prot opt source               destination KUBE-FORWARD  all  --  0.0.0.0/0            0.0.0.0/0            /* kubernetes forwarding rules */ KUBE-SERVICES  all  --  0.0.0.0/0            0.0.0.0/0            ctstate NEW /* kubernetes service portals */ DOCKER-USER  all  --  0.0.0.0/0            0.0.0.0/0 DOCKER-ISOLATION-STAGE-1  all  --  0.0.0.0/0            0.0.0.0/0 ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED DOCKER     all  --  0.0.0.0/0            0.0.0.0/0 ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0 ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0 ACCEPT     all  --  10.244.0.0/16        0.0.0.0/0 ACCEPT     all  --  0.0.0.0/0            10.244.0.0/16  Chain OUTPUT (policy ACCEPT) target     prot opt source               destination KUBE-SERVICES  all  --  0.0.0.0/0            0.0.0.0/0            ctstate NEW /* kubernetes service portals */ KUBE-FIREWALL  all  --  0.0.0.0/0            0.0.0.0/0  Chain DOCKER (1 references) target     prot opt source               destination  Chain DOCKER-ISOLATION-STAGE-1 (1 references) target     prot opt source               destination DOCKER-ISOLATION-STAGE-2  all  --  0.0.0.0/0            0.0.0.0/0 RETURN     all  --  0.0.0.0/0            0.0.0.0/0  Chain DOCKER-ISOLATION-STAGE-2 (1 references) target     prot opt source               destination DROP       all  --  0.0.0.0/0            0.0.0.0/0 RETURN     all  --  0.0.0.0/0            0.0.0.0/0  Chain DOCKER-USER (1 references) target     prot opt source               destination RETURN     all  --  0.0.0.0/0            0.0.0.0/0  Chain KUBE-EXTERNAL-SERVICES (1 references) target     prot opt source               destination  Chain KUBE-FIREWALL (2 references) target     prot opt source               destination DROP       all  --  0.0.0.0/0            0.0.0.0/0            /* kubernetes firewall for dropping marked packets */ mark match 0x8000/0x8000 DROP       all  -- !127.0.0.0/8          127.0.0.0/8          /* block incoming localnet connections */ ! ctstate RELATED,ESTABLISHED,DNAT  Chain KUBE-FORWARD (1 references) target     prot opt source               destination DROP       all  --  0.0.0.0/0            0.0.0.0/0            ctstate INVALID ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            /* kubernetes forwarding rules */ mark match 0x4000/0x4000 ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            /* kubernetes forwarding conntrack pod source rule */ ctstate RELATED,ESTABLISHED ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            /* kubernetes forwarding conntrack pod destination rule */ ctstate RELATED,ESTABLISHED  Chain KUBE-KUBELET-CANARY (0 references) target     prot opt source               destination  Chain KUBE-PROXY-CANARY (0 references) target     prot opt source               destination  Chain KUBE-SERVICES (3 references) target     prot opt source               destination 

环境信息如下:

[root@k8s-master ~]# kubectl version Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.14", GitCommit:"0fd2b5afdfe3134d6e1531365fdb37dd11f54d1c", GitTreeState:"clean", BuildDate:"2021-08-11T18:07:41Z", GoVersion:"go1.15.15", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.14", GitCommit:"0fd2b5afdfe3134d6e1531365fdb37dd11f54d1c", GitTreeState:"clean", BuildDate:"2021-08-11T18:02:17Z", GoVersion:"go1.15.15", Compiler:"gc", Platform:"linux/amd64"}  [root@k8s-master ~]# cat /etc/redhat-release CentOS Linux release 7.9.2009 (Core)  [root@k8s-master ]# kubectl get node NAME         STATUS   ROLES    AGE   VERSION k8s-master   Ready    master   10d   v1.19.14 k8s-node1    Ready    <none>   10d   v1.19.14 k8s-node2    Ready    <none>   10d   v1.19.14 k8s-node3    Ready    <none>   10d   v1.19.14 

C++ 有什么好的源码分析工具吗?

Posted: 30 Aug 2021 10:31 PM PDT

看到别的语言有类似的工具,
可以自动生成 class 视图和各个 class 之间的关系,
我印象中 C++ 也有,但是找不到了,大家有推荐的吗?

请教一下有没有搜索视频的站点?

Posted: 30 Aug 2021 10:29 PM PDT

比如能够搜索视频的标题、语音、视频里的物件等等来搜索的?现在好像很缺乏视频内容搜索的引擎啊?

关于 运营商间断性劫持 dns ,一次 dns query ,回了 2 个包。

Posted: 30 Aug 2021 06:59 PM PDT

RT,见之前讨论的帖子。v2ex.com/t/798895

起因是,通过科大的 ipv6 站点 测速,老提示 dns not found.

经过排查,用 tcpdump 抓包,发现 一次 query,回了 2 个包。

dig test6.ustc.edu.cn  @221.6.4.66 aaaa 
05:54:24.313173 IP 221.6.4.66.53 > 153.x.x.x.34541: 23659$ 0/0/1 (58) 05:54:24.313953 IP 221.6.4.66.53 > 153.x.x.x.34541: 23659 1/0/0 AAAA 2001:da8:d800::40 (63) 

这种劫持污染,不是一直在,而是间隔几秒就出现。

搞了一个对照组,

 dig www.google.com @8.8.8.8 
05:37:11.599976 IP 153.x.x.x.45779 > 8.8.8.8.53: 23226+ [1au] A? www.google.com. (55) 05:37:11.632142 IP 8.8.8.8.53 > 153.x.x.x.45779: 23226 1/0/0 A 31.13.90.19 (48) 05:37:11.632348 IP 8.8.8.8.53 > 153.x.x.x.45779: 23226 1/0/0 A 173.252.100.21 (48) 05:37:11.650795 IP 8.8.8.8.53 > 153.x.x.x.45779: 23226 1/0/1 A 142.251.42.228 (59) 

回了三个包,第一个包估计是运营商返回的,第二个包估计是 qiang 返回的,第三个包才是 8 返回的。真是层层拦截,层层污染。

请问,联通是如何做到间断性污染的?

请问有没有自动定义生成列表的方法

Posted: 30 Aug 2021 04:56 PM PDT

最近刚接触 python,想请问下:

在处理一堆 list 类型数据的时候,有没有办法在不提前定义出空 list 的时候,根据需求凭空创建出一堆名字自动生成出来的 list 呢?

比方说我搜到的所谓的列表生成往往是这样的
# 举例:a = [1,2,3] b = [ 'A' , 'B' , 'C' ] 生成 ls = [ 'A1' , 'B2' , 'C3 ']
a = [1, 2, 3]
b = ['A', 'B', 'C']
ls = []
# 获取 0,1,2,用作原始列表的下标,索引原始列表的元素,以便于操作
for i in range(0, 3):
# int 和 str 不能直接拼接,先将 int 转为 str
x = b[i] + str(a[i])
ls.append(x)
print(ls)

在提前定义出 ls = []后,利用 for 之类的功能往里面塞东西.
而当我有很多列表时,想凭借任意两个列表的组合创造出一个新列表的时候有没有方法不去手动创建,而是写一个方法像是:
def create_new_list(list1,list2)

新列表的名字命名规则像是: "newlist_from_"+list1+list2
这里的 list1 与 list2 就是 def create_new_list(list1,list2)里面两个 list 的名字
然后这个新列表内包含像是 newlist_from_list1+list2 = [(list1[0]+list2[0]),(list1[1]+list2[1])...]

第一次问这种抽象编程问题不太好表达 不知道能不能让人理解

就职业生涯而言,梅西和 C 罗的巅峰期保持的挺长的

Posted: 30 Aug 2021 04:04 AM PDT

这绝的值得吹牛皮的
需要天赋 自律 自驱 以及各种优越的外在条件,迁移到程序员也是同理