Tuesday, May 24, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Java Socket Client-Server Application

Posted: 24 May 2022 12:47 PM PDT

I have to create a client-server application where the client reads input as a string and sends the message to the server, then the server accepts the message, analyzes it(counts length, letters, numbers, digits, and whitespace), and adds those to global statistics. If the client messages a "." the server will send the global stats to the client and close and of course, the client will print the stats. If a normal message it will send the stats for the current entry and the client will print it out and close it. The issue I'm having is my code doesn't seem to run all the way through and I'm not getting my correct output. I'm very new to this so I don't know what I'm doing wrong. Can someone help?

import java.io.BufferedReader;  import java.io.DataOutputStream;  import java.io.InputStreamReader;  import java.net.Socket;    public class mueClient {  public static void main(String argv[]) throws Exception{      String userInput;      String currentStats;      String globalStats;      BufferedReader input = new BufferedReader(new InputStreamReader(System.in));            while (true){      //Creating the Socket and reading and writing methods          Socket clientSocket = new Socket("localhost", 8080);          BufferedReader fromTheServer = new BufferedReader(new           InputStreamReader(clientSocket.getInputStream()));          DataOutputStream toTheServer =new DataOutputStream(clientSocket.getOutputStream());                //Asking for user input      System.out.println("Input something. To finish, input '.' :\n");      userInput= input.readLine();      toTheServer.writeBytes(userInput);            //Printing of global stats or current stats      if (userInput.equals(".")) {          System.out.print("\nGlobal Statistics:");          globalStats=fromTheServer.readLine();          System.out.println(globalStats);          break;          }      else {          System.out.print("Current Statistics: ");          currentStats = fromTheServer.readLine();          System.out.println(currentStats);      }      System.out.print("Connection Ended...");      clientSocket.close();      }  }  }  

And here is my server code

import java.io.BufferedReader;  import java.io.DataOutputStream;  import java.io.InputStreamReader;  import java.net.ServerSocket;  import java.net.Socket;    public class mueServer {  public static void main(String argv[]) throws Exception{      String userInput;      String currentStats;      String globalStats;      int string_length= 0;   int global_string_length= 0;      int number_of_characters=0;      int global_number_of_characters= 0;      int number_of_digits= 0;    int global_number_of_digits= 0;      int number_of_whitespaces= 0;   int global_number_of_whitespaces= 0;      ServerSocket ss =new ServerSocket(8080);     while (true){      //SOCKET AND READ/WRITE METHODS      Socket cs=ss.accept();      BufferedReader fromTheClient = new BufferedReader(new       InputStreamReader(cs.getInputStream()));      DataOutputStream toTheClient =new DataOutputStream(cs.getOutputStream());      userInput = fromTheClient.readLine();        //CALCULATIONS      string_length=userInput.length();      global_string_length=global_string_length+string_length;      for (int i=0;i<string_length;i++) {          if (Character.isAlphabetic(userInput.charAt(i))) {              number_of_characters++;              global_number_of_characters++;}          if (Character.isDigit(userInput.charAt(i))) {              number_of_digits++;              global_number_of_digits++;}          if (Character.isWhitespace(userInput.charAt(i))) {              number_of_whitespaces++;              global_number_of_whitespaces++;}      }            //CURRENT STATS      currentStats=("Message Length = "+string_length+"; Characters = "+number_of_characters+"; Digits = "+number_of_digits+"; Whitespaces = "+number_of_whitespaces);      toTheClient.writeBytes(currentStats);      toTheClient.flush();      string_length= 0;      number_of_characters= 0;      number_of_digits= 0;      number_of_whitespaces= 0;                                  //GLOBAL STATS      if (userInput.equals(".")) {          //globalStats=("Message Length = "+ global_string_length +"; Characters = "+ global_number_of_characters +"; Digits = "+ global_number_of_digits +"; Whitespaces = "+ global_number_of_whitespaces);          toTheClient.writeBytes("Message Length = "+ global_string_length +"; Characters = "+ global_number_of_characters +"; Digits = "+ global_number_of_digits +"; Whitespaces = "+ global_number_of_whitespaces);          toTheClient.flush();          ss.close();          break;      }    }  }  }  

Dealing with multiple Azure Pipelines with multiple Environment targets

Posted: 24 May 2022 12:47 PM PDT

I'm trying to set up a pipelines template to streamline releases. We have numerous repos, and multiple team environments that need to utilize this. The release pipeline should look like this:

Build -> Dev Deploy -> Test Deploy -> UAT Deploy -> Prod Deploy

When the user manually runs the pipeline they should be allowed to specify which environment they are running for (ie: Team 1, Team 2; then the Dev Deploy step knows to use the Team 1 Dev environment for example). I first attempted to use a separate variable template that contained the environments in one spot. This does not work according to Azure Pipelines parameter value from variable template, other than allowing users to type a freeform string which is not ideal. The workarounds as far as I know are:

  1. Add the list of environments to every azure-pipelines.yml (not feasible as we have many repos and have environments changing frequently)
  2. Provide a freeform text box that the user can type in their environment (not a good solution as it allows typos and is generally just a bad user experience)

This is my current workaround, which "works" but is not ideal. UAT/Prod is not tied to a successful Test stage completion, because it would require all Test stages to succeed, and we typically will only deploy to the team's environment that is currently working on the repo. And since not all stages will always run, an app deployed to prod will still show the pipeline is still waiting on stages to run with the blue clock. Current workaround

- stage: DeployToTeam1Dev    displayName: Deploy to Team1 Dev    dependsOn:     - Build    jobs:    - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml      parameters:        environment: Team1 Dev        testRegion: true        siteName: ${{ parameters.siteName }}        virtualAppName: ${{ parameters.virtualAppName }}    - stage: DeployToTeam1Test    displayName: Deploy to Team1 Test (MIVA)    dependsOn:     - DeployToTeam1Dev    jobs:    - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml      parameters:        environment: Team1 Test        testRegion: true        siteName: ${{ parameters.siteName }}        virtualAppName: ${{ parameters.virtualAppName }}    - stage: DeployToTeam2Dev    displayName: Deploy to Team2 Dev    dependsOn:     - Build    jobs:    - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml      parameters:        environment: Team2 Dev        testRegion: true        siteName: ${{ parameters.siteName }}        virtualAppName: ${{ parameters.virtualAppName }}    - stage: DeployToTeam2Test    displayName: Deploy to Team2 Test (UAT)    dependsOn:     - DeployToTeam2Dev    jobs:    - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml      parameters:        environment: Team2 Test        testRegion: true        siteName: ${{ parameters.siteName }}        virtualAppName: ${{ parameters.virtualAppName }}    - stage: DeployToTeam3Dev    displayName: Deploy to Team3 Dev    dependsOn:     - Build    jobs:    - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml      parameters:        environment: Team3 Dev        testRegion: true        siteName: ${{ parameters.siteName }}        virtualAppName: ${{ parameters.virtualAppName }}    - stage: DeployToTeam3Test    displayName: (NYI) Deploy to Team3 Test    dependsOn:     - DeployToTeam3Dev    jobs:    - job: Team3TestDeploy      timeoutInMinutes: 10      pool:        vmImage: 'ubuntu-latest'      steps:      - bash: echo "Team3 Test does not currently exist. Skipping this stage"    - stage: DeployToTeam4Dev    displayName: Deploy to Team4 Dev    dependsOn:     - Build    jobs:    - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml      parameters:        environment: Team4 Dev        testRegion: true        siteName: ${{ parameters.siteName }}        virtualAppName: ${{ parameters.virtualAppName }}    - stage: DeployToTeam4Test    displayName: (NYI) Deploy to Team4 Test    dependsOn:     - DeployToTeam4Dev    jobs:    - job: Team4TestDeploy      timeoutInMinutes: 10      pool:        vmImage: 'ubuntu-latest'      steps:      - bash: echo "Team4 Test does not currently exist. Skipping this stage"      - stage: DeployToUAT    displayName: (NYI) Deploy to UAT    dependsOn:     - Build    jobs:    - job: UATDeploy      timeoutInMinutes: 10      pool:        vmImage: 'ubuntu-latest'      steps:      - bash: echo "UAT is not yet implement"      - stage: DeployToProd    displayName: Deploy to Prod    dependsOn:     - DeployToUAT    jobs:    - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml      parameters:        environment: Prod        testRegion: false        siteName: ${{ parameters.siteName }}        virtualAppName: ${{ parameters.virtualAppName }}  

Has anyone else ran in to a similar problem and come up with a solution besides hardcoding a list of environments in every azure-pipelines.yml? Thanks for the help in advance.

How can i fix this Indentation Error I cant seem to find?

Posted: 24 May 2022 12:47 PM PDT

I keep getting a indentation error when trying to add a blit to almost the end of this code, or trying to add anything, Ive been looking for the problem for over an hour but i can't seem to find it could somebody please have a look at it?

while True:      for event in pygame.event.get():          if event.type == pygame.QUIT:              pygame.quit()              sys.exit()                  if event.type == pygame.KEYDOWN:              if event.key == pygame.K_UP:                  speler_speed -= 6              if event.key == pygame.K_DOWN:                  speler_speed += 6          if event.type == pygame.KEYUP:              if event.key == pygame.K_UP:                  speler_speed += 6              if event.key == pygame.K_DOWN:                  speler_speed -= 6            bal_animatie()      player_animation()      computer_ai()      screen.fill(bg_color)      pygame.draw.rect(screen, wit, player)      pygame.draw.rect(screen, wit, computer)      pygame.draw.ellipse(screen, wit, ball)      pygame.draw.aaline(screen, wit, (screen_width /2, 0),(screen_width / 2, screen_height))      speler_text = font.render(f'{speler_score}',False,wit)      screen.blit(speler_text,(screen_width / 2 + 25, screen_height / 2 -15))      computer_text = font.render(f'{computer_score}',False,wit)      screen.blit(computer_text,(screen_width / 2 - 40, screen_height / 2 - 15))  

How to connect and disconnect a surfshark vpn server with python?

Posted: 24 May 2022 12:46 PM PDT

How to connect and disconnect a surfshark vpn server with python? How can I change the vpn location every minute?

Pandas how to count when string values converted to_numeric is greater than N?

Posted: 24 May 2022 12:46 PM PDT

I have monthly dataframe (df) that is already in min - max ranges like the below:

Wind      Jan       Feb           Nov         Dec      calib  West     0.1-25.5   2.8-65.3    1.3-61.3    0.9-35.3     50  North    0.2-28.3   3.1-66.4    1.0-67.7    1.9-40.1     60  South    0.3-29.5   2.5-49.4    1.9-63.4    0.3-33.0     60  East     20.5       1.1-41.1    0.9-40.3      nan        50  

I want to know the number of times the max wind speed was below the calib number each month. So I am trying to create a column Speed below calib (sbc) like below.

month_col = ['Jan', 'Feb', 'Nov', 'Dec']  df['sbc'] = (pd.to_numeric(df[month_col].str.extract(r"(?<=-)(\d+\.\d+)")) < df["calib"]).sum(axis=1)  

The above code is not working and I am getting the error AttributeError: 'DataFrame' object has no attribute 'str'. How would I fix this?

DirectoryInfo GetFiles without wildcard

Posted: 24 May 2022 12:46 PM PDT

DirectoryInfo source = new DirectoryInfo(src);  DirectoryInfo destination = new DirectoryInfo(dest);    FileInfo[] files = source.GetFiles("myfile.mp3);  

is using DirectoryInfo GetFiles without "*" in the parameter ok? This would just get 1 file everytime?

ElasticSearch: My analyzers aren't having an effect on sorting

Posted: 24 May 2022 12:46 PM PDT

I'm trying to use analyzers to return alphabetically sorted data, however my changes are always returned in lexographical order. I've tried multiple implementations from here and other sources to no avail. Is the issue in my tokenizer? Or possibly my use of custom analyzers i wrong? Thanks in advance

await client.indices.create({                  index: esIndexReport,                  body: {                      settings: {                          analysis: {                              filter: {                                  min_term_length: {                                      type: 'length',                                      min: 2,                                  },                              },                              analyzer: {                                  name_analyzer: {                                      tokenizer: 'whitespace',                                      filter: [                                          'lowercase',                                          'min_term_length',                                      ],                                  },                                  min_term_analyzer: {                                      tokenizer: 'standard',                                      filter: [                                          'lowercase',                                          'min_term_length',                                      ],                                  },                              },                          },                      },                      mappings: {                          report: {                              properties: {                                  reportId: {                                      type: 'text',                                      analyzer: 'min_term_analyzer',                                  },                                  reportName: {                                      type: 'text',                                      analyzer: 'name_analyzer',                                  },                                  description: {                                      type: 'text',                                      analyzer: 'name_analyzer',                                  },                                  author: {                                      type: 'text',                                      analyzer: 'min_term_analyzer',                                  },                                  icType: {                                      type: 'text',                                      analyzer: 'min_term_analyzer',                                  },                                  status: {                                      type: 'text',                                      analyzer: 'min_term_analyzer',                                  },                                  lastUpdatedAt: {                                      type: 'text',                                      analyzer: 'min_term_analyzer',                                  },                                  'sort.reportName': {                                      type: 'text',                                      fielddata: true,                                  },                                  'sort.description': {                                      type: 'text',                                      fielddata: true,                                  },                                  'sort.author': {                                      type: 'text',                                      fielddata: true,                                  },                                  'sort.status': {                                      type: 'text',                                      fielddata: true,                                  },                                  'sort.lastUpdatedAt': {                                      type: 'text',                                      fielddata: true,                                  },                              },                          },                      },                  },              });  

Is there a way to programmtically check via an API on that status of Google Workspace Apps?

Posted: 24 May 2022 12:46 PM PDT

Google has a Google Workspace Status Dashboard where they indicate whether any of their core services are experiencing an outage or not.

Accordingly, I would like to be able to fetch the status for a particular service. For example, I would like to check whether Gmail has one of the following statuses:

  • Available
  • Service disruption
  • Service outage

I would like to make an API call in Python that would retrieve the status and allow me to perform an action according to the current status.

Is there a way I can achieve this?

Is there a way to display the first two results of each unique id?

Posted: 24 May 2022 12:46 PM PDT

I have a list of ids that have different number of instances when running a query. I want to figure out a way to limit those instances to just two for each id. For example:

If my initial query results are: A 1 B 1 B 2 C 1 C 2 C 3 D 1 D 2 D 3 D 4

I want to modify the script so the query results look like:

A 1 B 1 B 2 C 1 C 2 D 1 D 2

Any help would be great!

When executing pytest from the root of the project, ModuleNotFoundError: No module name 'main'

Posted: 24 May 2022 12:46 PM PDT

When I execute pytest from the root of the project in the cmd py -m pytest py_src/. I get the following error: ModuleNotFoundError: No module named 'main'. However if I cd into py_src/ and then run py -m pytest everything behaves accordingly. I am still relatively new with pytest, anything would be appreciated to direct me in the right direction.

What I am trying to achieve is to create a .yml file from the root of the project that will run the pytest and other tests in other directories.

here is what my file structure looks like.

root  |  |---py_src  |    |  |    |---tests  |    |    |  |    |    |---test_x.py  

in my tests.py file, I have

from main import app  

What are True,False and NULL in R functions and How can I character be converted To it?

Posted: 24 May 2022 12:46 PM PDT

I am writing a shiny app and some options in function are NULL, TRUE and FALSE

example:

Dimplot(object, label = True, Repel = False, cols = NULL)  

How can I make sure that character is converted to NULL or False from text input. I am using right now a series of if, else if but find so many combinations is tedious is there a simple so

Dimplot(object, label = True, Repel = input$repel, cols = NULL)  

works for me.

how to crop image to text bound using python

Posted: 24 May 2022 12:46 PM PDT

how to remove background color if present in the scanned image.and crop image based on text boundries using python. i have tried by converting image to grayscale but it didnt worked. please check below images. enter image description here enter image description here

How to get geolocation data on mobile browser in a react application at development environment?

Posted: 24 May 2022 12:46 PM PDT

I'm trying to test a React application which uses Geolocation API on my mobile browser. I'm having trouble obtaining the geolocation data, I have read that it only works on HTTPS URLs. I would like to know if there is a way to test my code in development, since I'm using my computer IP which is a HTTP URL, to access my application on my mobile browser.

Write a function to add key-value pairs

Posted: 24 May 2022 12:47 PM PDT

I'd like to write a function that will take one argument (a text file) to use its contents as keys and assign values to the keys. But I'd like the keys to go from 1 to n: {'A': 1, 'B': 2, 'C': 3, 'D': 4... }.

I tried to write something like this:

Base code which kind of works:

filename = 'words.txt'    with open(filename, 'r') as f:      text = f.read()    ready_text = text.split()    def create_dict(lst):      """ go through the arg, stores items in it as keys in a dict"""      dictionary = dict()      for item in lst:              if item not in dictionary:                  dictionary[item] = 1              else:                  dictionary[item] += 1      return dictionary    print(create_dict(ready_text))  

The output: {'A': 1, 'B': 1, 'C': 1, 'D': 1... }.

Attempt to make the thing work:

def create_dict(lst):      """ go through the arg, stores items in it as keys in a dict"""      dictionary = dict()      values = list(range(100)) # values      for item in lst:              if item not in dictionary:                  for value in values:                      dictionary[item] = values[value]              else:                  dictionary[item] = values[value]      return dictionary  

The output: {'A': 99, 'B': 99, 'C': 99, 'D': 99... }.

My attempt doesn't work. It gives all the keys 99 as their value.

Bonus question: How can I optimaze my code and make it look more elegant/cleaner?

Thank you in advance.

('float' object cannot be interpreted as an integer) problem is there another built-in function I could possibly use instead of linspace for plotting

Posted: 24 May 2022 12:46 PM PDT

This is my code:

import numpy as np  import matplotlib.pyplot as plt  

The problem lies here as i would like to plot the points from -0.4 to 0.8 in increments of 0.01 as there is an important part of the graph that im missing which happens after x = 0.6

x = np.linspace(-0.4,1,0.01)  y = np.sqrt(((47.9-72*x)/5))    plt.figure(figsize = (10,10))  plt.plot(x,y,label = "k", linestyle = "-", color = 'Blue')    plt.xlabel("delta ($\Delta$) [m]")  plt.ylabel("Vc [m/s] ") #Velocity after it passes point C   plt.title("TITLE")  plt.xlim([-0.4, 1])  plt.ylim([0,4.0])  plt.legend()  plt.grid()  plt.show()  

Create a buffer zone around a point of a shapefile which starts at a specific distance from point

Posted: 24 May 2022 12:46 PM PDT

I have a shapefile containing a few thousands of points. My goal is to create a buffer zone around each point which starts at a radius of 3 meters away of each point and ends at a radius of 15 meters.

I usually create buffer zones with st_buffer (sf package), however if I use st_buffer(df, 15) the area in the 3m circle around the point is also included.

I now created two different buffer zones for each point consisting of a 3 meter and a 15 meter radius. My idea was to bind them to together into one data frame containing each points ID and the the two buffer zones. However I am missing a function which could exclude the overlapping areas of each points buffer zones, without excluding the areas of overlapping buffer zones from different points. Does anyone have an idea?

Thanks for the help in this matter.

Write a program using Java programming language that asks the user to enter a string of characters [closed]

Posted: 24 May 2022 12:47 PM PDT

My assignment:

Write a program using Java programming language that asks the user to enter a string of characters, key and the option of processing which is 1 for encryption and 2 for decryption, and the program should encrypt the string with the key using ceaser cipher to obtain the cipher text or decrypt the cipher text to obtain the plain text based on the user choice.

I am getting type String is not a subtype of type int in my flutter project

Posted: 24 May 2022 12:46 PM PDT

I downloaded a flutter project and tried to run it, but I get this error

type 'String' is not a subtype of type 'int'  

And the error is pointing me the this code

int? identified = _allBackEnds.getUser(IDENTIFIED);  

IDENTIFIED is defined in a file called strings.dart like this

const IDENTIFIED = "identified";

as well as other strings such as

const FIRST_NAME = "firstName";  const LAST_NAME = "lastName";  

I notice the problem causing the error is because IDENTIFIED is a string.

What I don't understand is, in the same file where there is an error there are other variables like this

   String fName = _allBackEnds.getUser(FIRST_NAME);     String lName = _allBackEnds.getUser(LAST_NAME);  

And they all return data in a text widget

  Text(      fName.capitalize()! + " " + lName.capitalize()!,    ),   

So I don't understand how the string is been used to return data and why I am getting an error

PS - This might sound confusing, and I hope you understand the question

"The method 'SplashScreen' isn't defined for the type 'MyApp'.". I have tried a lot of things and nothing. Any solution?

Posted: 24 May 2022 12:47 PM PDT

main.dart:

import 'package:flutter/material.dart' show BuildContext, Colors, MaterialApp, StatelessWidget, ThemeData, VisualDensity, Widget, runApp;    void main() {    runApp(MyApp());  }    class MyApp extends StatelessWidget {    // This widget is the root of your application.      Widget build(BuildContext context) {      return MaterialApp(          debugShowCheckedModeBanner: false,          // Application name          title: 'UranteX',          theme: ThemeData(            primarySwatch: Colors.red,            visualDensity: VisualDensity.adaptivePlatformDensity,          ),          home: SplashScreen());    }  

splashScreen.dart(2nd page)

import 'package:flutter/material.dart' show BuildContext, Center, Column, Container, CrossAxisAlignment, Image, MainAxisAlignment, Scaffold, SizedBox, State, StatefulWidget, Widget;    class SplashScreen extends StatefulWidget {    @override    _SplashScreenState createState() => _SplashScreenState();  }    class _SplashScreenState extends State<SplashScreen> {    @override    Widget build(BuildContext context) {      return Scaffold(        body: Container(          height: double.infinity,          width: double.infinity,          child: Center(            child: Column(crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [              SizedBox(                height: 300.0,                child: Image.asset('Images/logo.png'),              )            ]),          ),        ),      );    }  }  

///The code isn't working and its saying that"The method 'SplashScreen' isn't defined for the type 'MyApp'". I know the solution probably is on the "Container" but I can't solve it.

Dynamically Binding parameters to push to SQL Server

Posted: 24 May 2022 12:46 PM PDT

I have a lot of historical data I'm pushing to SQL. As a stop gap I'm coding this in VBA first. I open the .xlsx file, put the headers into an array to determine what SQL table the data goes into. Then I'm using solution #3 from INSERT INTO statement from Excel to SQL Server Table using VBA to base my SQL string on. I'm throwing an automation error at the .parameters.append line. Is there another way to dynamically append the parameters? Or is this just incorrect syntax? I appreciate any help!

Code:

'creates db connection  Set conn = CreateObject("ADODB.Connection")  With conn      .Provider = "Microsoft.ACE.OLEDB.12.0;"      .ConnectionString = "Data Source=" & wbk.FullName & ";" & "Excel 8.0;HDR=Yes;IMEX=0;Mode=ReadWrite;"      .Open  End With    sqlStr = "INSERT INTO DB_Name." & tblname & " ("    For i = 1 To UBound(hdrary)      If i <> UBound(hdrary) Then          sqlStr = sqlStr & hdrary(i, 1) & ", "      Else          sqlStr = sqlStr & hdrary(i, 1) & ") VALUES ("      End If  Next i    For i = 1 To UBound(hdrary)      If i <> UBound(hdrary) Then          sqlStr = sqlStr & "?, "      Else          sqlStr = sqlStr & "?)"      End If  Next i    'Statement follows this example:  'strSQL = "INSERT INTO " & Database_Name & ".[dbo]." & Table_Name & _  '         "    ([Audit], [Audit Type], [Claim Received Date], [Date Assigned], [Date Completed]," & _  '         "     [Analyst], [Customer], [ID], [Affiliate], [Facility], [DEA], [Acct Number], [Wholesaler]," & _  '         "     [Vendor], [Product], [NDC], [Ref], [Claimed Contract], [Claimed Contract Cost]," & _  '         "     [Contract Price Start Date], [Contract Price End Date], [Catalog Number], [Invoice Number], [Invoice Date]," & _  '         "     [Chargeback ID], [Contract Indicator], [Unit Cost],[WAC], [Potential Credit Due]," & _  '         "     [Qty], [Spend],[IP-DSH indicator Y/N], [DSH and/or HRSA Number], [Unique GPO Code]," & _  '         "     [Comment],[ResCode],[Correct Cost],[CRRB CM],[CRRB Rebill],[CRRB Date])" & _  '         " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," _  '         "         ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"    lastrow = wks.Cells(Rows.count, "a").End(xlUp).Row    sys.Close  wbk.Close    For i = 2 To lastrow      Set cmd = CreateObject("ADODB.Command")        With cmd        .ActiveConnection = conn   ' CONNECTION OBJECT        .CommandText = sqlStr        ' SQL STRING        .CommandType = adCmdText          ' BINDING PARAMETERS          For j = 1 To UBound(hdrary)              .Parameters.Append .CreateParameter("s" & hdrary(j, 1), adVarChar, adParamInput, 255, wks.Cells(i, j))              .Execute          Next j      End With        Set cmd = Nothing  Next i  

Convert image to webp and send it to nodejs [closed]

Posted: 24 May 2022 12:46 PM PDT

I am using express and I need to make a form with an image upload, that when receiving the image converts it to webp and after that when the user sends the form to be able to receive the image and save it on the server with unique id, is this possible?

Add String to New Line After Final Pattern Match

Posted: 24 May 2022 12:47 PM PDT

I am trying to add the follow string after the last pattern match in a text file.

Text File

<MultiGeometry>  <Polygon>1  </Polygon>  <Polygon>2  </Polygon>  <Polygon>3  </Polygon>  <Polygon>4  </Polygon>  <Polygon>5  </Polygon>  

Attempted Code

sed -i '/<\/Polygon>/a</\MultiGeometry>' text_file  

This code inserts </MultiGeometry> after each match of </Polygon> instead of the last match of </Polygon> in the text file.

Current Result

<MultiGeometry>  <Polygon>1  </Polygon>  </MultiGeometry>  <Polygon>2  </Polygon>  </MultiGeometry>  <Polygon>3  </Polygon>  </MultiGeometry>  <Polygon>4  </Polygon>  </MultiGeometry>  <Polygon>5  </Polygon>  </MultiGeometry>  

Expected Result

<MultiGeometry>  <Polygon>1  </Polygon>  <Polygon>2  </Polygon>  <Polygon>3  </Polygon>  <Polygon>4  </Polygon>  <Polygon>5  </Polygon>  </MultiGeometry>  

Need a quick start guide to configure SAML 2.0 Single Sign On in Azure Active directory

Posted: 24 May 2022 12:46 PM PDT

I have a SAML 2.0 based Single Sign On working with Pingfederate, wso2 Identity server as well as ADFS. Its also working with Azure AD SAML 2.0 fedration. But I need to have my own setup to incorporate the recent changes by Azure on using multiple certificates for signing it responses which they claim to change dynamically.

Please point me to a quick setup resouce on this as I am new to Azure.

Http response cannot be deserialized when it's created from test case

Posted: 24 May 2022 12:47 PM PDT

I'm trying to run this test:

[TestFixture]  public class AccountManagementViewModelTests  {      [Test, BaseAutoData]      public void OnSync_Should_AddToDatabase_MissingLists(          [Frozen] Mock<IHttpClientService> httpClientService,          [Frozen] Mock<IDataStore<AppModel.List>> dataStore,          List<ApiModel.List> lists,          AccountManagementViewModel sut)      {          // Arrange          httpClientService              .Setup(x => x.GetAsync(It.IsAny<string>()))              .ReturnsAsync(new HttpResponseMessage()              {                  Content = JsonContent.Create(lists)              });            // Act          sut.SyncCommand.Execute(null);            // Assert          dataStore.Verify(              d => d.AddItemAsync(                  It.Is<AppModel.List>(                      x => lists.Any(y => y.Guid == x.ListId))),              Times.Exactly(3));      }  }  

Problem is, when I try to deserialize the response, I get 3 empty entities

var allBackedupListsForCurrentUserRequestTask = _httpClientService.GetAsync(string.Format(ListApiEndPoints.GetListsByOwnerEmail, ApplicationUser.Current.Email));      var allBackedupListsForCurrentUserRequest = await allBackedupListsForCurrentUserRequestTask;  var allBackedupListsForCurrentUser = await JsonSerializer.DeserializeAsync<List<ApiModel.List>>(await allBackedupListsForCurrentUserRequest.Content.ReadAsStreamAsync());  

If I examine the content of allBackedupListsForCurrentUserRequest.Content I can see all the data there, but none are deserialized into the allBackedupListsForCurrentUser.

The code works fine with real HttpRequests, the issue rises only during unit tests.

What am I missing here?

Other classes involved:

HttpClientService

using ListApp.Services.Interfaces;  using System;  using System.Net.Http;  using System.Threading.Tasks;    namespace ListApp.Services  {      public class HttpClientService : IHttpClientService      {          private static HttpClient _httpClient = new HttpClient();            public async Task<HttpResponseMessage> GetAsync(string requestUri)          {              return await _httpClient.GetAsync(requestUri);          }            public async Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)          {              return await _httpClient.PutAsync(requestUri, content);          }          public async Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)          {              return await _httpClient.PostAsync(requestUri, content);          }            public void SetBaseAddress(Uri baseAddress)          {              _httpClient.BaseAddress = baseAddress;          }      }  }  

BaseAutoDataAttribute

using AutoFixture;  using AutoFixture.AutoMoq;  using AutoFixture.NUnit3;  using System;    namespace ListApp.UnitTests.DataTtributes  {      [AttributeUsage(AttributeTargets.Method)]      internal class BaseAutoDataAttribute : AutoDataAttribute      {          public BaseAutoDataAttribute() : base(() => CreateFixture()) { }            private static IFixture CreateFixture()          {              var fixture = new Fixture();                fixture.Customize(new AutoMoqCustomization { ConfigureMembers = true, GenerateDelegates = true });                return fixture;          }      }  }    

bar plot in 3d following a given line

Posted: 24 May 2022 12:46 PM PDT

I want to draw a bar plot in 3d. I know how to do that using the following code:

from mpl_toolkits.mplot3d import Axes3D  import matplotlib.pyplot as plt  import numpy as np  fig = plt.figure(figsize=(10,10))  ax = fig.add_subplot(111, projection='3d')  nbins = 50  # for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):  ys = np.random.normal(loc=10, scale=10, size=2000)    hist, bins = np.histogram(ys, bins=nbins)  xs = (bins[:-1] + bins[1:])/2    ax.bar(xs, hist, zs=30, zdir='y', color='r', ec='r', alpha=0.8)    ax.set_xlabel('X')  ax.set_ylabel('Y')  ax.set_zlabel('Z')    plt.show()  

This will render something like this: https://i.stack.imgur.com/KK2If.png

However, my goal is to make the bar plot follows a line that I give as parameter. For example here, the parameter zdir='y' makes the plot have its current direction. Ideally I want to pass a parameter that makes the plot follows a given line for example y=2x+1.

Could someone help arrive at the desired result?

Elasticsearch document -- what does the "input" key do?

Posted: 24 May 2022 12:46 PM PDT

I am working in a legacy codebase, and I have documents that are being indexed in ElasticSearch that look like the below image. I am trying to determine what feature or functional part of ElasticSearch is being used in the image below, with these "input" keys.

example ES document

The reason I need to know is because I have reason to suspect that this feature or whatever it is, is not supported by OpenSearch, due to bugs cropping up around these fields in particular (I recently upgraded). However, I can perform a search that successfully queries for these fields when using my current version of ElasticSearch, doing something like the below. However, the same code does not work in an updated version of OpenSearch:

from elasticsearch import Elasticsearch, RequestsHttpConnection    ELASTICSEARCH_URL = "localhost:9200/"  ES_CLIENT = Elasticsearch(      [ELASTICSEARCH_URL],       connection_class=RequestsHttpConnection  )  q = "Brian Peterson"  queries = (MatchPhrasePrefix(full_name=q))  s = (      Search(using=client, index="riders")      .query(queries)      .highlight_options(order="score")      .extra(from_=0, size=25)  )    hits = s.execute().hits  result = hits.hits[0]  

I can't find any reference to input, used this way, in old or new documentation, release notes or anything. Does anyone know what this "input" key is supposed to do? Any guesses? Is it just an old bug, maybe? I need to know definitively in order to be comfortable removing it.

It looks a bit like this feature, related to "watchers", but the format is different: https://www.elastic.co/guide/en/elasticsearch/reference/6.3/input-simple.html.
I also find references to LogStash plugins when I search for "Elasticsearch DSL input" or similar things.

The version we were using of ElasticsSearch was possibly version 6.3.2.

Select a ComboBoxItem when button is clicked

Posted: 24 May 2022 12:47 PM PDT

I want to set the ComboBox yrComBox that selects the ComboBoxItem when I click the button.

Combobox in WPF:

<ComboBox x:Name="yrComBox" Grid.Column="3"      Margin="0 0 10 0" FontSize="14" Padding="5"       FontFamily="Fonts/#Montserrat" Background="#fff">      <ComboBoxItem Content="1st Year" Padding="5"/>      <ComboBoxItem Content="2nd Year" Padding="5"/>      <ComboBoxItem Content="3rd Year" Padding="5"/>      <ComboBoxItem Content="4th Year" Padding="5"/>  </ComboBox>  

Button:

<Button Grid.Column="2" x:Name="submitBtn"      Margin="5 0 0 0" Cursor="Hand"      Click="submitBtn_Click" Content="submit"      Foreground="White" FontFamily="Fonts/#Montserrat">   </Button>  

C#:

private void submitBtn_Click(object sender, RoutedEventArgs e)  {      string year = "2nd Year";        // set yrComBox here that selects a comboboxitem that its content is the variable year  }  

Android Studio Compose preview render problem

Posted: 24 May 2022 12:46 PM PDT

Android Studio Chipmunk 2021.2.1;   Compose Version = '1.1.1';   Gradle  Version 7.4.2;   Kotlin 1.6.10;  

Up to one point, everything was working. Then this error appeared and the preview stopped working when I try to call "LocalContext.current" and make "context.applicationContext as Application" both in this project and in another one. Where it used to work with "LocalContext.current"

Tried on different versions of Compouse, kotlin, gradle.

Render problem

java.lang.ClassCastException: class com.android.layoutlib.bridge.android.BridgeContext cannot be cast to class android.app.Application (com.android.layoutlib.bridge.android.BridgeContext and android.app.Application are in unnamed module of loader com.intellij.ide.plugins.cl.PluginClassLoader @3a848149)   at com.client.personalfinance.screens.ComposableSingletons$AccountScreenKt$lambda-2$1.invoke(AccountScreen.kt:136)   at com.client.personalfinance.screens.ComposableSingletons$AccountScreenKt$lambda-2$1.invoke(AccountScreen.kt:133)   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)   at androidx.compose.material.MaterialTheme_androidKt.PlatformMaterialTheme(MaterialTheme.android.kt:23)   at androidx.compose.material.MaterialThemeKt$MaterialTheme$1$1.invoke(MaterialTheme.kt:82)   at androidx.compose.material.MaterialThemeKt$MaterialTheme$1$1.invoke(MaterialTheme.kt:81)   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)   at androidx.compose.runtime.CompositionLocalKt.CompositionLocalProvider(CompositionLocal.kt:228)   at androidx.compose.material.TextKt.ProvideTextStyle(Text.kt:265

@Preview(showBackground = true) @Composable fun PrevAccountScreen() {           val context  = LocalContext.current           val mViewModel: MainViewModel =               viewModel(factory = MainVeiwModelFactory(context.applicationContext as Application))          AccountScreen(navController = rememberNavController(), viewModel = mViewModel)        }  

Snyk Code Upload Results To Dashboard like Monitor

Posted: 24 May 2022 12:47 PM PDT

I'm trying to run Snyk on bitbucket pipeline. I'm running the pipes for composer and npm and things are working but I also want to run it for static code analysis. None of the documentation shows how this is possible. I have tried installing snyk with NPM followed by running

snyk auth TOKEN  snyk code test  snyk monitor  

but the static code analysis doesn't showup on the Snyk dashboard. Looking for commands or documentation to run static code analysis through the bitbucket pipline.

AWK script- Not showing data

Posted: 24 May 2022 12:46 PM PDT

I'm trying to create a variable to sum columns 26 to 30 and 32. SO far I have this code which prints me the hearder and the output format like I want but no data is being shown.

#! /usr/bin/awk -f    BEGIN { FS="," }  NR>1 {      TotalPositiveStats= ($26+$27+$28+$29+$30+$32)      }          {printf "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%.2f %,%s,%s,%.2f %,%s,%s,%.2f %,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s, %s\n",  EndYear,Rk,G,Date,Years,Days,Age,Tm,Home,Opp,Win,Diff,GS,MP,FG,FGA,FG_PCT,3P,3PA,3P_PCT,FT,FTA,FT_PCT,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS,GmSc,TotalPositiveStats          }    NR==1   {      print "EndYear,Rk,G,Date,Years,Days,Age,Tm,HOme,Opp,Win,Diff,GS,MP,FG,FGA,FG_PCT,3P,3PA,3P_PCT,FT,FTA,FT_PCT,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS,GmSc,TotalPositiveStats" }#header  

Input data:

EndYear,Rk,G,Date,Years,Days,Age,Tm,Home,Opp,Win,Diff,GS,MP,FG,FGA,FG_PCT,3P,3PA,3P_PCT,FT,FTA,FT_PCT,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS,GmSc  1985,1,1,10/26/1984,21,252,21.6899384,CHI,1,WSB,1,16,1,40,5,16,0.313,0,0,,6,7,0.857,1,5,6,7,2,4,5,2,16,12.5  1985,2,2,10/27/1984,21,253,21.69267625,CHI,0,MIL,0,-2,1,34,8,13,0.615,0,0,,5,5,1,3,2,5,5,2,1,3,4,21,19.4  1985,3,3,10/29/1984,21,255,21.69815195,CHI,1,MIL,1,6,1,34,13,24,0.542,0,0,,11,13,0.846,2,2,4,5,6,2,3,4,37,32.9  1985,4,4,10/30/1984,21,256,21.7008898,CHI,0,KCK,1,5,1,36,8,21,0.381,0,0,,9,9,1,2,2,4,5,3,1,6,5,25,14.7  1985,5,5,11/1/1984,21,258,21.7063655,CHI,0,DEN,0,-16,1,33,7,15,0.467,0,0,,3,4,0.75,3,2,5,5,1,1,2,4,17,13.2  1985,6,6,11/7/1984,21,264,21.72279261,CHI,0,DET,1,4,1,27,9,19,0.474,0,0,,7,9,0.778,1,3,4,3,3,1,5,5,25,14.9  1985,7,7,11/8/1984,21,265,21.72553046,CHI,0,NYK,1,15,1,33,15,22,0.682,0,0,,3,4,0.75,4,4,8,5,3,2,5,2,33,29.3  

Output expected:

EndYear,Rk,G,Date,Years,Days,Age,Tm,Home,Opp,Win,Diff,GS,MP,FG,FGA,FG_PCT,3P,3PA,3P_PCT,FT,FTA,FT_PCT,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS,GmSc,TotalPositiveStats  1985,1,1,10/26/1984,21,252,21.6899384,CHI,1,WSB,1,16,1,40,5,16,0.313,0,0,,6,7,0.857,1,5,6,7,2,4,5,2,16,12.5,35  1985,2,2,10/27/1984,21,253,21.69267625,CHI,0,MIL,0,-2,1,34,8,13,0.615,0,0,,5,5,1,3,2,5,5,2,1,3,4,21,19.4,34  1985,3,3,10/29/1984,21,255,21.69815195,CHI,1,MIL,1,6,1,34,13,24,0.542,0,0,,11,13,0.846,2,2,4,5,6,2,3,4,37,32.9,54  1985,4,4,10/30/1984,21,256,21.7008898,CHI,0,KCK,1,5,1,36,8,21,0.381,0,0,,9,9,1,2,2,4,5,3,1,6,5,25,14.7,38  1985,5,5,11/1/1984,21,258,21.7063655,CHI,0,DEN,0,-16,1,33,7,15,0.467,0,0,,3,4,0.75,3,2,5,5,1,1,2,4,17,13.2,29  1985,6,6,11/7/1984,21,264,21.72279261,CHI,0,DET,1,4,1,27,9,19,0.474,0,0,,7,9,0.778,1,3,4,3,3,1,5,5,25,14.9,36  1985,7,7,11/8/1984,21,265,21.72553046,CHI,0,NYK,1,15,1,33,15,22,0.682,0,0,,3,4,0.75,4,4,8,5,3,2,5,2,33,29.3,51  

This script will be called like gawk -f script.awk <filename>.

Currently when calling this is the output (It seems to be calculating the variable but the rest of fields are empty) enter image description here

No comments:

Post a Comment