-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgetCodeCF.py
More file actions
311 lines (271 loc) · 8.69 KB
/
getCodeCF.py
File metadata and controls
311 lines (271 loc) · 8.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
from pyquery import PyQuery as pq
import requests as req
import time
import json
import os, os.path
from Database import Database
from fileDB import FileDB
import random
import SleepTimer
base_url = 'http://codeforces.com/'
url = base_url + 'api/'
userfile = 'data/users.json'
samplefile = 'data/sampleUsers.json'
inf = 1000000000
time_inf = inf*2
timer = None
def getData(api, option):
timer.sleep(0.4)
request = req.get(url+api, params=option)
timer.reset()
return request.json()
# get user list from codeforces (consume some time)
def getUserData(option):
if not os.path.isfile(userfile):
users = getData('user.ratedList', {'activeOnly': 'true'})
saveAsJson(users, userfile)
return users
else:
return loadData(userfile)
def getSampleUsers(datalist, n):
if not os.path.isfile(samplefile):
user_list = getUsers(datalist)
sample_list = random.sample(user_list, n)
saveAsJson(sample_list, samplefile)
print('saved sample users')
return sample_list
else:
return loadData(samplefile)
def setSubmissionHistory(db, users, time_from, time_end):
# db.createSampleTableIfNotExists()
# print('start getting submissions')
for user in users:
# db.addUser(user)
handle = user['user_name']
try:
source = recentSources(handle, time_from=time_from, time_end=time_end, src=False)
except:
print('error '+handle)
continue
if len(source) == 0:
continue
# db.addSampleUser(handle, len(source))
for src in source:
filename = '%s_%s_%s.src' % (handle, src['prob_id'], src['contest_id'])
src['file_name'] = filename
db.addFile(src)
# get n users with some information (currently: handle, rating, max_rating)
def getUsers(datalist, n=inf):
users = getUserData({'activeOnly': 'true'})['result']
user_list = []
count = 0
for user in users:
count += 1
if count > n:
break
data = {}
for (cf_name, db_name) in datalist.items():
if not cf_name in user:
print('Wrong datalist. Key %s was not found' % cf_name)
data[db_name] = user[cf_name]
user_list.append(data)
return user_list
# save json data as txt
def saveAsJson(data, filename):
with open(filename, 'w', encoding='utf-8') as f:
f.write(json.dumps(data))
def getSource(prob_id, contest_id):
timer.sleep(1)
dom = pq(base_url + 'contest/%d/submission/%d' % (contest_id, prob_id))
timer.reset()
return dom.find('pre.prettyprint.program-source').text()
def getSourceData(status, src=True):
prob_id = status['id']
contest_id = status['contestId']
data = {}
if src:
data['source'] = getSource(prob_id, contest_id)
data['prob_id'] = prob_id
data['contest_id'] = contest_id
data['lang'] = status['programmingLanguage']
data['timestamp'] = status['creationTimeSeconds']
problem = status['problem']
data['prob_index'] = problem['index']
data['url'] = base_url + 'contest/%d/submission/%d' % (contest_id, prob_id)
if contest_id > 1000:
data['url'] = '-'
if 'verdict' in status:
data['verdict'] = status['verdict'][:20]
else:
data['verdict'] = '-'
return data
# get recent n sources
# return source list (which creationTimeSeconds is larger than "time")
def recentSources(username, n=inf, time_from=0, time_end=time_inf, src=True):
query = {
'handle': username,
'count': n
}
response = getData('user.status', query)
if response['status'] == 'FAILED':
try:
timer.sleep(0.4)
name = pq(base_url+'profile/'+username)('title').text()[:-len(' - Codeforces')]
timer.reset()
query['handle'] = name
username = name
response = getData('user.status', query)
except:
print(username+' failed')
return []
submissions = response['result']
source = []
print("%s's source" % username)
for status in submissions:
if status['creationTimeSeconds'] < time_from:
break
if status['creationTimeSeconds'] > time_end:
continue
# print('getting source id=%d' % status['id'])
source.append(getSourceData(status, src))
return source
def loadData(filename):
data = None
with open(filename, encoding='utf-8') as f:
data = json.loads(f.read())
return data
def saveFile(filename, content):
with open(filename, 'w', encoding='utf-8') as f:
f.write(content)
def init():
if not os.path.isdir('data'):
os.mkdir('data')
month_before = 6
end = 1479181649
def getLeastTime():
sec = end - month_before*30*24*60*60
return int(sec)
idx_file = 'data/lastIdx.dat'
def last():
idx = 0
with open(idx_file) as f:
idx = int(f.read().strip())
return idx
filename = 'data/sample.json'
userdata_format = {
'handle': 'user_name',
'rating': 'rating',
'maxRating': 'max_rating'
}
def getSamples():
db = Database()
filenames = db.getSampleFilenames()
idx = 0
while True:
length = len(filenames)
try:
for filename in filenames[idx:]:
if os.path.isfile('data/src/'+filename):
idx += 1
continue
print('%d/%d' % (idx+1, length))
items = filename[:-4].split('_')
source = getSource(int(items[-2]), int(items[-1]))
saveFile('data/src/'+filename, source)
# saveFile('//nas2/s-tutumi/codeforces/src/'+filename, source)
idx += 1
except:
print('Error in idx: '+str(idx))
saveFile(idx_file, str(idx))
time.sleep(15)
db.close()
def countMiss():
db = Database()
filenames = db.getSampleFilenames()
count = 0
for i, filename in enumerate(filenames):
if (i+1)%10000 == 0:
print('fin '+str(i+1))
if not os.path.isfile('data/src/'+filename):
count += 1
db.close()
print(count)
def setUsersToDB():
# with open('has_null.txt') as f:
# user_list = [{'user_name': row.strip()} for row in f]
user_list = getUsers(userdata_format)
border = getLeastTime()
# samples = set()
# for user in sample_user:
# samples.add(user['user_name'])
# newlist = []
fdb = FileDB()
# flag = False
index = 'prob_index'
for i, user in enumerate(user_list):
# if not user['user_name'] in samples:
# if user['user_name'] == 'SwapnilDGr8':
# flag = True
# if not flag:
# continue
if (i+1)%100 == 0:
fdb.con.connector.commit()
print('%d/%d' % (i, len(user_list)))
# if not fdb.hasNull(user['user_name'], 'points'):
# continue
# newlist.append(user)
file_list = fdb.getFiles({'user_name': user['user_name']})
for fd in file_list:
if fd['timestamp'] is None:
continue
if not index in fd or fd[index] is None or fd[index] == '-':
setSubmissionHistory(fdb, [user], border, end)
break
fdb.close()
def checkDB():
# with open('has_null.txt') as f:
# user_list = [{'user_name': row.strip()} for row in f]
user_list = getUsers(userdata_format)
border = getLeastTime()
# samples = set()
# for user in sample_user:
# samples.add(user['user_name'])
# newlist = []
fdb = FileDB()
# flag = False
index = 'prob_index'
blacklist = []
for i, user in enumerate(user_list):
# if not user['user_name'] in samples:
# if user['user_name'] == 'SwapnilDGr8':
# flag = True
# if not flag:
# continue
if (i+1)%100 == 0:
print('%d/%d' % (i, len(user_list)))
# if not fdb.hasNull(user['user_name'], 'points'):
# continue
# newlist.append(user)
file_list = fdb.getFiles({'user_name': user['user_name']})
for fd in file_list:
if fd['timestamp'] is None:
continue
if not index in fd or fd[index] is None or fd[index] == '-':
blacklist.append(user)
break
if len(blacklist)>10:
break
print(blacklist)
print(len(blacklist))
fdb.close()
if __name__ == '__main__':
# countMiss()
timer = SleepTimer.SleepTimer()
# setUsersToDB()
getSamples()
# checkDB()
# user_list = getUsers(userdata_format)
# target = -1
# for i, user in enumerate(user_list):
# if user['user_name'] == 'MrBear':
# print(i)