Wednesday, September 1, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to close all the other related work items when a work item is closed?

Posted: 01 Sep 2021 08:04 AM PDT

Actually, I am writing MSFlow to automate some DevOps actions. I am able to retrieve all the related work items of a work item through the below API.

https://dev.azure.com/{organizationname}/_apis/wit/workitems?ids=600&$expand=all&api-version=6.0

But I don't know how to close \ how to change the state of those work items automatically. I can't see any APIs. Can someone help me with this?

Multiple events firing on button click

Posted: 01 Sep 2021 08:04 AM PDT

I'm creating a button below to the textarea and on the click on this button, reading the textarea value and downloading into csv. Below is the code snippet. Whenever, i'm clicking on Export, the downloads increasing with increasing clicks i.e. on first click, one file is downloaded, second click-two files downloaded, third click-three files downloaded and so on... pls help

`$(document).on('click', '#id_export_button', function() {                var a = document.createElement('a');          with (a) {              href = 'data:text/csv;base64,' + btoa($('textarea')[0].value);              download = 'File.csv';          }          document.body.appendChild(a);          a.click();          document.body.removeChild(a);             });    $("textarea")[0].insertAdjacentHTML('afterend', '<div id="localCreatedDIV" style="width:100%; display: flex; flex-direction: row; margin-top: 15px; justify-content: space-between"><div id="localCreatedDIVSecond" style=""><button id="id_export_button">Export</button></div></div>');`  

Access violation while requesting memory in getmem.inc

Posted: 01 Sep 2021 08:03 AM PDT

I'm trying to understand an access violation (c0000005) in my C++ program build with "Codegear C++ Builder 2009"
I have catched the access violation with procdump and analysed it with WinDbg.
Here is the information i gathered with WinDbg.:

Callstack:

  # ChildEBP RetAddr  Args to Child                >00 0d98f960 004b3728 0001e000 108c6af0 0001e000 MMIServer!SystemSysGetMem$qqri+0x316 [GETMEM.INC @ 2015]    01 0d98f978 004b443f 0d98f988 004890b8 108d5b20 MMIServer!SysReallocMem+0x2dc [GETMEM.INC @ 3404]    02 0d98f998 0048910c 0d98f9f4 108c6af0 00482730 MMIServer!ReallocMem+0x13 [System.pas @ 3521]    03 0d98f9ac 00488a40 09b60b58 108c6af0 0000f000 MMIServer!TMemoryStreamWrite+0x30 [Classes.pas @ 6181]    04 0d98f9bc 00488b0e 0d98fa04 00488b3c 0d98f9f4 MMIServer!ClassesTStreamWriteBuffer+0x18 [Classes.pas @ 5789]    05 0d98f9f4 0046d910 0000fc40 00000000 0d98fa10 MMIServer!ClassesTStreamCopyFrom+0xae [Classes.pas @ 5814]    06 0d98fa38 0046dc85 0d98faec 0046dcec 0d98fad8 MMIServer!TOPToSoapDomConvertDOMToStream+0x80 [..\..\Patches\BDS2009\TByteDynArrayThroughSOAP\OPToSOAPDomConv.pas @ 895]    07 0d98fad8 0052c272 01ca3930 10680b90 10d4daa8 MMIServer!TOPToSoapDomConvertMakeResponse+0x31d [..\..\Patches\BDS2009\TByteDynArrayThroughSOAP\OPToSOAPDomConv.pas @ 987]    08 0d98fb94 0052eff9 0d98fcfb 10680b90 10680870 MMIServer!TSoapPascalInvokerInvoke+0x34e [SOAPPasInv.pas @ 230]    09 0d98fc24 00526edb 0d98fcfb 10680b90 10680870 MMIServer!THTTPSoapPascalInvokerDispatchSOAP+0x20d [soaphttppasinv.pas @ 82]    0a 0d98fd2c 00566d5b 10d1fee0 0d98fd6c 00566d83 MMIServer!THTTPSoapDispatcherDispatchRequest+0x28b [WebBrokerSOAP.pas @ 223]    0b 0d98fd5c 00566e88 00000000 10d1fee0 0d98fda4 MMIServer!DispatchHandler+0x8b [HTTPApp.pas @ 1511]    0c 0d98fd98 00567063 0046b308 0d98fdb0 0046b321 MMIServer!TCustomWebDispatcherDispatchAction+0xf0 [HTTPApp.pas @ 1546]    0d 0d98fe10 0046b205 08dae450 02e3f360 09b21b70 MMIServer!TCustomWebDispatcherHandleRequest+0xb [HTTPApp.pas @ 1594]    0e 0d98fe28 005b6e1f 08dae450 0d98fe40 005b6e43 MMIServer!TIdHTTPWebBrokerBridgeDoCommandGet+0x2d [..\..\Patches\Indy10\IdHTTPWebBrokerBridge.pas @ 964]    0f 0d98fefc 005d86be 01c23370 005c7939 005c7783 MMIServer!IdcustomhttpserverTIdCustomHTTPServerDoExecute$qqrp20IdcontextTIdContext+0x683   10 0d98ff70 0048da71 0d98ff84 0048da7b 0d98ffa0 MMIServer!IdcontextTIdContextRun$qqrv+0x12   11 0d98ffa0 004b63f2 0d98ffdc 004b5e74 0d98ffb4 MMIServer!ThreadProc+0x45 [Classes.pas @ 10892]    12 0d98ffb4 7c80b729 08b3e090 030afabc 00000000 MMIServer!ThreadWrapper+0x2a [System.pas @ 13819]   

