Tuesday, March 23, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


convertApi.ConvertAsync is not returning converted image

Posted: 23 Mar 2021 08:33 AM PDT

I am trying to convert vsd/vsdx to png file, it was working fine until today. here is my code. please help. code stuck on convertApi.ConvertAsync line, it doesnt throw any error. but it just doesn't return anything.

public async void PrintVisioToTIFF(string VisioFilePath, string Filepath, string Extension)      {          var convertApi = new ConvertApi("XXXXXXXXXXXXXXX");            if (Extension == ".vsd")          {              var convert = await convertApi.ConvertAsync("vsd", "jpg",              new ConvertApiFileParam("File", VisioFilePath)          );              await convert.SaveFilesAsync(Filepath);          }          else if (Extension == ".vsdx")          {              var convert = await convertApi.ConvertAsync("vsdx", "png",              new ConvertApiFileParam("File", VisioFilePath)          );              await convert.SaveFilesAsync(Filepath);            }        }  

no output for existing substring is a main string python

Posted: 23 Mar 2021 08:33 AM PDT

I build a code to print strings if a substring exists at a particular section of the main string. I have a file as below and I create 5 alphabet substrings (5mers) from the seq11_rv.

>seq11_fw  TCAGATGTGTATAAGAGACAGTTATTAGCCGGTTCCAGGTATGCAGTATGAGAA  >seq11_rv  GAGATTATGTGGGAAAGTTCATGGAATCGAGCGGAGATGTGTATAAGAGACAGTGCCGCGCTTCACTAGAAGTCATACTGC  

Then I make a reverse-complement of these 5mers and append them to a list. Then I looked into the seq11_fw and if position [42:51] (GCAGTATGA in the seq11_fw) has any of items of a list then a confirmation should be printed.

To just make it easy to understand the last 5mer of the seq11_rv is ACTGC which its reverse-complement becomes GCAGT and if you check the seq11_fw[42:51] this GCAGT exists inside that location but I do not get any output.

Any help would be appreciated.

here is my code:

from Bio import SeqIO  from Bio.Seq import Seq    with open('fw_rv_cross_binding_.fasta', 'r') as f:      lst = []      for record in SeqIO.parse(f, 'fasta'):          if len(record.seq) == 81:              for i in range(len(record.seq)):                  kmer = str(record.seq[i:i + 5])                  if len(kmer) == 5:                      C_kmer = Seq(kmer).complement()                      lst.append(C_kmer[::-1])              cnt=0          if len(record.seq) == 54 and any(str(items) in str(record.seq[42:51]) for items in lst):              cnt +=1            if cnt == 1:              print(record.id)              print(record.seq)        print(lst)  

HTML email add a share email newsletter

Posted: 23 Mar 2021 08:33 AM PDT

I want to add a Share this email link/button to our email newsletter.

How to send the email to the added list of emails on clicking Share this email link/button?

Any help would be appreciated, Thanks

Antiforgery Error on Load Balanced Server

Posted: 23 Mar 2021 08:33 AM PDT

I keep getting the following error "Antiforgery token validation failed. The provided antiforgery token was meant for a different claims-based user than the current user." The environment I'm using is load balanced and we are persisting the keys to SQL Server.

Its a .NET Core 3 application and I'm using Role based authentication instead of policy. I have a custom role provider which gets the users roles from a webservice call. I've implemented the code found here https://gist.github.com/DamienBraillard/4dbd6aa2c56edf5a8e57c59b6e08da94 with my custom role provider. This works fine and everything is good until i hit an environment with a load balancer. I cant understand why I'm getting this error as I'm the same user on both nodes. I've provided the SQL Server anti forgery code below incase it may be something to do with that.

DataProtectionExtensions DataProtectionExtensions

SQLServerDataProtection SQLServerDataProtection

SqlServerXmlRepository SqlServerXmlRepository

ServiceNow KB in Azure cognitive services

Posted: 23 Mar 2021 08:33 AM PDT

Is there a way to integrate the ServiceNow KB in azure cognitive services? We want to use the ServiceNow KB as a knowledge base for Azure Cognitive.

Access local variable created by glob

Posted: 23 Mar 2021 08:33 AM PDT

I think this is not as complicated as I think but I cant get my head around it I need to access the newroad variable inside the load_songs method from the on_start method

Python

