Wednesday, November 24, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Jackson @JsonRawValue without a key

Posted: 24 Nov 2021 05:34 AM PST

I want to use Jackson's @JsonRawValue but get rid of the key that's part of the response. I sort of like to use @JsonRawValue in combination with @JsonUnwrapped but that doesn't do what I want to achieve.


Lets break it down:

I have a database table with two fields id and json.

  • The id is just the database id
  • The json is a String as json, for example:

{ "tenantId": 1, "name": "someName", "location": "http://someurl.com"}

So my entity looks like:

@Data  @Entity  public class SomeEntity {        @Id      @Column(nullable = false)      @GeneratedValue(strategy = GenerationType.IDENTITY)      private Long id;        @Column(columnDefinition = "text", length = Integer.MAX_VALUE)      private String json;        }  

I've created a Dto to map this entity to and return it as a JSON object via my Controller. The Dto looks like this:

@Data  public class SomeDto {        private Long id;        @JsonRawValue      private String json;        }  

The response I would like is:

 {      "id" : 1,      "tenantId": 1,      "name": "someName",      "location": "http://someurl.com"   }  

The response I got contains the 'json' key (because that's the name of the variable in my Dto), like:

{      "id": 1,      "json": {          "tenantId": 1,          "name": "someName",          "location": "http://someurl.com"      }  }  

Is there anyway I can get rid of the 'extra' key in my response ? I've tried to use @JsonRawValue in combination with @JsonUnwrapped but that doesn't seem to work.

Thankyou!

How to limit the data fired on the first load using Table Pagination MUI

Posted: 24 Nov 2021 05:34 AM PST

I have question how can I limit the data on the first fire of the page? Right now I experience when I set the count property of table to = 1 the data table still on same limit. I used MUI for the data table.

Version: "@mui/icons-material": "^5.0.0",

Goal: limit the data on the first load of the page to = 10

Here is the table structure:

    <TableContainer sx={{ maxHeight: 440, mt:4 }}>        <Table>          <TableHead sx={{backgroundColor:'#F9F9F9'}}>              <TableRow>              {columns.map((column) => (                  <TableCell                      key={column.id}                      align={column.align}                      style={{ top: 57, minWidth: column.minWidth, fontWeight:'bold' }}                  >                  {column.label}                  </TableCell>              ))}              </TableRow>          </TableHead>          <TableBody>              {userList?.map((row) => (                  <TableRow key={row.id}>                      <TableCell>                          {row.name}                      </TableCell>                      <TableCell>                          {row.email}                      </TableCell>                      <TableCell>                          {row.role != '' && null ? row.role : '-'}                      </TableCell>                      <TableCell>                          {row.status}                      </TableCell>                      <TableCell >                          <Visibility onClick={handleOpenEditUser} style={{color:'#3167E9'}}/>                          <Delete style={{color:'#F53C56'}}/>                      </TableCell>                  </TableRow>              ))}          </TableBody>      </Table>  </TableContainer>    <TablePagination      rowsPerPageOptions={[5, 10, 25]}      component="div"      count={1}      rowsPerPage={1}      page={1}      onChangePage={handleChangePage}      onChangeRowsPerPage={handleChangeRowsPerPage}  />  

Sample Output

browse .net application in .net6 with docker cause a problem

Posted: 24 Nov 2021 05:33 AM PST

I have this application as you can see that I run in IIS Express :

enter image description here

So I want to run it on docker so the docker file is generated :

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.    FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base  WORKDIR /app  EXPOSE 80    FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build  WORKDIR /src  COPY ["Docker/Docker.csproj", "Docker/"]  RUN dotnet restore "Docker/Docker.csproj"  COPY . .  WORKDIR "/src/Docker"  RUN dotnet build "Docker.csproj" -c Release -o /app/build    FROM build AS publish  RUN dotnet publish "Docker.csproj" -c Release -o /app/publish    FROM base AS final  WORKDIR /app  COPY --from=publish /app/publish .  ENTRYPOINT ["dotnet", "Docker.dll"]  

So I create the image as you can see with this command :

docker build -t containername/tag -f docker/Dockerfile .  

The image is created so I want to run my container using this :

docker run -d -p 42419:42419 --name apitest containername/tag:latest  

The container is created but when I call this url http://localhost:42419/swagger/index.html I can't see the swagger page .Why?

how to align angular mat prefix to a label in a form field

Posted: 24 Nov 2021 05:33 AM PST

As you can see on the screenshot guys , I have a prefix for an input but the problem is it is not aligned with the mat label ..is there a way we can modify the mat prefix that it will be align with the mat label ? Thanks for any help and ideas , appreciated.

it should be something like this

enter image description here

#html code

 <mat-form-field appearance="fill">              <mat-label>Termination Payment ($)</mat-label>              <input                 name="terminationPayment"                 matInput                (keyup) = "computeBuyout()"                mask="separator.0"                 thousandSeparator=","                [allowNegativeNumbers]="false"                [(ngModel)]="dealDispositionFormFields.terminationPayment"                >                <span matPrefix *ngIf="dealDispositionFormFields.terminationPayment">$</span>            </mat-form-field>  

current issue - screenshot

PDO INSERT INTO is not working for me....driving me nuts

Posted: 24 Nov 2021 05:33 AM PST

Having an issue with INSERT INTO on my website. I'm trying to implement CRUD. I have Read, Update and Delete working but Create is giving me a problem. For some reason when I create a user, I can find it on the table on my website but when I try to find it via phpmyadmins table filter, it does not appear. But if I request the value via a SQL query, it will appear. If you need a better understanding of what I'm talking about, I have provided a YouTube video which demonstrates my problem (Hopefully that's allowed on this website)

I will also attach my code as mentioned in the YouTube Video

Youtube Video

PHP/SQL:

$sql = 'INSERT INTO user (user.userID,user.firstName,user.lastName,user.DOB,user.streetAddress,user.city,user.state,user.postalCode,user.phoneNumber,user.userType) VALUES(:id, :studentfirstname, :studentlastname, :studentDOB, :studentstreet, :studentcity, :studentstate, :studentzip, :studentphone, :usertype)';      $statement= $connect->prepare($sql);      if ($statement->execute([':id'=>$id,':studentfirstname'=>$studentfirstname,':studentlastname'=> $studentlastname,':studentDOB'=>$studentDOB,':studentstreet'=>$studentstreet,':studentcity'=>$studentcity,':studentstate'=>$studentstate,':studentzip'=>$studentzip,':studentphone'=>$studentphone,':usertype'=>$usertype]))      {        $sql ='INSERT INTO login (login.userID,login.username,login.password,login.userType) VALUES(:id,:studentemail,:studentpassword,:usertype)';        $statement= $connect->prepare($sql);        if ($statement->execute([':id'=>$id,':studentemail'=>$studentemail,':studentpassword'=>$studentpassword,':usertype'=>$usertype]))        {          $_SESSION["created"]=TRUE;          header("Location: ../users.php");        }      }  

Hyperledger Fabric: Using Fabcar and SDK for connecting ubuntu server with local maschine

Posted: 24 Nov 2021 05:32 AM PST

I was setting up my hyperledger fabric network on my ubuntu server. I took the fabcar example with default settings, so just executing ./startFabric.sh javascript.

In the next step I was running enrollAdmin.js, registerUser.js & query.js on the server.

Now I want to connect my fabric network with my local maschine:

First I move all JS files to local directory! Next I move package.json to dir & excecuting npm install for dependencies.

Afterwards I copy connection.json, connection.yaml & fabric-ca-client-config.yaml from /.../fabric-samples/test-network/organizations/peerOrganizations/org1.example.com

By adapting the json file with IP from Server, I can run local enrollAdmin.js & registerUser.js!

But query.js is not working: enter image description here

This is the connection.json: enter image description here

Why is it still not working?

How can I get the full connection to my hyperledger network from local maschine?

Name 'Account' is not defined when it is the name of the class

Posted: 24 Nov 2021 05:34 AM PST

class Account:      def __init__(self, id = 0, balance = 100, annual_interest_rate = 0):          self.id = int(id)          self.balance = float(balance)          self.annual_interest_rate = float(annual_interest_rate)        def get_id(self):              return self.id      def set_id(self, id):              self.id = id        def get_balance(self):          return self.balance      def set_balance(self, balance):          self.balance = balance        def get_annual_interest_rate(self):          return self.annual_interest_rate      def set_annual_interest_rate(self, annual_interest_rate):          self.annual_interest_rate = annual_interest_rate            def get_monthly_interest_rate(self):          return self.annual_interest_rate/12      def get_monthly_interest(self):          return self.balance*self.get_monthly_interest_rate()        def withdraw(self, withdraw):          self.balance -= withdraw        def deposit(self, deposit):          self.balance += deposit        def main():          account1 = Account(id =1122, balance= 20000, annual_interest_rate= 4.5)          account1.withdraw(2500)           account1.deposit(3000)          print(account1.get_id() )          print(account1.get_balance() )          print(account1.get_monthly_interest_rate() )          print(account1.get_monthly_interest() )            main()  

I do not understand/can't find out why the code won't work.

I get an error saying name 'Account' is not defined, when it is the name of the class.

My funds are stuck in a reserved state. How do I get them out?

Posted: 24 Nov 2021 05:32 AM PST

I have a large amount of reserved funds that I can't use, how do I get them out?

Status for account: [redacted]    ┌────────────────────┬───────────────────────────────┬───────────────────────────────┬─────────────┬────────────┬────────────────────────────────┐  │  platform          │  total amount                 │  reserved                     │  amount     │  incoming  │  outgoing                      │  ├────────────────────┼───────────────────────────────┼───────────────────────────────┼─────────────┼────────────┼────────────────────────────────┤  │  driver: zksync    │  111.271646252988321632 GLM   │  106.310490959782071751 GLM   │  accepted   │  0 GLM     │  305.416973117029318531 GLM  │  │  network: mainnet  │                               │                               │  confirmed  │  0 GLM     │  14.533081348947285750 GLM  │  │  token: GLM        │                               │                               │  requested  │  0 GLM     │  853.498111482561896347 GLM │  └────────────────────┴───────────────────────────────┴───────────────────────────────┴─────────────┴────────────┴────────────────────────────────┘  

React.JS : make fetch to populate selelect

Posted: 24 Nov 2021 05:32 AM PST

I'm trying to make a fetch to populate my select, but I can't use the fetch..

const loadOptions = async (searchQuery, loadedOptions, { page }) => {      const requestMethod = {                  method: "PUT",                  headers: { 'Content-Type': 'application/json' },                  body: { realmIds: [props.realmScelto] }              };                    const response = await fetch('myapi', requestMethod) // error is here, in requestMethod                // const response = await axios.post(`myapi?page=${page}&size=20`, { realmIds: [props.realmScelto] }) // this works.. it gives me back 1 value, and it ok but add always the same value that I obtain from api                // const optionToShow = await response.data              const optionToShow = await response.json()   return {              options: optionToShow,              hasMore: optionToShow.length >= 1,              additional: {                  page: searchQuery ? 2 : page + 1,              },          };      };        const onChange = option => {          if (typeof props.onChange === 'function') {              props.onChange(option);          }      };        return (          <AsyncPaginate              value={props.value}              loadOptions={loadOptions}                onChange={onChange}              isSearchable={true}              placeholder="Select"              additional={{                  page: 0,              }}          />      );  

The error that I receive in the requestMethod is:

The argument of type '{method: string; headers: {'Content-Type': string; }; body: {realmIds: any []; }; } 'is not assignable to the parameter of type' RequestInit '. The types of the 'body' property are incompatible. The type '{realmIds: any []; } 'is not assignable to type' BodyInit '. In type '{realmIds: any []; } 'The following properties of type' URLSearchParams' are missing: append, delete, get, getAll and 4 more.

How to to update data by clicking actionButton in R in runtime

Posted: 24 Nov 2021 05:32 AM PST

I want to update output data on update button every time. Here is my code which show the output on update button for the first time I run the code but in runtime if the input is changed, the output is updated automatically.

library(shiny)    ui <- fluidPage(    titlePanel("My Shop App"),        sidebarLayout(      sidebarPanel(        helpText("Controls for my app"),                selectInput("item",                     label = "Choose an item",                    choices = list("Keyboard",                                    "Mouse",                                   "USB",                sliderInput("price",                     label = "Set Price:",                    min=0, max = 100, value=10),                actionButton ("update","Update Price")      ),            mainPanel(        helpText("Selected Item:"),        verbatimTextOutput("item"),        helpText("Price"),        verbatimTextOutput("price")      )    )  )    server <- function(input, output) {        SelectInput <- eventReactive (input$update , {        output$item = renderText(input$item)      output$price = renderText(input$price)      })      output$item <- renderText(SelectInput())    output$price <- renderText(SelectInput())  }    shinyApp(ui = ui, server = server)    

RESTFUL API for Peepso plugin in wordpress

Posted: 24 Nov 2021 05:34 AM PST

I am using Peepso plugin and I need to connect my website's database to the android app I created. To do that I need a RESTFUL API for Peepso but unfortunately the plugin doesn't support any APIs, so I decided to create it by myself. The problem I am facing is that I can't figure out how I can open the .php file I created to test it on browser. So, can someone explain to me how can I test my code so as to know if the API I created is working?

How to check a string contain a certain value in C

Posted: 24 Nov 2021 05:34 AM PST

while (str[i])      {          if(str[i] == '0' && values[i] == '1')          {              i++;              continue;          }          else          {              printf("Wrong number input")              break;          }  

I want to check whether the user has type in the correct input.

The str input is 00111111010100000000000000000000. However, the code does not go in the if condition but the else condition instead. What is wrong with the code?

Get Youtube video title with classname and .text

Posted: 24 Nov 2021 05:33 AM PST

Hi im using Python Selenium Webdriver to get Youtube title but keep getting more info than i'd like. The line is: driver.find_element_by_class_name("style-scope ytd-video-primary-info-renderer").text

Is there any way to fix it and make it more efficient so that it displays only the title. Here is the test script im using:

from selenium import webdriver as wd  from time import sleep as zz    driver = wd.Firefox(executable_path=r'./geckodriver.exe')  driver.get('https://www.youtube.com/watch?v=wma0szfIafk')  zz(4)  test_atr = driver.find_element_by_class_name("style-scope ytd-video-primary-info-renderer").text  print(test_atr)  

Fit image to div without a set height

Posted: 24 Nov 2021 05:34 AM PST

I have this JSX

<div style={{ display: 'flex' }}>    <div className='outer-div'>      <div className='first-div'>        a <br />        b <br />c      </div>      <div className='second-div'>        <img          src='https://upload.wikimedia.org/wikipedia/commons/0/0f/Eiffel_Tower_Vertical.JPG'          alt=''        />      </div>    </div>    <div className='outer-div'>      <div className='first-div'>        a <br />        b <br />c      </div>      <div className='second-div'></div>    </div>  </div>  

and this CSS

.outer-div {    width: 300px;    height: 500px;    background-color: blue;    display: flex;    flex-direction: column;  }    .first-div {    background-color: red;  }    .second-div {    height: 100%;    background-color: green;  }    .second-div > img {    height: 100%;    width: 100%;  }  

I wanted the image to fit the div completely, but instead it is like this:

enter image description here

I noticed that if the screen is thinner, the problem doesn't happen, like here:

enter image description here

How can I make it so the image completely fills the second-div for any screen size, without having a set height?

How do I pass the main window's handle to a new thread using win32 API only?

Posted: 24 Nov 2021 05:33 AM PST

I have read that I need to have the HWND placed on the heap. Is that correct?

I need this to read values from user input.

Thank you in advance!

VOID MakeThread(HWND hWnd)  {        HWND* h = new HWND(hWnd);      stringstream stream;      stream << h << char(13) << char(10) << hWnd;      std::string s = stream.str();      MessageBoxA(hWnd, s.c_str(), "hWnd?", 0);      stream.str("");      stream.clear();      s.clear();      s.shrink_to_fit();        HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 0, WorkerThread, h, 0, nullptr);        if (hThread != nullptr) {          WaitForSingleObject(hThread, INFINITE);          CloseHandle(hThread);      }      delete h;  }    unsigned int __stdcall WorkerThread(VOID* h)  {        stringstream stream;      stream << (HWND)h << char(13) << char(10) << (*(HWND*)h);      std::string s = stream.str();      MessageBoxA(nullptr, s.c_str(), "hWnd?", 0);      stream.str("");      stream.clear();      s.clear();      s.shrink_to_fit();      return 0;  }  

What is the best way to extract a method name and parameter name from a given mathematical expression string in java?

Posted: 24 Nov 2021 05:33 AM PST

What is the best way to extract a method name and parameter name from a given mathematical expression string in java? Where method name and parameter can be any string value.

Eg. 10+ sumRun('playerName')*70;

Expected result

Method name : sumRun

Parametervalue: playerName?

How can I write a loop to make the timer run every two seconds

Posted: 24 Nov 2021 05:33 AM PST

I have a question on how I am able to set the timer so that every time it exits the loop it sets the time back to 2 seconds. The problem is that the first time the sound works after 2 seconds, the next times it is executed immediately. Thank you very much in advance for any advice.

This is my code:

              time = 2              while time > 0:                  timer = datetime.timedelta(seconds=time)                  time -= 1                  duration = 1000                  freq = 440              winsound.Beep(freq, duration)    

I need to check if CHAR from Array1 contains some CHAR from my Array2 but I cant use Contains for CHAR... How to solve it?

Posted: 24 Nov 2021 05:34 AM PST

I need to convert one phone number (badly written) to correct format. Example: + 420 741-854()642. to +420741854642 enter image description here

Doctrine Fetch mode

Posted: 24 Nov 2021 05:34 AM PST

I have a N+1 query issue with my symfony project.

You will say me, please with profiler and doctrine doc, it's should be easy to fix. And I'm agree with you, I should add fetch="EAGER" on my field emails and it's should fix it. But no... I tested all modes and I can't figure it out ...

This is the query called N time :

SELECT     t0.id AS id_1,     t0.email AS email_2,     t0.data_id AS data_id_3  FROM     obs_affiliate_email t0  WHERE     t0.data_id = ?  

this is my entity where obs_affiliate_email variable is :

class ObsData implement InterfaceDataLight {      /**       * @ORM\OneToMany(targetEntity="App\Entity\Obs\ObsAffiliateEmail", mappedBy="data", orphanRemoval=true)       * @Groups({"public"})      */      protected Collection $emails;      ...  }  

This is my ObsAffiliateEmail class

class ObsAffiliateEmail extand AbsAffiliateEmail {     /**      * @ORM\ManyToOne(targetEntity="App\Entity\Obs\ObsData", inversedBy="emails")      * @ORM\JoinColumn(nullable=false)     */   protected ?InterfaceDataLight $data = null;   ...  }  

Is it due to the interface? or I missed something?

Of course for this example I removed all useless/wrong fetch mode.

Groovy (jenkinsfile) - Parsing Json maintaining same order

Posted: 24 Nov 2021 05:34 AM PST

First, thank you for reading and helping. I have this issue and can't find a way to solve it. So, I'm setting up a test pipeline using jenkinsfile with parameters to start the build. I have a json file with the list of the docker tags available from a project order by time (newest first) that I want to test. The json file is something like this:

[      "tag1",      "tag2",      (...)  ]  

The objective is to have a list in groovy with the tags in the same order as they are in the file to be able to set them as parameters option for jenkins.

I've tried to use groovy.json.JsonSlurperClassic and groovy.json.JsonSlurper, but after the parsing the order of the tags is completely different. Any suggestions how to do it? Thank you.

Django Separate Settings raises error TemplateDoesNotExist at /

Posted: 24 Nov 2021 05:34 AM PST

I have been attempting to separate my settings via settings folder with base, dev prod and init files and ran the server with the dev settings it says it runs with no issues but when I click on the link I now get an error TemplateDoesNotExist at /, I was able to access the page before seperating my settings

I decided to try the above on a fresh django project which appears to have worked on out of the box django main page and admin panel however again when I go to add a new url and view and template the same error is raised TemplateDoesNotExist at /.

Please see the following code exlcuding settings/base.py as this is just fresh project settings but cut SECRET_KEY and placed in settings/dev.py which worked prior to adding url/view and template:

urls

from django.contrib import admin  from django.urls import path, include, reverse_lazy  from django.contrib.auth import views as auth_views  from . import views      urlpatterns = [      path('admin/', admin.site.urls),      path('', views.home, name="home"),  ]    

views

from django.shortcuts import render, redirect    def home(request):      return render(request, 'test.html')  

template - projectroot/templates/test.html

<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>Test</title>  </head>    <h1>Test</h1>  <body>    </body>  </html>  

Help is much apprecaited in getting this back runing again. Thanks

How to aggregate a nested array using MongoDB?

Posted: 24 Nov 2021 05:33 AM PST

I tried to use aggregate to find out each product's monthly sales in my order , but I ran into a problem.

Here's my data structures.

Order.model.ts

const OrderSchema: Schema = new Schema(    {      userId: {        type: String,        require: true,      },      products: [        {          product: {            _id: {              type: String,            },            title: {              type: String,            },            desc: {              type: String,            },            img: {              type: String,            },            categories: {              type: Array,            },            price: {              type: Number,            },            createdAt: {              type: String,            },            updatedAt: {              type: String,            },            size: {              type: String,            },            color: {              type: String,            },          },          quantity: {            type: Number,            default: 1,          },        },      ],      quantity: {        type: Number,      },      total: {        type: Number,      },      address: {        type: String,        require: true,      },      status: {        type: String,        default: 'pending',      },    },    { timestamps: true },  );  

Order-service.ts

public async getIncome(productId?: string) {      const date = new Date();      const lastMonth = new Date(date.setMonth(date.getMonth() - 1));      const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1));      //const lastYear = new Date(date.setFullYear(date.getFullYear() - 1));      const income = await this.order.aggregate([        {          $match: {            createdAt: { $gte: lastMonth },            ...(productId && {              products: { $elemMatch: { product: { _id: productId } } },            }),          },        },        {          $project: {            month: { $month: '$createdAt' },            sales: '$total',          },        },        {          $group: {            _id: '$month',            total: { $sum: '$sales' },          },        },      ]);      return income;    }  

When I calculate whole sales without productId , it went well , I tried to use elemMatch to find productId , but it won't work , did I miss something ?

Add number of minutes to DateTime for a specific duration

Posted: 24 Nov 2021 05:34 AM PST

I have in cell A1 a starting DateTime as 01-01-2021 00:00:00.

In another cell C2 I have a duration specifed as 240 minutes and in C3 I have a specified interval in minutes it could be 1 minute intervals or perhaps 5. I would like to fill out DateTime based on the duration and intervals from A2 and down.

1 minute interval 240 duration  01-01-2021 00:00:00  01-01-2021 00:01:00  ...  01-01-2021 04:00:00  

Different interval same duration:

5 minute intervals  01-01-2021 00:00:00  01-01-2021 00:05:00  ...  01-01-2021 04:00:00  

I've solved this by using a formula =IF(Y<$A$2+TIME(0;$C$2;0)-TIME(0;$C$3;0);A2+TIME(0;$C$3;0);"") but would like to convert this to VBA.

enter image description here

enter image description here

Sub Time()        Selection.NumberFormat = "dd-mm-yyyy hh:mm"        Dim StartTime As Date      Dim newDate As Date      Dim CountOfMinutes As Double      Dim i As Double            i = Sheets("Ark1").Range("C3")            CountOfMinutes = Sheets("SVK stationer").Range("C2")            Set StartTime = Sheets("SVK stationer").Date("A2")                newDate = DateAdd("n", CountOfMinutes, StartTime)            For Each cell In StartTime          If IsEmpty(cell) = False Then              cell.Value = cell.Value + DateAdd("n", i + CountOfMinutes, StartTime)          End If            End Sub  

How to reload one livewire component from another component?

Posted: 24 Nov 2021 05:33 AM PST

I have components named Cart, AddToCart, and CartCounter which are inside the livewire>cart folder. I emit the listeners from the AddToCart component

$this->emit('cartCounterUpdate');  

And CartCounter has listeners named cartCounterUpdate

protected $listeners = [      'cartCounterUpdate' => 'render'  ];  

But CartCounter is not refreshing/reloading after emitting from AddToCart.

Dataframe to multiple dataframes or lists for unique index values

Posted: 24 Nov 2021 05:32 AM PST

I have a dataframe that has two columns and I want to create a list containing all the values in the second column for the same value in column one.

If I have a dataframe that looks like:

Type Item
Cars Toyota
Cars Honda
Cars Tesla
Fruits Apple
Fruits Orange
Countries USA
Countries Mexico

So I want to be either be able to divide this datafram into three separate df for Cars, Fruits, and Countries. Or I want to have a list for Cars, Fruits, and Countries that would like this:

Cars = ['Toyota', 'Honda', 'Tesla']  Fruits = ['Apple', 'Orange']  Countries = ['USA, 'Mexico']  

This is just an example, my dataframe is huge so I want to have a function that does this without having to manually type in each Type. I tried looking up groupby function for pandas but don't think I was able to find how I can use it to do what I need to.

Any help is appreciated.

How to store a text-to-speech audio in an audio file (IOS)

Posted: 24 Nov 2021 05:34 AM PST

I am trying to create a video in IOS with Text-to-speech (like TikTok does). The only way to do this that I thought was to merge a video and an audio with AVFoundations, but it seems impossible to insert the audio of a text-to-speech into a .caf file.

This is what I tried:

public async Task amethod(string[] _text_and_position)  {                  string[] text_and_position = (string[])_text_and_position;                  double tts_starting_position = Convert.ToDouble(text_and_position[0]);                  string text = text_and_position[1];                    var synthesizer = new AVSpeechSynthesizer();                  var su = new AVSpeechUtterance(text)                  {                      Rate = 0.5f,                      Volume = 1.6f,                      PitchMultiplier = 1.4f,                      Voice = AVSpeechSynthesisVoice.FromLanguage("en-us")                  };                  synthesizer.SpeakUtterance(su);                    Action<AVAudioBuffer> buffer = new Action<AVAudioBuffer>(asss);                  try                  {                      synthesizer.WriteUtterance(su, buffer);                  }                  catch (Exception error) { }  }          public async void asss(AVAudioBuffer _buffer)          {              try              {                  var pcmBuffer = (AVAudioPcmBuffer)_buffer;                    if (pcmBuffer.FrameLength == 0)                  {                      // done                  }                  else                  {                      AVAudioFile output = null;                      // append buffer to file                      NSError error;                        if (output == null)                      {                          string filePath = Path.Combine(Path.GetTempPath(), "TTS/" + 1 + ".caf");                          NSUrl fileUrl = NSUrl.FromFilename(filePath);                            output = new AVAudioFile(fileUrl, pcmBuffer.Format.Settings, AVAudioCommonFormat.PCMInt16 , false ,out error);                      }                      output.WriteFromBuffer(pcmBuffer, out error);                }              }              catch (Exception error)              {                  new UIAlertView("Error", error.ToString(), null, "OK", null).Show();              }          }  

This is the same code in objective-c

let synthesizer = AVSpeechSynthesizer()  let utterance = AVSpeechUtterance(string: "test 123")  utterance.voice = AVSpeechSynthesisVoice(language: "en")  var output: AVAudioFile?    synthesizer.write(utterance) { (buffer: AVAudioBuffer) in     guard let pcmBuffer = buffer as? AVAudioPCMBuffer else {        fatalError("unknown buffer type: \(buffer)")     }     if pcmBuffer.frameLength == 0 {       // done     } else {       // append buffer to file       if output == nil {          output = AVAudioFile(           forWriting: URL(fileURLWithPath: "test.caf"),            settings: pcmBuffer.format.settings,            commonFormat: .pcmFormatInt16,            interleaved: false)        }       output?.write(from: pcmBuffer)     }   }  

The problem with this code is that "synthesizer.WriteUtterance(su, buffer);" always crashes, after reading other posts I believe this is a bug that results in the callback method (buffer) never being called.

Do you know of any workaround to this bug or any other way to achieve what I am trying to do?

Thanks for your time, have a great day.

Zabbix5.0 How do I Change disk Monitoring thresholds

Posted: 24 Nov 2021 05:34 AM PST

For zabbix5.0, the default alarm is generated when the disk usage exceeds 80%, but I want to change the alarm to exceed 90%. How should I change the alarm? I did not find the modification, and I used the Template 'Template OS Linux by Zabbix Agent Active'.

Android Compose - crossfade with sizechange

Posted: 24 Nov 2021 05:34 AM PST

My Composable has the following structure:

var expandedState by remember { mutableStateOf(false) }    Box(modifier = Modifier.animateContentSize()) {              Crossfade(targetState = expandedState) { expanded ->                  if (expanded) {                      ExpanedContent()                  } else {                      CollapsedContent()                  }              }  }  

The animation from collapsed to expanded state works as expected: both crossfade and size change animation run simultaneously. When collapsing, though. The crossfade animation runs first, after which the size change animation starts.

How can I animate the state in such a way that the crossfade and size change animations run simultaneously for both directions?

Notification Center / Embarcadero.DesktopToasts

Posted: 24 Nov 2021 05:33 AM PST

When I call up the Notification Center, I get the value Embarcadero.DesktopToasts.???????? as the reporting app for a limited period of time.

Embarcadero.DesktopToasts

If I delete the link created by Delphi in the C:\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs directory and also the registry entries Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Embarcadero.DesktopToasts.???????? the app name will be correct again after the second call at the latest.

How can this behavior be corrected?

As a side question, in which value can I store a better icon?

How to Install Vue Packages in nuxt.js

Posted: 24 Nov 2021 05:33 AM PST

I'm trying to install Vue Typer in my Nuxt js app but no luck. I keep getting "document not defined". I tried importing it in my nuxt.config.js as a plugin but it doesn't work.

I got it working in my VueCLI 3, seems to work fine with this method.

Appreciate it!

Getting

NuxtServerError render function or template not defined in component: anonymous

////plugins///    import Vue from vue;    if (process.client) {     const VueTyper = require('vue-typer');     Vue.use(VueTyper);  }    ///nuxt.config.js///    plugins: [      {src: '~/plugins/vue-typer.js', ssr: false}    ],
<template>      <vue-typer text='Hello World! I was registered locally!'></vue-typer>  </template>    <script>  const VueTyper = processs.client ? require('vue-typer'): '';  export default {      components: {         VueTyper      }  }  </script>

No comments:

Post a Comment