StackOverflow.com

VN:F [1.9.22_1171]
Rating: 9.3/10 (9 votes cast)

Random snippets of all sorts of code, mixed with a selection of help and advice.

Attribute Error - int object has no attribute keys - Python

6 Dec 2019, 7:51 am | Recent Questions - Stack Overflow

I'm running this code but I seem to keep getting an attribute error and I don't know how this would be fixed. I've included code as well as the shell window when I run it! Thanks so much!Code:

the Count class. The wordleFromObject function takes a Count object as

input, and calls its getTopWords method.

import stringclass Count:    # method to initialize any data structures, such as a dictionary to    # hold the counts for each word, and a list of stop words    def __init__(self):            #print("Initializing Word Counter")            # set the attrbute wordCounts to an empty dictionary        self.wordCounts = {}        infile = open("stop_words.txt", "r")        self.stop_word_dict = {};        for line in infile.readlines():                self.stop_word_dict = 1    # method to add one to the count for a word in the dictionary.    # if the word is not yet in the dictionary, we'll need to add a    # record for the word, with a count of one.     def incCount(self,word):            my_table = str.maketrans('', '', string.punctuation)            self.wordCounts = {}            if word in self.stop_word_dict.keys():                    return            else:                    self.stop_word_dict += 1            cleaned_word = word.translate(my_table).lower()            if cleaned_word != '':                if cleaned_word in self.wordCounts.keys():                        self.wordCounts[cleaned_word] += 1                else:                        self.wordCounts[cleaned_word] = 1    # method to look up the count for a word    def lookUpCount(self, word):            return self.wordCounts.get(word.lower(), 0)def main():    print("Initializing Word Counter")    filename = input("Enter book file:")    infile = open(filename, "r")    counter = Count()    for line in infile.readlines():            words = [word.strip() for word in line.strip().split()]            for word in words:                    counter.incCount(word)    infile.close()    # Test code for Part 2 and 3      # Comment this code once you have completed part 3.    print(counter.lookUpCount("alice"))    print(counter.lookUpCount("rabbit"))    print(counter.lookUpCount("and"))    print(counter.lookUpCount("she"))    return    # Test code for Part 4 and 5    # topTen = counter.getTopWords(10)    # print(topTen)    # Test code for Part 5    # Import the wordle module and uncomment the call to the wordle function!     # wordle.wordleFromObject(counter,30)# run the main programmain()       

Error Message: Initializing Word Counter Enter book file:Alice.txt Traceback (most recent call last): line 69, in main() line 50, in main counter.incCount(word) line 28, in incCount if word in self.stop_word_dict.keys(): AttributeError: 'int' object has no attribute 'keys'

Slidesshow on a stand alone browser?

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