class MainApp(MDApp):        def build(self):          sm = ScreenManager()          sm.add_widget(BooksScreen(name='BooksScreen1'))          sm.add_widget(ChapterScreen(name='ChapterScreen1'))            return sm        def on_start(self):          songs = self.load_songs(newroad)          pygame.mixer.music.load(songs[0])        def load_songs(self, newroad):          songs = []          if Path('Books').is_dir():              newroad = Path.cwd() / 'Books'              print(newroad)              for filename in newroad.glob('**/*.mp3'):                  self.root.get_screen('BooksScreen1').ids.Books.add_widget(                      OneLineListItem(text=str(filename), on_release=self.change_screen,                                      pos_hint={"center_x": 1, "center_y": 1}, ))                              print(newroad)          return songs          print(newroad)        @staticmethod      def play_song(*args):          pygame.mixer.music.play()          print(OneLineListItem.text)        MainApp().run()  

I have some kivy

ScreenManager:      Screen          BooksScreen:          ChapterScreen:        <BooksScreen>:      NavigationLayout:          ScreenManager:              Screen:                  # Front / Main Screen                  MDBoxLayout:                      orientation: "vertical"                     #Toolbar                      MDToolbar:                          title: "Chapters"                          font_style: "Caption"                          elevation: 8                          left_action_items: [['menu', lambda x: nav_drawer.set_state("open")]]                        Widget:                    #stop/pause Button                  MDBoxLayout:                      orientation:"vertical"                  #    id: StopButton                      text:"Pause"                    BoxLayout:                     # Button:                        #  text: 'Goto settings'                       #   on_press:                       #       root.manager.transition.direction = 'left'                        #      root.manager.current = 'ChapterScreen1'                            # Chapters list/ Play list                  MDScreen                      MDBoxLayout:                          orientation: "vertical"                          MDList                              id: Books                #Options menu          MDNavigationDrawer:              id: nav_drawer              MDBoxLayout:                  orientation: "vertical"                  padding: "8dp"                  spacing: "8dp"                          ScrollView:                      # Options Menu Options                      MDList:                          MDRectangleFlatIconButton:                              on_press:                                  root.ids.nav_drawer.set_state("close")                                pos_hint: {"center_x": .5, "center_y": .5}                              icon: 'arrow-left'                              line_color: 0, 0, 0, 0                                  OneLineIconListItem:                              text: "Options"                              font_style: "Caption"                              #size_hint_y: None                              #height: self.texture_size[1]                             # Options Menu- About                          OneLineIconListItem:                              text: "About"                              font_style: "Caption"                             # size_hint_y: None                              #height: self.texture_size[1]                            # Options Menu Storage                          OneLineIconListItem                              text: 'Storage'                              font_style: "Caption"                              #IconLeftWidget                                  #icon: 'tools'                            # Options Menu Toolbox                          OneLineIconListItem:                              text: 'Choose Voice'                              font_style: "Caption"                                #IconLeftWidget:                              #    icon: 'toolbox'                            # Options Menu About                          OneLineIconListItem:                              text: 'About'                              font_style: "Caption"                             # IconLeftWidget:                              #    icon: 'toolbox-outline'  <ChapterScreen>:      BoxLayout:          Button:              text: 'Back to menu'              on_press:                  root.manager.transition.direction = 'right'                  root.manager.current = 'BooksScreen1'  

Which Google rest api is used for searching all address possible for taxi application?

Posted: 23 Mar 2021 08:32 AM PDT

As i am creating application like uber ola and using autocomplete api for address this one https://maps.googleapis.com/maps/api/place/textsearch/json which is not return all location such as search Gwalior railway station but it does-not show right prediction.I want to search all address search like we do in google maps.Kindly help me which api should i use to achieve from any google rest api.Thanks in advance.

how to sync contact from phone to wear os emulator in androidd

Posted: 23 Mar 2021 08:32 AM PDT

i m new to wear os development android, i m looking for how to sync contacts from phone(real device)to wear os emulator in android.?

In phone i have installed wear os by google app added email id and connected wear os to phone by bluetooth.

wear os is connected via bluetooth but when i cannot see contacts in wear os emulator still showing no contact. Can any one let me know whether we can sync contact when we are connected to wear os emulator?

how to sync contact in wear os emulator connected to real device?

Any help is really appreciated!

go generate code based on code generated by a previous go generate statement

Posted: 23 Mar 2021 08:32 AM PDT