CodeGear\RAD Studio\6.0\source\Win32\rtl\sys\getmem.inc:

 2004 @GotBinAndGroup:   2005   {ebx = block size, ecx = bin number, edx = group number}   2006   push esi   2007   push edi   2008   {Get a pointer to the bin in edi}   2009   lea edi, [MediumBlockBins + ecx * 8]   2010   {Get the free block in esi}   2011   mov esi, TMediumFreeBlock[edi].NextFreeBlock   2012   {Remove the first block from the linked list (LIFO)}   2013   mov eax, TMediumFreeBlock[esi].NextFreeBlock   2014   mov TMediumFreeBlock[edi].NextFreeBlock, eax  >2015   mov TMediumFreeBlock[eax].PreviousFreeBlock, edi   2016   {Is this bin now empty?}   2017   cmp edi, eax   2018   jne @MediumBinNotEmptyForMedium   2019   {eax = bin group number, ecx = bin number, edi = @bin, esi = free block, ebx = block size}   2020   {Flag this bin as empty}   2021   mov eax, -2   2022   rol eax, cl   2023   and dword ptr [MediumBlockBinBitmaps + edx * 4], eax   2024   jnz @MediumBinNotEmptyForMedium   2025   {Flag the group as empty}   2026   btr MediumBlockBinGroupBitmap, edx   2027 @MediumBinNotEmptyForMedium:  

Disassembly:

 004b31d4 56              push    esi   004b31d5 57              push    edi   004b31d6 8d3ccd00be3201  lea     edi,MMIServer!NeverSleepOnMMThreadContention+0x1ef (0132be00)[ecx*8]   004b31dd 8b7704          mov     esi,dword ptr [edi+4]   004b31e0 8b4604          mov     eax,dword ptr [esi+4]   004b31e3 894704          mov     dword ptr [edi+4],eax  >004b31e6 8938            mov     dword ptr [eax],edi  ds:0023:00000000=????????   004b31e8 39c7            cmp     edi,eax   004b31ea 7517            jne     MMIServer!SystemSysGetMem$qqri+0x333 (004b3203)   004b31ec b8feffffff      mov     eax,0FFFFFFFEh   004b31f1 d3c0            rol     eax,cl   004b31f3 21049580bd3201  and     dword ptr MMIServer!NeverSleepOnMMThreadContention+0x16f (0132bd80)[edx*4],eax   004b31fa 7507            jne     MMIServer!SystemSysGetMem$qqri+0x333 (004b3203)   004b31fc 0fb3157cbd3201  btr     dword ptr [MMIServer!NeverSleepOnMMThreadContention+0x16b (0132bd7c)],edx  

My understanding of this piece of code of getmem.inc is:

  1. There is a double-linked list of free memory blocks.
  2. One block is taken from this list.
  3. The Double Linked List is reconnected.

In drawing:

|----------|--------------------->|----------|--------------------->|----------|  |          | NextFreeBlock        |          | NextFreeBlock        |          |  |  132d408 |                      | 11290132 |                      | 00000000 |  |          |<---------------------|          |<---------------------|          |  |----------|    PreviousFreeBlock |----------|    PreviousFreeBlock |----------|       ^                                  ^                                 ^       |                                  |                                 |      edi                                esi                               eax      |----------|--------------------->|----------|                      |----------|  |          | NextFreeBlock        |          |                      |          |  |  132d408 |                      | 00000000 |                      | 11290132 |  |          |<---------------------|          |                      |          |  |----------|    PreviousFreeBlock |----------|                      |----------|       ^                                  ^                                 ^       |                                  |                                 |      edi                                eax                               esi  

Some registers:

eax 0  ebx 1e030  ecx 2c1  edx 16  edi 132d408  esi 11290132    ebp 1e000  eip 4b31e6  esp d98f958  

There is a NULL pointer in the Double Linked Lists of the free memory blocks.
When writing the PreviousFreeBlock to this address the access violation occurred.

How can there be a NULL pointer in the Double Linked Lists of the free memory blocks?
Was the memory already corrupted?
Have anyone experienced the same problem in getmem.inc?
What can i do to investigate this crash further?

Is there an uncomplicated way to split an array of deeply nested objects, based on a pattern of keys discovered in deep nests of individual objects?

Posted: 01 Sep 2021 08:03 AM PDT

Let's say there's an array of deeply nested objects, where the depth is known. All the objects in the array have a similar structure. The input array could be something like below:

