Tuesday, July 13, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Apache NiFi NTLM Authentication 401

Posted: 13 Jul 2021 08:13 AM PDT

I'm having troubles authenticating NiFi to a SOAP WebService, using a NTLM Authentication.

I've using this custom processor: https://github.com/peetkes/nifi-http-processor

I've created a simple flow, with a FlowFile that contains the XML request, passed to the CustomInvokeHTTP Processor.

The problem is that I obtain "Error 401 Unauthorized".

I tried to use the same credentials with SOAPUI and they work.

I attach the flow and the processor properties.

flow

properties1

properties2

properties3

Is there something else I can try? I don't really know what to do.

Thank you so much!

Run-time error '13': type mismatch when using if statement

Posted: 13 Jul 2021 08:12 AM PDT

I'm trying to configure autofilters bottom X items for Spain to be different then other territories and I'm getting Run-time error'13': Type mismatch

Sub Only_Choose_Unders()  ' Only_Choose_Unders Macro   If [Lab UP no 360 Chem OPP!D2] Like "1A. Madrid" Or "1B. Madrid" Or "2A. Barcelona" Or "2B. Barcelona" Or "3. Valencia" Or "4A. Malaga" Or "4B. Sevilla" Or "5. Bilbao" Or "6. Canarias" Or "7. Baleares" Or "8. NorOeste" Then      With Sheets("Lab UP no 360 Chem OPP").Range("k24:k5000")          .AutoFilter Field:=8, Criteria1:="50", _           Operator:=xlBottom10Items           .AutoFilter Field:=9, Criteria1:="50", _           Operator:=xlBottom10Items      End With  Else      With Sheets("Lab UP no 360 Chem OPP").Range("k24:k5000")          .AutoFilter Field:=8, Criteria1:="10", _          Operator:=xlBottom10Items          .AutoFilter Field:=9, Criteria1:="10", _          Operator:=xlBottom10Items      End With  End If  End Sub  

Random.choice() in a While True loop:

Posted: 13 Jul 2021 08:12 AM PDT