I need to generate code using go generate based on the code generated by a previous go generate statement. More specifically, I am trying to generate an interface from a struct and its associated methods using ifacemaker, and then generate a mock from this generated interface using mockery. I am generating code using the command go generate ./... which executes the //go:generate statements in all sub-folders recursively. Here is a simple example in a file human.go:

package human    type Human struct {      Name  }    func (h Human) Hello() string {      return "Hello " + h.Name + "!"   }    //go:generate ifacemaker -f=human.go -s=Human -i=HumanInterface -p=human -o=interface.go  //go:generate mockery --name=HumanInterface --filename=mocked_human.go --outpkg=human --structname=MockedHuman    

The problem, I believe, is that the original code is parsed once at the beginning of the go generate ./... command. Therefore, HumanInterface is not found by mockery because it is generated after the code was parsed. If I run it a second time, HumanInterface will be found (because it was generated by the previous call), but the mock will be generated based on the previous interface and not the one that is (potentially) updated by the second call.

A solution would be to call go generate ./... twice, while acknowledging that the first call could potentially fail, but the code base is pretty large and a single call already takes a while to complete.

Is there a way chain two //go:generate statements, when the second one depends on the output of the first one?

Is it 5.7TB Read/ 4.2TB Write in only 371 hours normal?

Posted: 23 Mar 2021 08:32 AM PDT

Disk Info

In other words, it has a read speed of 15.8gb per hour which is pretty high and ridiculous.

Hello! Im new in Vs Code

Posted: 23 Mar 2021 08:32 AM PDT

When i tried to run the program for the first time, it crashes and this is what i got. im sure that i've installed mono sdk

PS D:\Microsoft VS Code\Projects\New Projects> cd "d:\Microsoft VS Code\Projects\New Projects" ; if ($?) { mcs Program.cs -out:Program } ; if ($?) { mono Program }