[    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'Code[1]': 'asd',              'Code[2]': 'xyz',              'CodeDeep[1]': 'qwe',              'CodeDeep[2]': 'rty',              'Phoebe[5]': 'rty',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd_mod': {          'e': {              'f': 'val',              'g': 'val2',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'CodeDeep[2]': 'rty',              'h': {                  Some other object data          }        }      }    }  ]  

Key 'd' in the example can also be 'd_mod', but that's not a problem, as we can do ('d' || 'd_mod') while traversing. The challenge is when traverse the values of 'e', we find a pattern in the key name. It could be anything alphanumeric followed by '[someNumber]'.

Few things to consider: If the key Code[1] is present, then it's not necessary that CodeDeep[1] is also there and vice versa. There can be as many keys matching the pattern. i.e. If Code[1] is there, then Code[2] can also be there and so on. The starting alphabets in the pattern will always be there. i.e. only the number changes in either Code[number here] or CodeDeep[number here]. The numbering in the key pattern doesn't have to be sequential always. Also it's possible that there is no such match, in that case the object will not be splitted and stays as is. If the number in the patterns of keys in nested object 'e' is same for multiple keys then both the keys go in same split of the object. The keys in the split objects can be same as the pattern or with '[number]' bit stripped.

The desired outcome(s):

[    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'Code[1]': 'asd',              'CodeDeep[1]': 'qwe',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'Code[2]': 'xyz',              'CodeDeep[2]': 'rty',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'Phoebe[5]': 'rty',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd_mod': {          'e': {              'f': 'val',              'g': 'val2',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'CodeDeep[2]': 'rty',              'h': {                  Some other object data          }        }      }    }  ]    

or without numbers but everything else as same:

[    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'Code': 'asd',              'CodeDeep': 'qwe',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'Code': 'xyz',              'CodeDeep': 'rty',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'Phoebe': 'rty',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd_mod': {          'e': {              'f': 'val',              'g': 'val2',              'h': {                  Some other object data          }        }      }    },    {      'a': {          SomeObjectData      },      'b': {          Something Else      },      'c': '',      'd': {          'e': {              'f': 'val',              'g': 'val2',              'CodeDeep': 'rty',              'h': {                  Some other object data          }        }      }    }  ]  

both are acceptable as there won't be any cases where keys like Code[1] and Code[2] will end up in the same object by earlier requirements. Again to reiterate main problem: Pattern matching similar numbered keys, leads to split, and if only single number for all keys in an object, then no split is required. Also if no pattern, then no split is required.

I did manage to solve above, but I'm after something that doesn't look as messy as mine.

My attempt: Below takes a single object in the array and nested property then splits it returning array of nested property splits.

const sameKeyArray = arr => {      const [rest, ...numbered] = Object.values(Object.entries(arr).reduce((o, [k, v]) => {        const acc = o;        const [name, number] = k?.replace('[', '').match(/\D+|\d+\]$/g);        acc[number] = { ...(acc[number] || {}),          [name]: v        };        return acc;      }, {}));      return numbered.map(i => ({ ...i,        ...rest      }));    };  

Then I iterate over the initial input array, where for each item i intend to override the value of nested property i.e. 'e' in our example from an dict object to an array of splitted dicts/objects, using above function.

originalInputArray.map(e => ({ ...e,      data: { ...e?.data,        text: { ...e?.data?.text,          [Object.keys(e?.data?.text)[0]]: { ...e?.data?.text?.['d' || 'd_mod'],            nested_prop: sameKeyArray(e?.data?.text?.['d' || 'd_mod']?.nested_prop || {})          }        }      }    }));  

Note that still original items have not been returned as cartesian products. Only the deeply nested property of individual items in the array have been changed from object to array.

AgainI traverse through input array from above which is now modified. Where for each item and for length of nested property, i push entire item along with nested property set to ith element, in a new list, which gives me the final output. Here's the final traversal code.

const nested_propSplits = [];    modifiedInputArray.forEach(e => {      e.data.text['d' || 'd_mod'].nested_prop.forEach(element => {        nested_propSplits.push({ ...e,          data: { ...e?.data,            text: { ...e?.data?.text,              [Object.keys(e?.data?.text)[0]]: { ...e?.data?.text?.['d' || 'd_mod'],                nested_prop: element              }            }          }        });      });    });  

If any explanation is not clear, needs clarification, code and/or examples are not aligned with the initial requirements, let me know, I'll update/clarify at the earliest. Any suggestions and cool ideas are welcome.

Excel formula to count date ranges

Posted: 01 Sep 2021 08:03 AM PDT

I need to come up with a formula that will count the number of rows of a date column. I need greater than 365, 300-365, 299-230 ect all the way down to 30 days. One formula for each will be perfect and as long as I can figure out the first couple, I can get the rest. Help is much appreciated.

The date format in the excel table is: 9/1/2021

A year or older. Seems this may be close but it's giving an error

=COUNTIF(A1:A1000,">="=DATE(YEAR(=TODAY()-1)))

=COUNTIFS(A1:A1000,">="=DATE(DAY(=TODAY()-364)),A1:A1000,"<="=DATE(DAY(=TODAY()-300)))

JSON - How to avoid code redundancy, how can I avoid repeating the same block twice

Posted: 01 Sep 2021 08:03 AM PDT

JSON - How to avoid code redundancy, how can I avoid repeating the same block twice

   "main": {         "block1": {            "x": "text1",            "y": "text2",            "z": "text3",         },         "block2": {            "x": "text1",            "y": "text2",            "z": "text3",         }      }  

Struggling to vectorize an iterrows function that removes duplicate values, keeping only the first

Posted: 01 Sep 2021 08:03 AM PDT

I have a script that uses iterrows and have read that this is an inefficient method and would like to refine my code. But after reading other questions on the topic I haven't found the answer to my specific example. I'm a complete amateur coder so would appreciate any assistance in getting better.

I just want to remove duplicates in a series, keeping only the first and leaving blanks for subsequent rows with the same time. I keep the first row's time no matter what, so I start with comparing the second value.

def clean_times(df):        time = df.iloc[1]['Result']  # initilize to the first time gap      if ':' in time:          for index, row in df.iterrows():              if index > 1:                  if row['Result'] == time:                      df.loc[index, 'Result'] = ''                  else:                      time = row['Result']      return df      time = ''  
x = [{'Result':'4:51:36'},{'Result':'0:01:27'},{'Result':'0:02:19'},{'Result':'0:02:42'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:02:57'},{'Result':'0:03:03'},{'Result':'0:03:03'},{'Result':'0:03:23'},{'Result':'0:03:23'},{'Result':'0:03:23'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:03:57'},{'Result':'0:04:02'},{'Result':'0:04:15'},{'Result':'0:04:15'},{'Result':'0:04:25'},{'Result':'0:04:25'},{'Result':'0:04:25'}]  df = pd.DataFrame(x)  df1 = clean_times(df)  

Result

Result  0   4:51:36  1   0:01:27  2   0:02:19  3   0:02:42  4   0:02:57  5     6     7     8     9     10    11    12    13    14    15    16    17    18  0:03:03  19    20  0:03:23  21    22    23  0:03:57  24    25    26    27    28    29    30    31    32    33  0:04:02  34  0:04:15  35    36  0:04:25  37    38    

Java 8 filter to stream list return by method

Posted: 01 Sep 2021 08:04 AM PDT

I'm still learning java 8, but here's what I'm basically trying to do. I have this method here that I'd like to convert into a stream.

public void checkCustomers() {      List<Student> students = studentRegistry.getAllStudents();    List<Student> mathStudents = new ArrayList<>();    List<Customer> studentCustomers = new ArrayList<>();      for (Student student : students) {         if (!student.getAll().contains(Classes.MATH101)) {             mathStudents.add(student);         }     }       for (Student student : mathStudents){         studentCustomers = getCustomers(student.getId());     }       cancelCustomers(studentCustomers);  }  

I've been working on this for a while and having a ton of issues. I'm basically trying to do something like this:

cancelCustomers(studentRegistry.getAllStudents().stream()                 .filter(Objects::nonNull)                 .filter(p -> (p.getAll().contains(Classes.MATH101)))                 .collect(Collectors.toList()));  

I know this doesn't work for a lot of reasons, but every time I fix one of them, a different issue seems to pop up. I can share other code if necessary, but the main bit of what I'm trying to do is here.

openssl decryption works even with modified key

Posted: 01 Sep 2021 08:04 AM PDT

I executed the below command and generated a random key

openssl rand -hex 45

and it generated me

524ec7a76ad9140087232b8e278c03d4bc121fdfd0e4f13a6bd16959a81e2d289b5edcf0848b435fc201fc4c1c

I then encrypted me file with Open ssl using this. When i tried to decrypt i just changed last two characters like this

524ec7a76ad9140087232b8e278c03d4bc121fdfd0e4f13a6bd16959a81e2d289b5edcf0848b435fc201fc4c2d

and now when it tried to decrypt, it still works and decrypt the file... what could be wrong ? Below is my decrypt command

export my_key=524ec7a76ad9140087232b8e278c03d4bc121fdfd0e4f13a6bd16959a81e2d289b5edcf0848b435fc201fc4c2d

openssl enc -aes-256-cbc -d -in my-secret-encrypted.enc -K $my_key -iv 9 > my-secret.txt

How to align a div within a div using flex and flex-col Tailwind CSS

Posted: 01 Sep 2021 08:04 AM PDT

I'm trying to vertically center the div with a white border onto the div with a green background. Colors just for show. I cannot figure out why justify-center and items-center do not work. I know I can use margin to achieve what I want but I know there's a better way. I have tried referencing this SO post but have had no luck:Reference Post

Also, if there is a better solution to implement what I want I'm all ears.

My code:

<div class="flex flex-col min-h-screen bg-coolGray-900">      <div class="w-screen justify-center items-center h-screen bg-green-500 ">          <div class="text-center text-white border-2 ">              <h1 class="mb-10 text-6xl font-bold font-lato">Message Here</h1>              <h2 class="mb-8 text-2xl font-semibold font-lato">More Detailed Message Here</h2>              <button class="mx-auto btn btn-learn">Learn More</button>          </div>      </div>  </div>  

enter image description here

SQL Pivot problems

Posted: 01 Sep 2021 08:04 AM PDT

I have a view called vwLocations that contains addresses for a person

columns are personid, address1, address2, city, state, zip

i person can have 1 to many addresses

I need to pull this in a dynamic pivot but i am struggling:

results should be

personid, aadr1 Address1, aadr1Address2, aadr1City, addr1State, addr2Zip, addr2Address1, addr2Address2, addr2City, addr2State...addrNAddres1, addrNAddress2, addrNCity, addrNState

EDIT:

PersonID Address1 Address2 City State Zip
1 123 main st Home CA 90210
1 456 main st Home CA 90210
1 789 main st Home CA 90210
2 123 main st Home CA 90210
2 456 main st Home CA 90210
2 789 main st Home CA 90210
3 123 main st Home CA 90210

given that input i would need the following output

PersonID Addr1Address1 Addr1Address2 Addr1City Addr1State Addr1Zip Addr2Address1 Addr2Address2 Addr2City Addr2State Addr2Zip Addr3Address1 Addr3Address2 Addr3City Addr3State Addr3Zip
1 123 Main St Home CA 90210 456 Main St Home CA 90210 789 Main St Home CA 90210
2 123 Main St Home CA 90210 456 Main St Home CA 90210 789 Main St Home CA 90210
3 123 Main St Home CA 90210

Changing div width with a button

Posted: 01 Sep 2021 08:04 AM PDT

i am trying to learn JS, React and Node.js. Now i am trying to change the width of a div with a button but i'm getting always the same error, that it "Cannot read property 'style' of null

Here is my JS

var sideNav = document.getElementById("side-nav");  var linksSideNavTop = document.getElementById("links-side-nav-top");  var linksSideNavBottom = document.getElementById("links-side-nav-bottom");      function openMenuTablet() {      if (sideNav.style.width === '70px') {          sideNav.style.width = '300px';          linksSideNavTop.style.display = "block";          linksSideNavBottom.style.display = "block";      } else {          sideNav.style.width = '70px';          linksSideNavTop.style.display = "none";          linksSideNavBottom.style.display = "none";      };  }  

Here the CSS

#side-nav {      position: fixed;      background-color: #454545;      height: 100%;      width: 70px;  }  

Decrypting GPG encrypted file in gihub actions fails, seemingly due to corrupt file

Posted: 01 Sep 2021 08:03 AM PDT

So this is a strange one. I've been following the guide for keeping large secrets (use GPG to symmetrically/password-encrypt the file, set the passphrase as a secret, decrypt at action runtime). The problem is that every time I try to decrypt the file, the decryption fails with either gpg: Fatal: zlib inflate problem: invalid distance too far back or gpg: block_filter 0x00000008000488d0: read error (size=7858,a->size=262834) gpg: block_filter: pending bytes!

Both of those error messages, combined with the fact that if I check the MD5 of the files locally and in the runner they don't match, lead me to believe the files are getting corrupted somehow, but I'm not sure how. I've tried committing them both via local git, and by uploading them through the web ui (to hopefully eliminate LF/CRLF issues) but no dice.

The command I'm using to encrypt: gpg --symmetric --cipher-algo AES256 .\secret_file.json

And the step in my build process that decrypts:

      - shell: pwsh          env:            DECRYPTION_PASSPHRASE: ${{ secrets.DECRYPTION_PASSPHRASE }}          run: |            gpg --quiet --batch --yes --decrypt --passphrase=$env:DECRYPTION_PASSPHRASE --output secret_file.json secret_file.json.gpg  

Locally, I'm using gnupg 2.2.27 installed via chocolatey, and my build is running on github's windows-2019 runner. Any advice would be very appreciated!

Clone, filter and plonk HTML node with jQuery

Posted: 01 Sep 2021 08:04 AM PDT

I try to clone subnode of HTML, filter the clone and plonk it elsewhere in the page.

I try this:

var emailTemplate = $("#email-post")[0]  $("#tempStoreEmailTemplate").val(emailTemplate.outerHTML)  $(tempStoreEmailTemplate).find('.num6:hidden').remove();  $("#iframe-textarea").val(tempStoreEmailTemplate.val)//.outerHTML  
<div id="tempStoreEmailTemplate" hidden></div>  

I tried both tempStoreEmailTemplate.val and tempStoreEmailTemplate.outerHTML in the last line. .outerHTML shows this text

<div id="tempStoreEmailTemplate" hidden=""></div>  

.val shows nothing.

The expected result would be to see the textual representation of the modified subnode. Do you know what is wrong?

whats the exact rule in function declaration in c++

Posted: 01 Sep 2021 08:03 AM PDT

I want to know is it mandatory to have constant arguments in the functions. Recently I had in interview and wrote a code like below

string& substring(string s1, string s2)  {     return s1.substr(s1.find(s2)+s2.length());  }  

The panel was expecting const string&s1 ,const string&s2 but i didn't wrote bcz of substr functionality usage...

can any one guide what's the standardised format to write the code.... the panel was insisting to improve the arguments in the function.

Dictionary comprehension - dynamically generate key-value pairs?

Posted: 01 Sep 2021 08:03 AM PDT

I want to achieve the same result of

{i: i+1 for i in range(4)} # {0: 1, 1: 2, 2: 3, 3: 4}  

But dynamically generate key: value part with myfunc(i), how do I do that?

Functions that return {i: i+1} or (i, i+1) won't work:

{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'  

Accessing object this key while nested

Posted: 01 Sep 2021 08:04 AM PDT

How can I access minimap.x inside of minimap.player.x

const minimap = {    x: 10,    y: 10,    width: 100,    height: 40,    player: {      x: this.x + 20, // But this doesn't work because we're currently in the player object      y: this.y + 20,      radius: 2,    },  };  

What I want is minimap.x inside of minimap.player.x.

Default username and password in connection string SQL Server

Posted: 01 Sep 2021 08:03 AM PDT

I'm trying to do a connection with SQL Server, setting my connection string.

Does anybody know the default username and password?

"DefaultConnection": "Server=(localdb)\\\\MSSQLLocalDB;Database=db_fields;User Id=;Password=;"  

How to improve the performance of queries when joining a lot of huge tables?

Posted: 01 Sep 2021 08:04 AM PDT

This is my SQL script, I have to join 7 tables

SELECT concat_ws('-', it.item_id, it.model_id) AS product_id,         concat_ws('-', aip.partner_item_id, aip.partner_model_id) AS product_reseller_id,         i.name as item_name,         im.name AS model_name,         p.partner_code,         sum(it.quantity) AS transfer_total,         sum(isb.remaining_item) as remaining_stock,         sum(isb.sold_item) as partner_sold  FROM transfer t  INNER JOIN partner p ON p.reseller_store_id = t.reseller_store_id  INNER JOIN item_transfer it ON t.id = it.transfer_id  INNER JOIN item i ON i.id = it.item_id  INNER JOIN item_model im ON it.model_id = im.id  INNER JOIN affiliate_item_mapping aip on it.item_id = aip.seller_item_id and it.model_id = aip.seller_model_id  and t.reseller_store_id = aip.reseller_store_id  LEFT JOIN inventory_summary_branch isb on isb.inventory_summary_id = concat_ws('-', aip.partner_item_id, aip.partner_model_id)  WHERE p.store_id = 9805  GROUP BY it.item_id, it.model_id, p.partner_code, i.id, im.id, aip.id, isb.inventory_summary_id  

This is the result of SQL EXPLAIN:

GroupAggregate  (cost=13861.57..13861.62 rows=1 width=885) (actual time=1890.392..1890.525 rows=15 loops=1)    Group Key: it.item_id, it.model_id, p.partner_code, i.id, im.id, aip.id, isb.inventory_summary_id    Buffers: shared hit=118610    ->  Sort  (cost=13861.57..13861.58 rows=1 width=765) (actual time=1890.310..1890.338 rows=21 loops=1)          Sort Key: it.item_id, it.model_id, p.partner_code, aip.id, isb.inventory_summary_id          Sort Method: quicksort  Memory: 28kB          Buffers: shared hit=118610          ->  Nested Loop  (cost=1.27..13861.56 rows=1 width=765) (actual time=73.156..1890.057 rows=21 loops=1)                Buffers: shared hit=118610                ->  Nested Loop  (cost=0.85..13853.14 rows=1 width=753) (actual time=73.134..1889.495 rows=21 loops=1)                      Buffers: shared hit=118526                      ->  Nested Loop  (cost=0.43..13845.32 rows=1 width=609) (actual time=73.099..1888.733 rows=21 loops=1)                            Join Filter: ((p.reseller_store_id = t.reseller_store_id) AND (it.transfer_id = t.id))                            Rows Removed by Join Filter: 2142                            Buffers: shared hit=118442                            ->  Nested Loop  (cost=0.43..13840.24 rows=1 width=633) (actual time=72.793..1879.961 rows=21 loops=1)                                  Join Filter: ((aip.seller_item_id = it.item_id) AND (aip.seller_model_id = it.model_id))                                  Rows Removed by Join Filter: 6003                                  Buffers: shared hit=118379                                  ->  Nested Loop Left Join  (cost=0.43..13831.47 rows=1 width=601) (actual time=72.093..1861.415 rows=24 loops=1)                                        Buffers: shared hit=118307                                        ->  Nested Loop  (cost=0.00..11.44 rows=1 width=572) (actual time=0.042..0.696 rows=24 loops=1)                                              Join Filter: (p.reseller_store_id = aip.reseller_store_id)                                              Rows Removed by Join Filter: 150                                              Buffers: shared hit=7                                              ->  Seq Scan on partner p  (cost=0.00..10.38 rows=1 width=524) (actual time=0.026..0.039 rows=6 loops=1)                                                    Filter: (store_id = 9805)                                                    Buffers: shared hit=1                                              ->  Seq Scan on affiliate_item_mapping aip  (cost=0.00..1.03 rows=3 width=48) (actual time=0.006..0.043 rows=29 loops=6)                                                    Buffers: shared hit=6                                        ->  Index Scan using branch_id_inventory_summary_id_inventory_summary_branch on inventory_summary_branch isb  (cost=0.43..13820.01 rows=1 width=29) (actual time=77.498..77.498 rows=0 loops=24)                                              Index Cond: ((inventory_summary_id)::text = concat_ws('-'::text, aip.partner_item_id, aip.partner_model_id))                                              Buffers: shared hit=118300                                  ->  Seq Scan on item_transfer it  (cost=0.00..5.31 rows=231 width=32) (actual time=0.024..0.391 rows=251 loops=24)                                        Buffers: shared hit=72                            ->  Seq Scan on transfer t  (cost=0.00..3.83 rows=83 width=16) (actual time=0.011..0.256 rows=103 loops=21)                                  Buffers: shared hit=63                      ->  Index Scan using pk_item on item i  (cost=0.42..7.81 rows=1 width=152) (actual time=0.022..0.023 rows=1 loops=21)                            Index Cond: (id = it.item_id)                            Buffers: shared hit=84                ->  Index Scan using pk_item_model on item_model im  (cost=0.43..8.41 rows=1 width=20) (actual time=0.016..0.018 rows=1 loops=21)                      Index Cond: (id = it.model_id)                      Buffers: shared hit=84  Planning time: 10.051 ms  Execution time: 1890.943 ms  

Of course, this statement works fine, but it's slow. Is there a better way to write this code?

How can I improve the performance? Join or sub-query is better in this case? Anyone, please give me a hand

Regex expression to match strings after example codes

Posted: 01 Sep 2021 08:03 AM PDT

Hello I'm trying to make regex expression to match text after code example of regex that I have at the moment with sample text.

(?<=H\d\d\d)([.*\w\W\n]+)(?=End word)  

https://regex101.com/r/9SBnH9/2

Sample text  Sample text  Sample text  H319 asdkjczixuqweoiurqoiweqwrjasdkjfqwe qweiouqwroiu kjasdkj czkjxklqjwekjiouasdiiaosudou  oiuasodiucxzlkjqweoiu oqiwur H320 asdkqjwe askjdq xzc  H325 asjdhasjd zxcjh  H331+H341+H341 askdjvkjzx qweqrqwoe  End word  Sample text  Sample text  

This is the sample text and I want expression to start searching for matches after find H** code and get the text only when find again H** code ignore it and take the text and have example with H**+H**+H** or H**+H**, but same deal skip H codes and get the text only. And search until it finds End word. I'm to the point where it start from first H code, but then it get all the string and end's on end word you can see that in regex site which I send.

I should get this as result: asdkjczixuqweoiurqoiweqwrjasdkjfqwe qweiouqwroiu kjasdkj czkjxklqjwekjiouasdiiaosudou oiuasodiucxzlkjqweoiu oqiwur.asdkqjwe askjdq xzc.asjdhasjd zxcjh.askdjvkjzx qweqrqwoe

Type value into email input field with JavaScript

Posted: 01 Sep 2021 08:03 AM PDT

I'm trying to write an email address into an input field with JavaScript. It should not be that hard. But I'm not able to do it. The input field has validation. Maybe this is the problem.

I already tried:

document.getElementsByClassName('sc-kEYyzF mqvXI')[0].setAttribute("value", "xyz@gmail.com");  document.getElementById("email").value = "xyz00@gmail.com";  

But after I click on the submit button, the input disappears. I'm trying this on this website: https://welcome.onelog.ch/

EDIT: Thanks to @epascarello. With his code I found the correct solution

SOLUTION:

let lastValue = input.value;  input.value = 'xyz@gmail.com';  let event = new Event('input', { bubbles: true });  event.simulated = true;  let tracker = input._valueTracker;  if (tracker) {    tracker.setValue(lastValue);  }  input.dispatchEvent(event);```  

Creating a for if loop with custom range

Posted: 01 Sep 2021 08:03 AM PDT

So I'm trying to create a script checking the A column with row 8,9,10,11,12,13, SKIPPING 14, 15,16,17,18, SKIPPING 19, 20,21,22. If it is empty I would like to hide that row.

Is there a way to define the range of rows before the if statement?

This is what I have, but I need to do a seperate loop every time there is a gap in rows

 for (i = 8; i < 14; i++) {  //for loop for Current rep      if (sheet.getRange(i, 1).getValue() == "") {       sheet.hideRows(i)};        };         

how to sent Information from ComboBox to Python

Posted: 01 Sep 2021 08:03 AM PDT

I have a simple code nothing crazy but i just can't figure out how i can sent information from ComboBox to Python. I know the connection between pyton and qml is good, becouse i can sent other strings to python from qml.

Thanks in advance

Funcy.py

@pyqtSlot(str)  def mail(self, dropdown):        print(dropdown) #should print Yes or No  

Gui.qml

ComboBox  {      id: dropdown        // those are the options a user could choose      model: ["No", "Yes"]  }    Button  {      // some styling        onClicked      {          backend.mail(dropdown.text)      }  }  

how to get active index with accordionPanel using primefaces in backing bean

Posted: 01 Sep 2021 08:04 AM PDT

when i try to get active index any accordion panel then its always return -1 value. I am using primefaces 7.0 version.

When i try to enable form tag then it is not working with the process of flow step wise.

I have also try other solutions from stackoverflow but nothing tobe work for me. Anyone have idea about this.

1.example.xhtml

<!-- <h:form> -->                                              <ui:fragment          rendered="#{not empty excursionResultsBean.excursionAvailabilities and not empty excursionResultsBean.excursionAvailabilities[0].excursionCategoryBeans}">          <p:accordionPanel multiple="false"              activeIndex="#{panelDisplayBean.index}" role="tablist"  id="indexId" cache="false" >                <f:ajax event="tabChange"                  listener="#{excursionResultsBean.onTabChange}" update="@form"/>                            <ui:insert name="creditCardPanel1">                  <ui:include src="step1.xhtml" />              </ui:insert>              <ui:insert name="creditCardPanel2">                  <ui:include src="step2.xhtml" />              </ui:insert>              <ui:insert name="creditCardPanel3">                  <ui:include src="step3.xhtml" />              </ui:insert>              <ui:insert name="creditCardPanel4">                  <ui:include src="step4.xhtml" />              </ui:insert>                                      </p:accordionPanel>      </ui:fragment>            <ui:fragment          rendered="#{empty excursionResultsBean.excursionAvailabilities or empty excursionResultsBean.excursionAvailabilities[0].excursionCategoryBeans}">          <div>              <p>Sorry! We're booked to capacity on your flight</p>              Please share your travel details with us at <b><a                  href="mailto:guest.ss@ss.com">guest.ss@ss.com</a></b>,              so that we can work on this specially for you! Or call                        </div>        </ui:fragment>  <!-- </h:form> -->  

method in bean

public void onTabChange(TabChangeEvent event) {          UITabPanel tabView = (UITabPanel) event.getComponent();          int activeTab = tabView.getChildren().indexOf(event.getTab());          System.out.println("Active index "+activeTab);  }  

OData Filtering By Latest Data

Posted: 01 Sep 2021 08:03 AM PDT

I'm trying to use WHO API to download a dataset, they use OData protocol. I need to filter by Country and latest year for which data available. Is there a way to update the following query to return only the latest year available (the year could differ from one country to another).

https://ghoapi.azureedge.net/api/{indicator}?$filter=SpatialDimType%20eq%20'COUNTRY'%20and%20date(TimeDimensionBegin)%20ge%202015-01-01%20and%20date(TimeDimensionBegin)%20lt%202021-01-01

Getting all words before a specific word in SAS

Posted: 01 Sep 2021 08:03 AM PDT

I have a SAS dataset which has text column as below:

" word1 word2 documented word .... word n"

I have two issues with:

  1. While performing text cleaning, I want to remove numbers from this word, but using compress function is compressing everything into 1 word and thus making sentence unreadable?
  2. I want to extract all the words before word "documented"

Any please?

input dataset:

enter image description here

Output dataset

ID Comments Results 1 increase documented this credit package requires approval increase 2 new business modification documented ls&f cancelled new business modification 3 annual renewal documented this package requires approval annual renewal

How to put a 'grid' (for example dividing the x-y plane into bins) on an image to calculate mean of the z-values in every bin and plot as a heatmap?

Posted: 01 Sep 2021 08:03 AM PDT

My aim:

I have x, y and z values as arrays. For example:

x=np.array([10,2,-4,12,3,6,8,14])  y=np.array([5,5,-6,8,20,10,2,2])  z=np.array([4,6,10,40,22,14,20,8])  

I want to plot a heatmap where the z-values will act as the intensity or 'weight' for every pair of (x,y) and the axes will be x and y values. So, my plot will be on a x-y plane. I want to lay a 'grid' on top of my plot by dividing my x-y plane into bins and then calculate the mean of the z-values within every bin and use that mean value as my color or intensity for that bin. I also want to make another plot but there I want to plot the variance of z-values as the intensity within the bins.

What I have done:

I coded it the following way but I think I am misinterpreting things..I don't think I understand bins etc well (I am new to programming).

import numpy as np  import matplotlib.pyplot as plt  x=np.array([10,2,-4,12,3,6,8,14])  y=np.array([5,5,-6,8,20,10,2,2])  z=np.array([4,6,10,40,22,14,-20,8])    # Bin the data onto a 2x2 grid  # Have to reverse x & y due to row-first indexing  zi, yi, xi = np.histogram2d(y, x, bins=(2,2), weights=z, normed=False)  counts, _, _ = np.histogram2d(y, x, bins=(2,2))    #to get mean divide by counts    zi = zi / counts  print(zi)    zi = np.ma.masked_invalid(zi)    fig, ax = plt.subplots()  sc=ax.pcolormesh(xi, yi, zi, edgecolors='black')  sct = ax.scatter(x, y, c=z, s=200) #shows the points in the bins   fig.colorbar(sc)  ax.margins(0.05)    plt.show()  

Where I am stuck:

I am not even sure if the above code is doing the right thing. So, feel free to forget it and advise me on any other standard way of solving this problem. With the above code I get a plot where the axes limits are determined by the given dataset automatically but I want to keep my axes constant at xmin=-20,xmax=20,ymin=-20,ymax=20. Also, I am not sure how to manipulate the z-values within the bins to calculate other statistical quantities like variance or standard deviation etc.

EDIT: so, I have got some better code that gives the mean z values in bins and plot using np.histogram2d and the I can set the axes etc to my liking now but using this gives H as the sum of values in bins and I can get the mean from that but not other statistical quantities like variance. I wanted a way to code this so that I can have access to the values in the bin and I can calculate variance of those and use that result as the weight/intensity of the heatmap.

I am attaching the plot for mean z in bins.

import numpy as np  import matplotlib.pyplot as plt    x=np.array([10,2,4,12,3,6,8,14])  y=np.array([5,5,6,8,20,10,2,2])  z=np.array([4,6,10,40,22,14,20,8])    x_bins = np.linspace(0, 20, 3)  y_bins = np.linspace(0, 20, 3)    H, xedges, yedges = np.histogram2d(x, y, bins = [x_bins, y_bins], weights = z)  H_counts, xedges, yedges = np.histogram2d(x, y, bins = [x_bins, y_bins])    print(H)  H1 = H/H_counts  print(H1)    plt.xlabel("x")  plt.ylabel("y")    plt.imshow(H1.T, origin='lower',  cmap='RdBu',              extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])  plt.colorbar().set_label('mean z', rotation=270)  

here's the plot for mean z

EDIT 2: When I use stats for standard deviation I get the following plot

std plot

The deep red bin on the top right is actually empty and has no z values so I want the standard deviation to be 'Nan' instead of being assigned a value of 0. How can I do that?

My code for this plot is:

from scipy import stats  import numpy as np  import matplotlib.pyplot as plt    x=np.array([10,2,4,12,3,6,8,14])  y=np.array([5,5,6,8,20,10,2,2])  z=np.array([4,6,10,40,22,14,20,8])    x_bins = np.linspace(0, 20, 3)  y_bins = np.linspace(0, 20, 3)    H, xedges, yedges = np.histogram2d(x, y, bins = [x_bins, y_bins], weights = z)    #mean = stats.binned_statistic_2d(x,y,z,statistic='',bins=[x_bins,y_bins])  #mean.statistic  std = stats.binned_statistic_2d(x,y,z,statistic='std',bins=[x_bins,y_bins])  #std.statistic  #print(std.statistic)  plt.xlabel("x")  plt.ylabel("y")  plt.imshow(std.statistic.T, origin='lower',  cmap='RdBu',              extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])  #plt.clim(0, 20)  plt.colorbar().set_label('std z', rotation=270)  

function for change the image using keyboard arrow key

Posted: 01 Sep 2021 08:03 AM PDT

I have a gallery of images, I need to change the image when the user will press the arrow keys after the modal popup.

left arrow to change the image to the left and the right arrow for right. I'm pretty new to JavaScript so I couldn't understand what function should I use to change the images to left and right.

This is what I have tried so far:

document.addEventListener('keydown', function(e) {    switch (e.keyCode) {      case 37:        alert('left');        break;      case 39:        alert('right');        break;    }  });
.modal {    width: 58%;    height: 100%;    top: 0;    position: fixed;    display: none;    background-color: rgba(22, 22, 22, 0.5);    margin-left: 300px;    max-width: 779px;    min-width: 779px;  }    .modal-content {    margin: auto;    display: block;    width: 80%;    max-width: 700px;  }    .mySlides {    display: none;  }    .mySlides {    display: none;  }    .cursor {    cursor: pointer;  }    .cursor {    cursor: pointer;  }    .prev {    cursor: pointer;    position: relative;    top: -149px;    padding: 16px;    margin-top: -50px;    color: white;    font-weight: bold;    font-size: 20px;    border-radius: 0 3px 3px 0;    user-select: none;    -webkit-user-select: none;    left: -10%;  }    .next {    cursor: pointer;    position: relative;    top: -149px;    padding: 16px;    margin-top: -50px;    color: white;    font-weight: bold;    font-size: 20px;    border-radius: 0 3px 3px 0;    user-select: none;    -webkit-user-select: none;    left: 600px;  }
<div class="main-container">    <div class="row">      <div class="column">        <p align="center"><img src="https://source.unsplash.com/collection/190727/300x200" width="250" height="164" onclick="openModal();currentSlide(1)" class="hover-shadow cursor"></p>      </div>      <div class="column">        <p align="center"><img src="https://source.unsplash.com/collection/190727/300x210" width="250" height="164" onclick="openModal();currentSlide(2)" class="hover-shadow cursor"></p>      </div>      <div id="myModal" class="modal">        <div class="modal-content">          <span class="close cursor" onclick="closeModal()">&times;</span>          <div class="mySlides">            <img src="https://source.unsplash.com/collection/190727/300x200" style="width: 98%;      position: relative;      left: 10px;      top: 109px;">          </div>          <div class="mySlides">            <img src="https://source.unsplash.com/collection/190727/300x210" style="width: 98%;      position: relative;      left: 10px;      top: 109px;">          </div>          <a class="prev" id="prev1" onclick="plusSlides(-1)">&#10094;</a>          <a class="next" onclick="plusSlides(1)">&#10095;</a>        </div>

getPackageName() in Fragment

Posted: 01 Sep 2021 08:03 AM PDT

I was using this method to resize markers in a Google Maps activity:

public Bitmap resizeMapIcons(String iconName,int width, int height){      Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(),getResources().getIdentifier(iconName, "drawable", getPackageName()));      Bitmap resizedBitmap = Bitmap.createScaledBitmap(imageBitmap, width, height, false);      return resizedBitmap;  }  

Now I wanted to use it in a fragment with MapView, but I get the error "error: cannot find symbol method getPackageName()". What could be the problem?

How does this piece of obfuscated Haskell code work?

Posted: 01 Sep 2021 08:03 AM PDT

While reading https://en.uncyclopedia.co/wiki/Haskell (and ignoring all the "offensive" stuff), I stumbled upon the following piece of obfuscated code:

fix$(<$>)<$>(:)<*>((<$>((:[{- thor's mother -}])<$>))(=<<)<$>(*)<$>(*2))$1  

When I run that piece of code in ghci (after importing Data.Function and Control.Applicative), ghci prints the list of all powers of 2.

How does this piece of code work?

No comments:

Post a Comment