I can use this function to fetch the picture from database and attach to the index.html. However I want to have a slides show of these pics on a stand alone browser where I could just enter the url to the browser and the slidesshow will play automatically. ANyone have an idea how to do it?Here is my JS function:

 function getPic(ID) {  $.ajax({    url : 'scripts/fgdconfig.php',    type : 'GET',    dataType: 'json',    data: {ID:ID},     success: function(response)       {                      // console.log(response);           // var  res = JSON.parse(response);           console.log(response);/* console json val*/           console.log("HEJ111");           var img = document.createElement("img");           img.src = 'data:image/jpeg;base64,'+ response;           data = img.src;           console.log("HEJ");           console.log(img.src );           var src = document.getElementById("showpic");           src.appendChild(img);                   //callback(data);                 },                 error : function () {                   alert("error getPic");                 }               });}

Read two rows together from CSV file which is pipe separated using python

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

We have below report which is pipe separated csv file.

1 CVOR_Abstract_L2||Abstract_L2_053018.rtf|Abstract_L2_053018.xlf|PDF|||

2 |Upload Success|

3 CVOR_Abstract_L2_Certified||Abstract_L2_053018_Certified.rtf|Abstract_L2_053018_Certified.xlf|PDF|||

4 |Upload Success|

5 CVOR_Abstract_L2_Siebel||Abstract_L2 - Siebel_v50_Dates.rtf|Abstract_L2 - Siebel_v50_Dates.xlf|PDF|||

6 |Upload Failure|

I have to print the first column from 1st 3rd 5th line and append with corresponding Success or Failure Message

I tried using following Python code, but its not fulfilling my requirement any help would be highly appreciated. I am not sure how to read group of lines as single line and parse

fileHandle = open('outout.csv', 'r')for line in fileHandle:    fields = line.split('|')    print(fields[0]) fileHandle.close()

How can i solve these database query problem?

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

I have an employees table and a department table.department and employee tableMy question is how to find those employees who worked in more than one department in the company. Print employee last names. Cannot use join in the main query and use sub-query. Also can use join in the sub-queries.

How to create a form and be able to input the data from the form into a text file and be able to output a contents of a text file in HTML

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

I have successfully hosted an .onion website but I don't have much experience in HTML codes. I need someone to tell me how to create a form + be able to input the submitted stuff inside the form (raw) into a text file + output the contents of a text file. Thanks :) Any help is greatly appreciated.

how to display one data based on the latest date that does not have the same data

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

I have difficulty displaying one data that does not have similarity based on the latest date

http://sqlfiddle.com/#!9/5d8147/1

expected display results

please help me to solve the problem

Unity's Probuilder: How insert edge loop on a mesh at runtime with script

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

As per the title - how can I insert edge loop on a mesh at runtime with a script?

I can't find anything on this on the documentation or the internet.

Thank you for your help

Accessing gsuite mail with C#

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

I am developing a console application in Windows that will connect to a gsuite mail account, check the list of messages, download the attachment and move the message to a done folder (or just delete it).

I sort of made this work, but the application sometimes needs to refresh the credentials and so it opens up a browser. This is a bit unfortunate as the application is run from the server using the scheduled task.

So I have been given the task to use service account.

When I connect now I either get this error:

Message[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global]This error comes when I use this one:

    credential = new ServiceAccountCredential(new         ServiceAccountCredential.Initializer(serviceAccount)                {                    Scopes = new[] {                        GmailService.Scope.MailGoogleCom                        // GmailService.Scope.GmailSettingsSharing                    }                }.FromPrivateKey(privateKey));

Or this one:

An error has occured: Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.

Same code as above, just adds User:

    var userId = "[email protected]";    credential = new ServiceAccountCredential(new      ServiceAccountCredential.Initializer(serviceAccount)                {                    User = userId,                    Scopes = new[] {                        GmailService.Scope.MailGoogleCom                        // GmailService.Scope.GmailSettingsSharing                    }                }.FromPrivateKey(privateKey));

My gut feeling is that the client has not gotten the correct settings in scope. Anyone experienced the same thing and got it right in the end?

Why does IntelliJ does not auto import react router hooks?

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

From v5.1 the react router supports hook. I have "react-router-dom": "^5.1.2" in my package.json but when typing useRouterMatch in my component, IntelliJ does not suggest to auto import import {useRouteMatch} from "react-router-dom";

When adding the import manually everything works, but that's pretty inconvenient.

When I converted a vgg model written by pytorch to caffe2, I encountered this problem

6 Dec 2019, 7:50 am | Recent Questions - Stack Overflow

model = VGGish()  # vgg model classmodel.train(False)x = torch.randn(10, 1, 64, 96, requires_grad=True)# Export the modeltorch_out = torch.onnx._export(model,             # model being run`enter code here`                               x,                       # model input (or a tuple for multiple inputs)                               "super_resolution.onnx", # where to save the model (can be a file or file-like object)                               export_params=True)      # store the trained parameter weights inside the model filemodel = onnx.load("modelsVGGish_conv.onnx")onnx.checker.check_model(model)onnx.helper.printable_graph(model.graph)rep = backend.prepare(model, device="CPU") # or "CPU"

When the program runs to this code

rep = backend.prepare(model, device="CPU") # or "CPU"

the erro occurred:

Traceback (most recent call last):  File "C:/Users/xxx/Desktop/python/新建文件夹/onnx_to_caffe2.py", line 159, in <module>    rep = backend.prepare(model, device="CPU") # or "CPU"  File "D:\environment\Anaconda\lib\site-packages\caffe2\python\onnx\backend.py", line 713, in prepare    init_net, predict_net = cls._onnx_model_to_caffe2_net(model, device, opset_version, False)  File "D:\environment\Anaconda\lib\site-packages\caffe2\python\onnx\backend.py", line 876, in _onnx_model_to_caffe2_net    onnx_model = onnx.utils.polish_model(onnx_model)  File "D:\environment\Anaconda\lib\site-packages\onnx\utils.py", line 21, in polish_model    model = onnx.optimizer.optimize(model)  File "D:\environment\Anaconda\lib\site-packages\onnx\optimizer.py", line 55, in optimize    optimized_model_str = C.optimize(model_str, passes)IndexError: invalid unordered_map<K, T> key

it just make me crazy!

Anyone can help me?

Recent Questions - Stack Overflow