mcs : The term 'mcs' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:62

  • ... "d:\Microsoft VS Code\Projects\New Projects" ; if ($?) { mcs Program ...
  •                                                           ~~~  
    • CategoryInfo : ObjectNotFound: (mcs:String) [], CommandNotFoundException
    • FullyQualifiedErrorId : CommandNotFoundExceptionstrong text

can't install new ruby project

Posted: 23 Mar 2021 08:32 AM PDT

I can't create a new ruby project. The output from the terminal is --

rails new test1  

/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/yaml.rb:12: warning: already initialized constant YAML /Library/Ruby/Site/2.6.0/rubygems/requirement.rb:13: warning: previous definition of YAML was here Traceback (most recent call last): 11: from /usr/local/bin/rails:26:in <main>' 10: from /usr/local/bin/rails:26:in load' 9: from /Library/Ruby/Gems/2.6.0/gems/railties-6.1.3/exe/rails:10:in <top (required)>' 8: from /Library/Ruby/Site/2.6.0/rubygems/custom_require.rb:29:in require' 7: from /Library/Ruby/Site/2.6.0/rubygems/custom_require.rb:29:in require' 6: from /Library/Ruby/Gems/2.6.0/gems/railties-6.1.3/lib/rails/cli.rb:9:in <top (required)>' 5: from /Library/Ruby/Site/2.6.0/rubygems/custom_require.rb:29:in require' 4: from /Library/Ruby/Site/2.6.0/rubygems/custom_require.rb:29:in require' 3: from /Library/Ruby/Gems/2.6.0/gems/railties-6.1.3/lib/rails/ruby_version_check.rb:3:in <top (required)>' 2: from /Library/Ruby/Gems/2.6.0/gems/railties-6.1.3/lib/rails/ruby_version_check.rb:3:in new' 1: from /Library/Ruby/Site/2.6.0/rubygems/version.rb:189:in initialize' /Library/Ruby/Site/2.6.0/rubygems/version.rb:189:in strip!': can't modify frozen String (FrozenError)

PostMessage function from WinUser.h libraries doesn't work

Posted: 23 Mar 2021 08:32 AM PDT

When I used PostMessage (...) function, the text put on screen is unreadable. You can look the result on the picture. All of my drivers (graphics,....) are up to date.

I'm working on a new image of my system, the old system is windows 2016 the new is windows 2019. On the old system, I have any problem, all work fine. The problem is on the new image. I have installed same drivers, I have also compared the both directory C:\Windows\System32 and C:\Windows\SysWOW64, and copy the missing DLL. The hardware of two machines are same.

I used tools like Dependency walker for find missing DLL but it find nothing missing.

I used the function like this

m_pWnd->PostMessage ( WM_FIRSTINIT_SETTEXT, msgCode, lParam );  

some thing is missing but what ? someone has already had this problem ?

thanks to all

Get instance of json array based on passed in variable then get the values for each of the keys within [duplicate]

Posted: 23 Mar 2021 08:32 AM PDT

I have a calendar pulling data from an external php file which returns a json value.

I then have the code to pull these values

$.get( "php/get-events.php", function( data ) {    // data is your result    rawdata = JSON.parse(data);    console.log(rawdata);    });  

The console log of rawdata is showing as correct, see below -

enter image description here

I am wondering how I would go about accessing (for example) the 3rd element which has ID 7. The ID is the value I want to read based on, as this could become the 5th element if there were more calendar dates returned from the json. So essentially I am trying to find the element that contains 'id: "7"' then return all the values associated with that element.

idVar = 7;  rawdata[?].idVar;  //find the value of the ?    TitleVar = rawData[2].title;  StartVar = rawData[2].start;  

The main thing I need is to retain the flexibility so that [2] can become [3],[4] etc if there are different json values returned.

How to access first made website in Django

Posted: 23 Mar 2021 08:32 AM PDT

Hi I'm new to Django so just wanted to ask if we create a website and then create another so how can we access the first website created

R code venn diagram but only overlap 1set with the rest 3 sets

Posted: 23 Mar 2021 08:32 AM PDT

I am looking to create a Venn diagram but only overlap 1 set with the rest 3 sets and the rest of the 3 sets do not overlap with each other. Is there any R code you can recommend? The packages of "VennDiagram" & "Vennerable" I found so far are overlapped with each other for 4 sets.

Svelte: How to manually stop subscribe?

Posted: 23 Mar 2021 08:33 AM PDT

I have a store that fetches data once in a while – according to user's actions. This is a store because its data is used globally and mainly all components needs the latest data available.

But, for one specific component, I only need the first data loaded.

For this component, there is no reason to keep a subscribe() function running after the first fetch. So, how can I stop this subscribe function?

The only example in Svelte doc's uses onDestroy(), but I need to manually stop this subscribe().

I tried with a simple "count" (if count > 1, unsubscribe), but it doesn't work.

    import user from './store'            let usersLoaded = 0            const unsubscribe = user.subscribe(async (data) => {          if(data.first_name !== null) {              usersLoaded = usersLoaded + 1          }                    if(usersLoaded > 1) {              unsubscribe;          }      });  

Here's a full working REPL:

https://svelte.dev/repl/95277204f8714b4b8d7f72b51da45e67?version=3.35.0

Delete Rows that contain a specific value VBA

Posted: 23 Mar 2021 08:32 AM PDT

I'm looking to create a simple procedure which will search for the 'In Shout?' column, search for all '#N/A's' in this column and delete these rows.

When I run the below, it doesn't delete the rows and I can't figure out why. Can anyone see why?

Sub DeleteBadRows()        Dim InShout As Long      Dim NA As String            NA = "#N/A"        'Declaring year value of 1 month & 2 month      'This is important to compare datasets from 2 months ago & last month      Year_2M = Format(Date - 57, "YYYY")        'Declaring month value of 1 month & 2 month      'This is important to compare datasets from 2 months ago & last month      Month_2M = Format(Date - 57, "MM")        'This translates the current month from number to character format      MonthChar_2 = MonthName(Month_2M, False)        sheet = "MASTERFILE_" & Year_2M & Month_2M            'setting string values so that we can identify open workbooks      myFile = "Dataset"      otherFile = "Monthly Reporting Tool"      shoutFile = "Copy of Daily Shout"                'if tool wb is open, declare it as MonthlyRepTool      For Each wb In Application.Workbooks          If wb.Name Like otherFile & "*" Then             Set MonthlyRepTool = Workbooks(wb.Name)          End If      Next wb                With MonthlyRepTool.Worksheets(sheet).Rows(1)              Set e = .Find("In Shout?", LookIn:=xlValues)              InShout = e.Column          End With        lastRow = MonthlyRepTool.Worksheets(sheet).Cells(Rows.count, "A").End(xlUp).Row        For i = 2 To lastRow Step -1            If MonthlyRepTool.Worksheets(sheet).Cells(i, InShout).value = NA Then              MonthlyRepTool.Worksheets(sheet).Rows(i).EntireRow.Delete          End If                Next i    End Sub  

Python dynamic structure and memory rellocation

Posted: 23 Mar 2021 08:33 AM PDT

I am encountering this error that I think can be related to memory.

I have a class Page()

class Page:      index = [None] * 3      is_word = False     #If this is false, then is not an end word, just a passing index  

Pages are used to build a dynamic structure, index is an array of pointers (or addresses) to other pages. Initially this addresses are empty and only when added they will contain the address to another page.

As you can see the index has all values to none when any page is created.

In one part of my code I have this:

self.index[1] = Page() #Create new page  new_page = self.index[1]  

After this code is executed the initial page should contain in the array index:

  • None
  • new created page
  • None

And the new_page should should contain in the array index:

  • None
  • None
  • None

The problem is that the new_page instead contains

  • None
  • new created page
  • None

This has no sense, I am not assigning the address of the new page to this position of the index in any line. Debugging I can see that at the moment self.index[1] = Page() #Create new page is executed this new created page already contains that wrong value in the index.

I am not used to python (I am a Java and C programmer), after sometime of my first project with python I was assuming that python handles memory and I don't have to care much about it.

I think the error happens because the original array is empty and I am assigning to it a Page object so probably I am causing a memory problem. This would be handled in C with reallocs but I don't know how to solve this in python, or if maybe this memory allocation is not needed in python and the problem is a different one I am not seeing.

P.D. As requested, full code:

class Page:  index = [None] * 256  #One for each ascii character  is_word = False     #If this is false, then is not an end word, just a passing index      def insert_word(self, word):      if(len(word) == 1): #Final condition          ascii_number_word = ord(word[0])          page_of_index = self.index[ascii_number_word]          if(page_of_index == None): #If the index is not present              page_of_index = self.index[ascii_number_word] = Page()              page_of_index.is_word = True #Mark page as word        else:          letter = word[0]          resulting_word = word[1:]          ascii_number_letter = ord(letter)          page_of_index = self.index[ascii_number_letter]          if(page_of_index == None): #index does not exist, then create              self.index[ascii_number_letter] = Page() #Create new page              self.index[ascii_number_letter]              page_of_index = self.index[ascii_number_letter]          page_of_index.insert_word(resulting_word)  

git commit --fixup hash does nothing

Posted: 23 Mar 2021 08:32 AM PDT

I have a commit I want to fixup. what am I doing wrong?

git commit --fixup bdf55a7c12996e3af853c27ca4ff6c670e826c5e  On branch foo  nothing to commit, working tree clean  git --version  git version 2.31.0    

How do I pass in Angular mat dialog box width and height?

Posted: 23 Mar 2021 08:32 AM PDT

I have this Mat dialog box in Angular and I understand I should pass in the styles for width and height alongside that object but I can't manage to figure out how, it keeps throwing errors. Or is there any other way to set width and height? Thank you

let dialogRef = this.dialog.open(GroupChooseComponent, {data: {variant} });  

Discord Bot RGB Role Python

Posted: 23 Mar 2021 08:32 AM PDT

I want to write a Bot that changes the color of a Role on a server every 1 minute. What should I do? The bot is supposed to do this only on one server

Can I pass a variable from my javascript to a jsp file?

Posted: 23 Mar 2021 08:33 AM PDT

I have a variable that I create in javascript in a html file. (I cannot create this anywhere else) The variable is an array, with two entries. A latitude and a longitude. I was hoping to use ajax to send these variable and then use them in my jsp file. There I want to fill in a form with this var.

Anyone know of a way to do this? I'm working with java 1.8

Error while uploading file to Firebase Storage using Firebase Cloud Functions

Posted: 23 Mar 2021 08:32 AM PDT

I'm trying to upload a pdf to Firebase Storage using Firebase Cloud Functions, I have this post function with the following body:

{      "email":"gianni@test.it",      "name":"Gianni",      "surname":"test",      "cellphone":"99999999",      "data":       {      "file":BASE_64,      "fileName":"test.pdf"      }  }  

I want to save the base64 value in the "file" field and name as "fileName" field, here is the function that saves the file:

const admin = require("firebase-admin");    /**     * Create a new file in the storage.     * @param {Object} wrapper [File to upload in the storage.]     * @param {String} path [Path to upload file to.]     * @return {object} [Containing the response]     */    postStorageFileAsync(wrapper, path) {      return new Promise((res, rej)=>{        System.prototype.writeLog({          wrapper: wrapper,          path: path,        });        const newFile = admin.storage().bucket().file(wrapper.path);        return newFile.save(wrapper.file).then((snapshot) => {          System.prototype.writeLog({snap: snapshot});          return snapshot.ref.getDownloadURL().then((downloadURL) => {            System.prototype.writeLog({fileUrl: downloadURL});            return res({code: 200, data: {url: downloadURL}});          });        }).catch((err)=>{          System.writeLog(err);          return rej(err);        });      });    }  

But I'm getting:

postCurriculum

Error: A file name must be specified. at Bucket.file (/workspace/node_modules/@google-cloud/storage/build/src/bucket.js:1612:19) at /workspace/Firebase/Firebase.js:43:48 at new Promise () at Object.postStorageFileAsync (/workspace/Firebase/Firebase.js:38:12) at /workspace/PersistanceStorage/PersistanceStorage.js:407:35 at processTicksAndRejections (internal/process/task_queues.js:97:5)

Aside for the error itself, does anybody has a working example/tutorial link on how to upload files to firebase storage through functions? The documentation is really lacking.

Thanks

How to hand over a visual Studio program with a database connection?

Posted: 23 Mar 2021 08:32 AM PDT

After a huge amount of searching I haven't found any information about how to hand over a web project based on entity framework with an SQL Server database connection. The company I do the project for, said I have to give them the whole project to test, but the problem is that I don't know how to give it to them.

If anyone has an instruction for me on how to hand them the project and how they have to install it, it would be very nice. At first I got the project with a test database in a VMware file. I coded the whole program in there as well. But I can't just hand them the VM back in again.

I'm there if you need any further Information (code, database, etc.)

Regards KSler

Use UIViewController as TableView cell

Posted: 23 Mar 2021 08:32 AM PDT

I have a segmented control which switches between two UIViewControllers. A info view, and a list view (TableView).

I want to use the first UIViewController as the first cell of my TableView (that is on the other segment).

Is there a way to convert a UIViewController to a cell or someway to use it as a cell for a TableView?

How to make a grid in pygame

Posted: 23 Mar 2021 08:32 AM PDT

I am trying to create a basic snake game with Python and I am not familiar with Pygame. I have created a window and I am trying to split that window up into a grid based on the size of the window and a set square size.

def get_initial_snake( snake_length, width, height, block_size ):      window = pygame.display.set_mode((width,height))      background_colour = (0,0,0)      window.fill(background_colour)        return snake_list  

What should I add inside window.fill function to create a grid based on width, height, and block_size? Any info would be helpful.

How to print canvas content using javascript

Posted: 23 Mar 2021 08:32 AM PDT

I am using canvas for writing purpose using jsp page. I am able to write any message on canvas, (canvas message i have created..) enter image description here but after this when i want to print this canvas message using javascript print code i am not able to print canvas content. below you can see print preview for that.. enter image description here

I want to print canvas message that i have created on canvas. Please help me out from this problem, any help will be appreciate..

Test case execution order in pytest

Posted: 23 Mar 2021 08:32 AM PDT

I am using pytest. I have two files in a directory. In one of the files there is a long running test case that generates some output. In the other file there is a test case that reads that output. How can I ensure the proper execution order of the two test cases? Is there any alternative other than puting the test cases in the same file in the proper order?

replace array keys with given respective keys

Posted: 23 Mar 2021 08:32 AM PDT

I have an array like below

$old = array(         'a' => 'blah',         'b' => 'key',         'c' => 'amazing',         'd' => array(                  0 => 'want to replace',                  1 => 'yes I want to'                )         );  

I have another array having keys to replace with key information.

$keyReplaceInfoz = array('a' => 'newA', 'b' => 'newB', 'c' => 'newC', 'd' => 'newD');  

I need to replace all keys of array $old with respective values in array $keyReplaceInfo.

Output should be like this

$old = array(         'newA' => 'blah',         'newB' => 'key',         'newC' => 'amazing',         'newD' => array(                  0 => 'want to replace',                  1 => 'yes I want to'                )         );  

I had to do it manually as below. I am expecting better option. can anyone suggest better way to accomplish this?

$new = array();  foreach ($old as $key => $value)  {       $new[$keyReplaceInfoz[$key]] = $value;  }  

I know this can be more simpler.

No comments:

Post a Comment