I am working on a text dungeon crawler game using python, and using random.choice() in a while true loop until the monster is dead... how do i make it choose a different move every time it reads the line through the loop and not constantly the same move over and over again?(while true loop is in the function but isn't properly set on here)

import random, math, sys, os, os.path, time    #Variables  #These Variables are For the pLayeer health and shield  PlayerHealthPoints = 200  #These Variables are for the Player's Move DMG  Slash = 3.1  Dash = 2.5  Slam = 5    var = [Slash,Dash,Slam]    #These Variables are the Mob 1 Health and Damage  Monster_One_Damage = 5  Monster_One_Health = 10    def Level_One():      global Monster_One_Health, PlayerHealthPoints  while True:          Move_Chooser = random.choice(var)            Monster_One_Health = Monster_One_Health - Move_Chooser          if Move_Chooser == Slash:              print("Player Has Used Dash Attack")              print("Monster[1] has taken 2.5 Hearts of DMG")              time.sleep(2)              print(Monster_One_Health, "HP Remaining")                if Monster_One_Health <= 0:                  print("Monster[1] Has been Defeated!")                  print("Monster[1]: How did you defeat me ? haha maybe I have lost but the other")                  break            elif Move_Chooser == Dash:              print("Player has used Slash Attack")              print("Monster[1] has taken 3.1 Hearts of DMG")              time.sleep(2)              print(Monster_One_Health, "HP Remaining")                            if Monster_One_Health <= 0:                  print("Monster[1] Has been Defeated!")                  print(                      "Monster[1]: How did you defeat me ? haha maybe I have lost but the others will take you out")                  break                    elif Move_Chooser == Slam:              print("Player has used Slam Attack")              print("Monster[1] has taken 5 Hearts of DMG")              time.sleep(2)              print(Monster_One_Health, "HP Remaining")                if Monster_One_Health <= 0:                  print("Monster[1] Has been Defeated!")                  print("Monster[1]: How did you defeat me ? haha maybe I have lost but the others will take you out")                  break            PlayerHealthPoints = PlayerHealthPoints - Monster_One_Damage            print("Monster[1] has used slap attack!, The Player has lost 5 HP!",PlayerHealthPoints)          if PlayerHealthPoints < 100:              print("Shield has BROKEN! Player has less than 100HP remaining")            elif PlayerHealthPoints <= 0:              print("Player Has been Defeated!")              exit()  

Streaming media to files in AWS S3

Posted: 13 Jul 2021 08:12 AM PDT

My problem:

I want to stream media I record on the client (typescript code) to my AWS storage (services like YouTube / Twitch / Zoom / Google Meet can live record and save the record to their cloud. Some of them even have host-failure tolerance and create a file if the host has disconnected). I want each stream to have a different file name so future triggers will be available from it.

I tried to save the stream into S3, but maybe there are more recommended storage solutions for my problems.

What services I tried:

  1. S3: I tried to stream directly into S3 but it doesn't really support updating files. I tried multi-part files but they are not host-failure tolerance. I tried to upload each part and have a lambda to merge it (yes, it is very dirty and consuming) but I sometimes had ordering problems.
  2. Kinesis-Video: I tried to use kinesis-video but couldn't enable the saving feature with the SDK. By hand, I saw it saved a new file after a period of time or after a size was reached so maybe it is not my wanted solution.
  3. Amazon IVS: I tried it because Twitch recommended this although it is way over my requirements. I couldn't find an example of what I want to do in code with SDK (only by hand examples).

Questions

  1. Do I look at the right services?
  2. What can I do with the AWS-SDK to make it work?
  3. Is there a good place with code examples for future problems? Or maybe a way to search for solutions?

Thank you for your help.

Installing laravel jetstream with php version 7.2

Posted: 13 Jul 2021 08:12 AM PDT

I am currently deploying my app in laravel to cpanel for shared hosting. Laravel jetstream is one of the vital packages that I use for my application. I know that jetstream requires a minimum php version of 7.3 however the server I am using for cpanel is currently running php version 7.2.34. I have tried the following piece of code in command line to ignore the php version:

$composer require laravel/jetstream --ignore-platform-reqs  

However I get the following response:

Using version ^2.3 for laravel/jetstream  ./composer.json has been updated  Running composer update laravel/jetstream  Loading composer repositories with package information  Updating dependencies    Problem 1      - laravel/jetstream[v2.3.0, ..., 2.x-dev] require illuminate/support ^8.0 -> found illuminate/support[v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.      - Root composer.json requires laravel/jetstream ^2.3 -> satisfiable by laravel/jetstream[v2.3.0, ..., 2.x-dev].      Installation failed, reverting ./composer.json and ./composer.lock to their original content.    

Any idea on how I can make this install work. Any help is greatly appreciated.

Xtext CustomScopeProvider Problems with adding candidates

Posted: 13 Jul 2021 08:12 AM PDT

I am working on an xtext Project where I have to customize the Scope Provider. I need to add up some possible candidates for the scope. The first part (getServiceInputs()) works fine but for the second one (addAll(sub.GetSubRecipeParameters()) not. Debugging showed that they get removed from its original source (sub) and can therefore not be retrieved again. When simply commenting out the addAll line the SubRecipeParameters remain in sub. Really dont know how to solve that, tried already some work arounds. Anyone with an Idea?

public class AutomationServiceDslScopeProvider extends AbstractAutomationServiceDslScopeProvider {        @Override      public IScope getScope(EObject context, EReference reference) {          if (context instanceof ServiceInvocationParameter                  && reference == AutomationServiceDslPackage.Literals.LITERAL) {                  ServiceInvocation serviceCall = (ServiceInvocation) invocationParameter.eContainer();                  ServiceDefinition calledService = serviceCall.getService();                  List<ServiceParameterDefinition> candidates= calledService.getServiceInputs();                  final EObject rootContainer = EcoreUtil.getRootContainer(context);                  List<SubRecipeDefinition> subs = EcoreUtil2.getAllContentsOfType(rootContainer, SubRecipeDefinition.class);                  for(SubRecipeDefinition sub:subs) {                      for(RecipeStep step:sub.getRecipeSteps()) {                          if(step.getName()==serviceCall.getName()) {                              candidates.addAll(sub.getSubRecipeParameters());                              }                      }                                                              }                                    return Scopes.scopeFor(candidates);  

Thanks for any help!!

Flutter - app-debug.apk is getting uploaded in github

Posted: 13 Jul 2021 08:12 AM PDT

I'm getting the following warnings every time I make a push to my git repo

remote: warning: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.  remote: warning: See http://git.io/iEPt8g for more information.  remote: warning: File build/app/outputs/flutter-apk/app-debug.apk is 63.00 MB; this is larger than GitHub's recommended maximum file size of 50.00   MB  

These are from my .gitignore file

# Flutter/Dart/Pub related  **/doc/api/  **/ios/Flutter/.last_build_id  .dart_tool/  .flutter-plugins  .flutter-plugins-dependencies  .packages  .pub-cache/  .pub/  /build/  

Additionally I've added the following line to get through the situation

build/app/outputs/flutter-apk/app-debug.apk  

Everything seems fine, yet app-debug.apk is getting pushed every time. How to solve this issue?

How to create values on new colum based on other columns?

Posted: 13 Jul 2021 08:12 AM PDT

my data

test = structure(list(id = c("903816", "903818", "903818", "903818",   "903841", "904904", "903868", "903818", "903026", "903841"),       value = c(76, 220, 179, 175, 81.2, 1.66, 115.1, 169.3, 7.34,       72), status = c("", "", "", "", "", "", "", "", "",       "")), row.names = c(NA, -10L), class = "data.frame")  

I require to run some numeric validations based on the value colum (i now have up to 2 conditions based on the same value column but i plan to add more conditions and more columns to validate). With the code i currently have, the next ifelse will delete ("") what i have done before because im not sure on how to not do anything on the NO portion of the ifelse

test$status = ifelse( (test$id== "903816") & (test$value <= 30) ,                                     'VALID',                                     ifelse(test$id == "903816",                                            'INVALID' ,                                            ''))    test$status = ifelse( (test$id== "903818") & (test$value > 200) ,                                   'VALID',                                   ifelse(test$id == "903818",                                          'INVALID' ,                                          ''))    test$status = ifelse( (test$id== "903841") & (test$value > 70) & (test$value < 85) ,                         'VALID',                         ifelse(test$id == "903841",                                'INVALID' ,                                ''))    test$status = ifelse( (test$id== "904904") & (test$value > 1)  ,                         'VALID',                         ifelse(test$id == "904904",                                'INVALID' ,                                ''))    test$status = ifelse( (test$id== "903868") & (test$value < 150)  ,                         'VALID',                         ifelse(test$id == "903868",                                'INVALID' ,                                ''))    test$status = ifelse( (test$id== "903026") & (test$value < 8)  ,                         'VALID',                         ifelse(test$id == "903026",                                'INVALID' ,                                ''))  

I want to change passed rate in allure report

Posted: 13 Jul 2021 08:12 AM PDT

In my opinion, total executed testcases should not include skipped testcases. so I want to know how to change testcase passed rate to passed/(passed+failed+broken).

Unable to get property 'textContent' of undefined or null reference in IE11 and Edge

Posted: 13 Jul 2021 08:13 AM PDT

function MainfillTable(table, srcs) {

var cols = 0  for (field in srcs)   {      srcs[cols] = field      cols++  }      var row  for (row = 0; row < srcs[srcs[0]].length; row++)   {      var tr = trtemplate.cloneNode(true)            var data Fields = new Array()      var elements = tr.getElementsByTagName('*')            for (var i = 0; i < elements.length; i++)      {          var element = elements[i]          if (element.hasAttribute('data'))          {              var dataFieldName = element.getAttribute('data')                var dataFieldValue = srcs[dataFieldName][row].textContent                if (element.tagName.toLowerCase() == 'div')                  element.innerHTML = dataFieldValue              else if (element.tagName.toLowerCase() == 'input')                  element.value = dataFieldValue                }        }  

}

Getting Issue in Line (var dataFieldValue = srcs[dataFieldName][row].textContent) as

IE11 - Unable to get property 'textContent' of undefined or null reference  Edge - Cannot read property 'textContent' of undefined  

Can anyone please help what is breaking the code?

Issue testing with jest

Posted: 13 Jul 2021 08:12 AM PDT

I'm struggling to test this code with Jest, but I don't have ideas how should I do this, maybe someone with Jest experience can help me with this. I have the following implementation:

import config from "config-loader";  import parse from "csv-parse/lib/sync";  import { logger } from "logger";    import { readFromBlob } from "../modules/blobStorage";  import pgpDecrypt from "../modules/pgp/decryptPGP";    const readFile = async () => {    const blobFile = await readFromBlob(file);      try {      const psvFile = await pgpDecrypt(blobFile);        const document = parse(psvFile, {        delimiter: "|",        columns: true,        trim: true,        skip_empty_lines: true,      });        return document;    } catch (error) {      logger.error(`Error while reading document: ${error}`);    }  };    export default readFile;    

and my test so far:

import { logger } from "logger";  import { readFromBlob } from "../modules/blobStorage";  import pgpDecrypt from "../modules/pgp/decryptPGP";  import parse from "csv-parse/lib/sync";    import "./readConsentFile";    jest.mock("config-loader", () => ({    eventservice: {      topic: {        topicName: "topic",      },    },  }));    jest.mock("logger", () => ({    logger: { log: jest.fn() },  }));    jest.mock("../modules/blobStorage", () => ({    readFromBlob: jest.fn(),  }));    jest.mock("../modules/pgp/decryptPGP", () => ({    pgpDecrypt: jest.fn(),  }));    jest.mock("csv-parse/lib/sync", () => ({    parse: jest.fn(),  }));    describe("readConsentFile", () => {    it("should create a log error message if an error occurs while reading consent file", async () => {      pgpDecrypt.mockRejectedValue(new Error("error message"));      expect(logger.log).toHaveBeenCalledWith(        "error",        expect.stringContaining("error message")      );    });      it("should read consent file correctly", async () => {      const testFile = "69154253976359661361067302SCCRM";      const testRead = await readFromBlob(testFile);        expect(testRead).toBe();    });  });    

The first one is failing with this error: TypeError: _decryptPGP.default.mockRejectedValue is not a function. The second one is passing, but because it's incomplete and I don't know how I should write the expect in this case.

Stored procedure overdoes - inserting multiple tables

Posted: 13 Jul 2021 08:12 AM PDT

I expect below procedure to insert one row into the orders table, grab the PK then insert it into the orderlines table this PK with as many lines as many are in the datagridview on the form, then update the stock table with the quantity and finally insert 1 row into the payments table. Unfortunately it inserts as many rows to all 3 tables as many rows are in the datagridview. Is there a way to achieve my goal preferably without braking it down into more procedures?

CREATE PROCEDURE spNewSale      @customer INT, -- passed from a comboBox      @staff VARCHAR(12), -- the user logged in      @product INT, -- passed from a comboBox      @quantity INT -- passed from a textBox  AS  BEGIN      SET NOCOUNT ON;        INSERT INTO orders (order_cust_id, order_staff_id, order_date) -- order_id (PK) = identity autoincremented      VALUES (@customer,               (SELECT logons.logon_st_id FROM logons                WHERE logons.logon_name = @staff), CURRENT_TIMESTAMP);        DECLARE @ordernbr INT = SCOPE_IDENTITY();        INSERT INTO orderlines (ol_order_id, ol_pro_id, ol_qty, ol_value) -- ol_id (PK) = identity autoincremented      VALUES (@ordernbr, @product, @quantity,               @quantity * (SELECT products.pro_price                            FROM products WHERE pro_id = @product));        UPDATE products       SET pro_stock = (pro_stock - @quantity)        WHERE pro_id = @product;        INSERT INTO payments (paym_order_id, paym_amount, paym_taken_by, paym_date) -- paym_id (PK) = identity autoincremented      VALUES (@ordernbr,               (SELECT SUM(orderlines.ol_value) AS paym_amount                FROM orderlines WHERE orderlines.ol_order_id = @ordernbr),              (SELECT logons.logon_st_id FROM logons                WHERE logons.logon_name = @staff), CURRENT_TIMESTAMP)  END  

Error happening due to string's length limit?

Posted: 13 Jul 2021 08:12 AM PDT

for(int i=1;i<=50;i++)        {          s+=to_string(i)+s;       }  

this code's giving error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc" can someone explain why ??

autossh works when started directly from a shell, but not in a service

Posted: 13 Jul 2021 08:13 AM PDT

I am trying to set up a service for autossh on Ubuntu 18.04. When I start autossh directly from my shell, the tunnel works (I can connect from my server to my local pc), but when it is started from the service, I get some "Permission denied" error.

Anybody can help ?

This works:

jul@narwhal:~$ /usr/bin/autossh -M 0 -N ***@*** -R 2222:localhost:22 -o "ServerAliveInterval 300" -o "ServerAliveCountMax 3" -i /home/jul/.ssh/autossh_id_rsa  

but when I start this service with the same command and user:

[Unit]  Description=AutoSSH tunnel service to ovh vps  After=network.target    [Service]  User=jul  Environment="AUTOSSH_GATETIME=0"  ExecStart=/usr/bin/autossh -M 0 -N ***@*** -R 2222:localhost:22 -o "ServerAliveInterval 300" -o "ServerAliveCountMax 3" -i /home/jul/.ssh/autossh_id_rsa    [Install]  WantedBy=multi-user.target  

I get

(base) jul@narwhal:~$ sudo systemctl status autossh-tunnel.service   [sudo] password for jul:   ● autossh-tunnel.service - AutoSSH tunnel service to ovh vps     Loaded: loaded (/etc/systemd/system/autossh-tunnel.service; enabled; vendor preset: enabled)     Active: active (running) since Tue 2021-07-13 16:43:06 CEST; 5min ago   Main PID: 32649 (autossh)      Tasks: 1 (limit: 4915)     CGroup: /system.slice/autossh-tunnel.service             └─32649 /usr/lib/autossh/autossh -M 0 -N ***@*** -R 2222:localhost:22 -o ServerAliveInterval 300 -o ServerAliveCountMax 3 -i /home/jul/.ssh/autossh_id_rsa    juil. 13 16:46:11 narwhal autossh[32649]: Permission denied, please try again.  juil. 13 16:46:11 narwhal autossh[32649]: Permission denied, please try again.  juil. 13 16:46:11 narwhal autossh[32649]: ***@***: Permission denied (publickey,password).  juil. 13 16:46:11 narwhal autossh[32649]: ssh exited with error status 255; restarting ssh  

Here's what's running:

jul@narwhal:~$ ps aux | grep autossh  jul      32649  0.0  0.0   4532  1816 ?        Ss   16:43   0:00 /usr/lib/autossh/autossh -M 0 -N ***@*** -R 2222:localhost:22 -o ServerAliveInterval 300 -o ServerAliveCountMax 3 -i /home/jul/.ssh/autossh_id_rsa  

Adding a new line in the table with Angular

Posted: 13 Jul 2021 08:12 AM PDT

So I am trying to add a new line in a table which is populated from an API but it looks that I miss something. Here is my code:

HTML:

    <button mat-flat-button color="primary" class="btn-add"  (click)="addRow()" [disabled] = "isLoading">ADD</button>    <table mat-table [dataSource]="dataSource" class="mat-elevation-z2" *ngIf="show">          <!-- Position Column -->          <ng-container *ngFor="let column of displayedColumns" [matColumnDef]="column">              <th mat-header-cell *matHeaderCellDef>{{column}}</th>              <td mat-cell *matCellDef="let element; index as i;">                  <span *ngIf="element.editing; then editBlock else displayBlock"></span>                  <ng-template #displayBlock>{{element[column]}}</ng-template>                  <ng-template #editBlock>                      <mat-form-field appearance="fill" >                          <input matInput [(ngModel)]="element[column]">                      </mat-form-field>                  </ng-template>              </td>          </ng-container>          <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>          <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>      </table>  

TS file:

  displayedColumns: string[] = [];    dataSource: any;      addRow() {      console.log("Adding new row");      let newRow = {        editing: true      };      this.displayedColumns.forEach(x => newRow[x]="");      this.dataSource.push(newRow);    }  

Scary errors in ancient code converting wstring to string

Posted: 13 Jul 2021 08:12 AM PDT

An old method contains code like the following (anonymised):

        std::wstring wstr = ...;          std::string str(wstr.begin(), wstr.end());  

Previously this all compiled without warnings but as we update to C++17 and VS2019 (v142) and tidy project settings, it now gives these big scary warnings:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29333\include\xstring(2468,23): warning C4244: 'argument': conversion from 'wchar_t' to 'const _Elem', possible loss of data          with          [              _Elem=char          ]  C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29333\include\xstring(2479): message : see reference to function template instantiation 'void std::basic_string<char,std::char_traits<char>,std::allocator<char>>::_Construct<wchar_t*>(_Iter,const _Iter,std::input_iterator_tag)' being compiled          with          [              _Iter=wchar_t *          ]  C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29333\include\xstring(2479): message : see reference to function template instantiation 'void std::basic_string<char,std::char_traits<char>,std::allocator<char>>::_Construct<wchar_t*>(_Iter,const _Iter,std::input_iterator_tag)' being compiled          with          [              _Iter=wchar_t *          ]  C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29333\include\xstring(2459): message : see reference to function template instantiation 'void std::basic_string<char,std::char_traits<char>,std::allocator<char>>::_Construct<wchar_t*>(const _Iter,const _Iter,std::forward_iterator_tag)' being compiled          with          [              _Iter=wchar_t *          ]  C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29333\include\xstring(2459): message : see reference to function template instantiation 'void std::basic_string<char,std::char_traits<char>,std::allocator<char>>::_Construct<wchar_t*>(const _Iter,const _Iter,std::forward_iterator_tag)' being compiled          with          [              _Iter=wchar_t *          ]    message : see reference to function template instantiation 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string<std::_String_iterator<std::_String_val<std::_Simple_types<_Elem>>>,0>(_Iter,_Iter,const _Alloc &)' being compiled          with          [              _Elem=wchar_t,              _Iter=std::_String_iterator<std::_String_val<std::_Simple_types<wchar_t>>>,              _Alloc=std::allocator<char>          ]  message : see reference to function template instantiation 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string<std::_String_iterator<std::_String_val<std::_Simple_types<_Elem>>>,0>(_Iter,_Iter,const _Alloc &)' being compiled          with          [              _Elem=wchar_t,              _Iter=std::_String_iterator<std::_String_val<std::_Simple_types<wchar_t>>>,              _Alloc=std::allocator<char>          ]  

I am pretty sure this code pre-dates use of UNICODE in our codebase - it seems to work but I don't really understand the warnings or what I should do about it.

I found this question: UTF8 to/from wide char conversion in STL but the nice neat solution has comments saying it's deprecated in C++17! It's somewhat a mystery why this code mixes string and wstring in the first place, is there an easy solution? Or is this a case "just leave it if it works?!"

Grouping strings in a list which have the same substing which is 4 letters in Python

Posted: 13 Jul 2021 08:12 AM PDT

This is an example list:

["cat" , "ccaatt" , "fish" , "ffish" , "dog", "doog" ,"bird" , "birdd".....]  

Exptected output should be like this:

mathcing sequences "fish" and "bird" both have 4 letters

[("fish","ffish") , ("bird","birdd") ....]  

How can I group RegEx correctly with '|'?

Posted: 13 Jul 2021 08:12 AM PDT

I want to match different RegEx to a string. For example

from os import listdir  from os.path import isfile, join  import os  import re    s = "rechnungsnr. 234342341"    re_nu = re.compile(r".?rechnung[s]*\s*nr[.]*[:]*\s*(\w*\d+[-.]?\d*)")    rn = re_nu.search(s)  rechnungsnr = (rn.groups())  print(rechnungsnr)  print(rn)  print(rn.group(1))  

This yields me the correct group (the number after the text):

('234342341',)  <re.Match object; span=(0, 22), match='rechnungsnr. 234342341'>  234342341  

However, if I expand the RegEx with '|' I get different results:

s = "rechnungsnr. 234342341"    re_nu = re.compile(r"rechnungs\s?nummer[:]*\s*(\w*\d+[-.]?\d*)|rechnung(?::*)(?:\s*)((?:\w*)(?:\d+)[-.]?(?:\d*))|.?rechnung[s]*\s*nr[.]*[:]*\s*(\w*\d+[-.]?\d*)|   \                      belegnummer(?::*)(?:\s*)((?:\w*)(?:\d+)[-.]?(?:\d*))|beleg(?:s*)[-.]?nr(?:.*)(?::*)(?:\s*)((?:\w*)(?:\d+)[-.]?(?:\d*))")    rn = re_nu.search(s)  rechnungsnr = (rn.groups())  print(rechnungsnr)  print(rn)  print(rn.group(1))  

As in I get 2 "none" groups before the number I want to extract:

(None, None, '234342341', None, None)  <re.Match object; span=(0, 22), match='rechnungsnr. 234342341'>  None  

How can I change the code such that the number is always the first group? The goal of the RegEx is to get the number after the string. The string can be any name for a invoice number (in German). For example the number could come after "rechnungsnummer" but also after "rechnungs nr." but also after "rechnungs nr:" and so on...

How to change csv to json array using javascript

Posted: 13 Jul 2021 08:12 AM PDT

I want to add an external CSV file into a JOSN Array in my JS Code.

I tried lots of codes, with no luck like this:

var map = {};  var rows = csv.split(/\n/g);  var keys = rows.shift().split(",");  rows.forEach(raw_row => {    var row = {};    var row_key;    var columns = raw_row.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);    columns.forEach((column, index) => {      var key = keys[index];      if (!key) return;      if (key === 'Name') {        row_key = column;        return;      }      if (key === "Coordinates") {        column = column.replace(/""/g, '"');        column = column.substring(1, column.length - 1);        column = column.replace(/([a-zA-Z_]+):/g, `"$1":`);        try {          column = JSON.parse(`{${column}}`);        } catch (e) {}      }        row[key] = column;    });    map[row_key] = row;  });  console.log(map);  

but I believe my expectation is something else, so I dont get what I want. could some one pleae help me to change this csv(file):

contry;fromNr;toNr;Type;cust_1;cust_2
US;0;100;wood;max;nuk
DE;100;500;metal;max;pal

into JSON Array:

[{    "country": "US",    "fromNr": 0,    "toNr": 100,    "Type": "wood",    "cust_1": "max",    "cust_2": "nuk"  }, {    "country": "DE",    "fromNr": 100,    "toNr": 500,    "Type": "metal",    "cust_1": "max"  }]  

How do I run a setup.py file without being in its directory?

Posted: 13 Jul 2021 08:12 AM PDT

To install a package that includes a setup.py file, usually you cd into the root directory where setup.py is located and then run the following:

python setup.py install  

Now my problem is that I'm building an addon for another application, and while I can install "normal" package via code with the following:

subprocess.run([sys.executable, "-m", "pip", "install", package])  

I also have to install a couple custom made packages, and if I try to do it like this:

subprocess.run([sys.executable, "-m", "/MSN-Point-Cloud-Completion-master/emd/setup.py", "install"])  

I get the following error: Error while finding module specification for 'MSN-Point-Cloud-Completion-master/emd/setup.py' (ModuleNotFoundError: No module named 'MSN-Point-Cloud-Completion-master/emd/setup')

What is annoying me is that if I manually cd into the directory and simply run python setup.py install from the cmd it works just fine.

So the problem seems to be passing the relative path to the setup.py file, but as I said, considering this is an addon I need to install that setup.py from code. Any solution?

tunning a POST request to reach Adobe PDF services, using Python and a REST API

Posted: 13 Jul 2021 08:13 AM PDT

I am trying to use Adobe PDF services throught a REST API requested using Python (image bellow), with the "EXPORT" option, since the "extract" option won't help with the very first objective of getting DOCX documents out of PDF ones.

Nevertheless :

I tried to work on the export service of the REST API. But have some struggles with that. My POST request seems good, but I struggle to get authentified by the service, and still don't.

import requests  import json  from requests.structures import CaseInsensitiveDict    URL = "https://cpf-ue1.adobe.io/ops/:create?respondWith=%257B%2522reltype%2522%253A%2520%2522http%253A%252F%252Fns.adobe.com%252Frel%252Fprimary%2522%257D"    headers = CaseInsensitiveDict()  headers["x-api-key"] = "17ea258cc8e14a2182be0eb35437ac05"  headers["Authorization"] = "Bearer MYREALLYLONGTOKENIGOT"  headers["Content-Type"] = "application/json"      myfile = {"file":open("absolute_path_to_the_pdf_file/input.pdf", "rb")}    j="""  {"contentAnalyzerRequests" : {    "cpf:engine": {      "repo:assetId": "urn:aaid:cpf:Service-26c7fda2890b44ad9a82714682e35888"    },    "cpf:inputs": {      "params": {        "cpf:inline": {          "targetFormat": "docx"        }      },      "documentIn": {        "dc:format": "application/pdf",        "cpf:location": "InputFile0"      }    },    "cpf:outputs": {      "documentOut": {        "dc:format": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",        "cpf:location": "output.docx"      }    }  }, "InputFile0":"C:/Users/user/Downloads/P_D_F/trs_pdf_file_copy.pdf"}"""    resp = requests.post(url=URL, headers=headers, json=json.dumps(j), files=myfile)  data = resp.json()          print('---- resp.text: ---')  print(resp.text)  print('---- resp.status_code: ---')  print(resp.status_code)  print('---- resp.headers: ---')  print(resp.headers)  
  • Error message : "Oath token is missing"

Indeed, I didn't mention the argument "auth" within the POST request. But isn't it what's mentionned here in the Export section : (https://documentcloud.adobe.com/document-services/index.html#post-extractPDF) (image bellow) where it was precised that the authorisation is done by the "Bearer Token"

I found this image while looking: enter image description here

which means I need to perform all the other steps. What do you think? Would you have any suggestions?

Thank you !

How to copy a date from one Excel sheet to another sheet with specific format?

Posted: 13 Jul 2021 08:12 AM PDT

I have an Excel sheet1 with dates at column L9 till L15. The dates must be saved to another sheet2 at column L3 till L9. I am using the formula:

=IF('Sheet1'!L10="","",TEXT('Sheet1'!L10;"yyyy-mm-dd"))    

While the JSON is being received from the backend, the last 2 digits of a long are removed

Posted: 13 Jul 2021 08:12 AM PDT

If I try to get an JSON response from a backend I wrote I get following response which is completely correct:

{    "status": "ok",    "get": {      "5b7e4b0b-fc98-4107-ab72-32577440e02e": {        "isUser": false,        "permissions": {          "play": true,          "disconnect": true,          "debug": false,          "color": false,          "leaderboard-collect-voice": true,          "view-bot-log": false,          "command-boobs": false,          "embed-builder": false,          "clear": false,          "admin": false,          "skip": true,          "w2g": true,          "pause": true,          "clear-queue": true,          "leaderboard": true,          "rank-self": true,          "rank-other": true,          "leaderboard-collect-text": true,          "queue": true,          "move-to-me": false        },        "id": 0      },      "d902f18f-95ad-432c-9ee9-27e63ff6fce1": {        "isUser": false,        "permissions": {          "play": false,          "disconnect": false,          "debug": false,          "color": false,          "leaderboard-collect-voice": false,          "view-bot-log": false,          "command-boobs": true,          "embed-builder": false,          "clear": false,          "admin": false,          "skip": false,          "w2g": false,          "pause": false,          "clear-queue": false,          "leaderboard": false,          "rank-self": false,          "rank-other": false,          "leaderboard-collect-text": false,          "queue": false,          "move-to-me": false        },        "id": 767965825293746217      }    }  }  

But it seems if Chrome tries to get the data it gets in the response from the server the correct data but in the preview and the JavaScript of the site gets an wrong value. I tried to change the value but nothing works. It seems that every time the last 2 digits are replaced by zeros.

correct value

wrong value

Application tried to present modal view controller on itself

Posted: 13 Jul 2021 08:13 AM PDT

let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)  if userSignedInGlobal == "success"{      if let mainTabController = storyboard.instantiateViewController(withIdentifier: "MainTabController") as?  MainTabController{          mainTabController.present(mainTabController, animated: true, completion: nil)      }  }  

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modal view controller on itself. Presenting controller is .'

I need to navigate to a page after Authenticating application with firebase to do so I use the above code after validating the authentication. How do I fix this an reference link or code explaining how to get there would suffice.

Flutter - Overlay card widget on a container

Posted: 13 Jul 2021 08:12 AM PDT

In flutter, is it possible to place a part of a card on another container? In CSS, we would set margin-top to a negative value or use translate property. In flutter as we cannot set negative values to margin-top, is there an alternative to that?

enter image description here

Pyspark : Cumulative Sum with reset condition

Posted: 13 Jul 2021 08:13 AM PDT

We have dataframe like below :

+------+--------------------+  | Flag |               value|  +------+--------------------+  |1     |5                   |  |1     |4                   |  |1     |3                   |  |1     |5                   |  |1     |6                   |  |1     |4                   |  |1     |7                   |  |1     |5                   |  |1     |2                   |  |1     |3                   |  |1     |2                   |  |1     |6                   |  |1     |9                   |        +------+--------------------+  

After normal cumsum we get this.

+------+--------------------+----------+  | Flag |               value|cumsum    |  +------+--------------------+----------+  |1     |5                   |5         |  |1     |4                   |9         |  |1     |3                   |12        |  |1     |5                   |17        |  |1     |6                   |23        |  |1     |4                   |27        |  |1     |7                   |34        |  |1     |5                   |39        |  |1     |2                   |41        |  |1     |3                   |44        |  |1     |2                   |46        |  |1     |6                   |52        |  |1     |9                   |61        |         +------+--------------------+----------+  

Now what we want is for cumsum to reset when specific condition is set for ex. when it crosses 20.

Below is expected output:

+------+--------------------+----------+---------+  | Flag |               value|cumsum    |expected |  +------+--------------------+----------+---------+  |1     |5                   |5         |5        |  |1     |4                   |9         |9        |  |1     |3                   |12        |12       |  |1     |5                   |17        |17       |  |1     |6                   |23        |23       |  |1     |4                   |27        |4        |  <-----reset   |1     |7                   |34        |11       |  |1     |5                   |39        |16       |  |1     |2                   |41        |18       |  |1     |3                   |44        |21       |  |1     |2                   |46        |2        |  <-----reset  |1     |6                   |52        |8        |  |1     |9                   |61        |17       |           +------+--------------------+----------+---------+  

This is how we are calculating the cumulative sum.

win_counter = Window.partitionBy("flag")    df_partitioned = df_partitioned.withColumn('cumsum',F.sum(F.col('value')).over(win_counter))  

How enable force global bucket access in aws s3 sdk java 2.0?

Posted: 13 Jul 2021 08:13 AM PDT

Here is a link to the documentation for java 3 sdk version 1. Does version 2.0 has something similar or they removed such option?

Wordpress shows 404 page when saving new post or editing post

Posted: 13 Jul 2021 08:12 AM PDT

Problem is ... when I click on edit post/edit page, it tries to open http://localhost/site/wp-admin/post-108.php?post=286&action=edit and ends up on 404 page. It also shows the 404 page when saving a new post/page.

I don't remember exactly what I did but it must have started after my IDE refactored the code when I was renaming a template file.

There is no post-108.php inside wp-admin folder or inside my theme folder, but there's post.php. I don't know why it is trying to open post-108.php which does not exist.

NOTE: It is a custom theme I am building myself using wordpress 4.7.4

Thank you all.

Angular 2.0 translate Pipe could not be found

Posted: 13 Jul 2021 08:12 AM PDT

I have a component that uses the translateService, but it's not possible to translate items with the pipe on the Component Template HTML, i get following error:

The pipe 'translate' could not be found

app.module.ts

import {BrowserModule} from "@angular/platform-browser";  import {NgModule} from "@angular/core";  import {HttpModule, Http} from "@angular/http";  import {TranslateModule, TranslateLoader, TranslateStaticLoader} from 'ng2-translate';  import {AppComponent} from "./app.component";    @NgModule({  declarations: [AppComponent],  imports: [  BrowserModule,  HttpModule,  TranslateModule.forRoot({      provide: TranslateLoader,      useFactory: (http: Http) => new TranslateStaticLoader(http, './assets/i18n', '.json'),      deps: [Http]     })  ],  bootstrap: [AppComponent]  })  export class AppModule {  }  

booking.component.ts

import {Component, OnInit} from '@angular/core';  import {BookingComponent} from './booking.component';  import {TranslateService} from 'ng2-translate';    @Component({     selector: 'app-booking',     templateUrl: './booking.component.html',     styleUrls: ['./booking.component.css']  })    export class BookingComponent implements OnInit {    constructor(private translate: TranslateService    ) {      translate.setDefaultLang('de');      translate.use('de');  };    ngOnInit() {  }  }  

booking.component.html

<p>{{'TESTKEY' | translate }}</p>  

The translation with the service on the component works fine, but i need to translate also the html with pipe

Custom select box onChange doesn't work

Posted: 13 Jul 2021 08:13 AM PDT

I am using custom select box script, but the problem is that when I change value, it does nothing (like in demo).

// Iterate over each select element  $('select').each(function () {      // Cache the number of options    var $this = $(this),        numberOfOptions = $(this).children('option').length;      // Hides the select element    $this.addClass('s-hidden');      // Wrap the select element in a div    $this.wrap('<div class="select"></div>');      // Insert a styled div to sit over the top of the hidden select element    $this.after('<div class="styledSelect"></div>');      // Cache the styled div    var $styledSelect = $this.next('div.styledSelect');      // Show the first select option in the styled div    $styledSelect.text($this.children('option').eq(0).text());      // Insert an unordered list after the styled div and also cache the list    var $list = $('<ul />', {      'class': 'options'    }).insertAfter($styledSelect);      // Insert a list item into the unordered list for each select option    for (var i = 0; i < numberOfOptions; i++) {      $('<li />', {        text: $this.children('option').eq(i).text(),        rel: $this.children('option').eq(i).val()      }).appendTo($list);    }      // Cache the list items    var $listItems = $list.children('li');      // Show the unordered list when the styled div is clicked (also hides it if the div is clicked again)    $styledSelect.click(function (e) {      e.stopPropagation();      $('div.styledSelect.active').each(function () {        $(this).removeClass('active').next('ul.options').hide();      });      $(this).toggleClass('active').next('ul.options').toggle();    });      // Hides the unordered list when a list item is clicked and updates the styled div to show the selected list item    // Updates the select element to have the value of the equivalent option    $listItems.click(function (e) {      e.stopPropagation();      $styledSelect.text($(this).text()).removeClass('active');      $this.val($(this).attr('rel'));      $list.hide();      /* alert($this.val()); Uncomment this for demonstration! */    });      // Hides the unordered list when clicking outside of it    $(document).click(function () {      $styledSelect.removeClass('active');      $list.hide();    });    });
body {    padding:50px;    background-color:white;  }  .s-hidden {    visibility:hidden;    padding-right:10px;  }  .select {    cursor:pointer;    display:inline-block;    position:relative;    font:normal 11px/22px Arial, Sans-Serif;    color:black;    border:1px solid #ccc;  }  .styledSelect {    position:absolute;    top:0;    right:0;    bottom:0;    left:0;    background-color:white;    padding:0 10px;    font-weight:bold;  }  .styledSelect:after {    content:"";    width:0;    height:0;    border:5px solid transparent;    border-color:black transparent transparent transparent;    position:absolute;    top:9px;    right:6px;  }  .styledSelect:active, .styledSelect.active {    background-color:#eee;  }  .options {    display:none;    position:absolute;    top:100%;    right:0;    left:0;    z-index:999;    margin:0 0;    padding:0 0;    list-style:none;    border:1px solid #ccc;    background-color:white;    -webkit-box-shadow:0 1px 2px rgba(0, 0, 0, 0.2);    -moz-box-shadow:0 1px 2px rgba(0, 0, 0, 0.2);    box-shadow:0 1px 2px rgba(0, 0, 0, 0.2);  }  .options li {    padding:0 6px;    margin:0 0;    padding:0 10px;  }  .options li:hover {    background-color:#39f;    color:white;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    <select id="selectbox1" onchange="alert('change')">    <option value="">Select an option&hellip;</option>    <option value="aye">Aye</option>    <option value="eh">Eh</option>    <option value="ooh">Ooh</option>    <option value="whoop">Whoop</option>  </select>  <select id="selectbox2">    <option value="">Month&hellip;</option>    <option value="january">January</option>    <option value="february">February</option>    <option value="march">March</option>    <option value="april">April</option>    <option value="may">May</option>    <option value="june">June</option>    <option value="july">July</option>    <option value="august">August</option>    <option value="september">September</option>    <option value="october">October</option>    <option value="november">November</option>    <option value="december">December</option>  </select>

http://www.jsfiddle.net/BB3JK/47

No comments:

Post a Comment