desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'The TorConnectionDialog wants to open the Settings dialog'
| def _tor_connection_open_settings(self):
| common.log('OnionShareGui', '_tor_connection_open_settings')
QtCore.QTimer.singleShot(1, self.open_settings)
|
'Open the SettingsDialog.'
| def open_settings(self):
| common.log('OnionShareGui', 'open_settings')
def reload_settings():
common.log('OnionShareGui', 'open_settings', 'settings have changed, reloading')
self.settings.load()
d = SettingsDialog(self.onion, self.qtapp, self.config)
d.settings_saved.connect(reload_settings)
d.exec_... |
'Start the onionshare server. This uses multiple threads to start the Tor onion
server and the web app.'
| def start_server(self):
| common.log('OnionShareGui', 'start_server')
self.set_server_active(True)
self.app.set_stealth(self.settings.get('use_stealth'))
self.downloads_container.hide()
self.downloads.reset_downloads()
web.download_count = 0
web.error404_count = 0
web.set_gui_mode()
def start_onion_service(se... |
'Step 2 in starting the onionshare server. Zipping up files.'
| def start_server_step2(self):
| common.log('OnionShareGui', 'start_server_step2')
self._zip_progress_bar = ZipProgressBar(0)
self._zip_progress_bar.total_files_size = OnionShareGui._compute_total_size(self.file_selection.file_list.filenames)
self.status_bar.clearMessage()
self.status_bar.insertWidget(0, self._zip_progress_bar)
... |
'Step 3 in starting the onionshare server. This displays the large filesize
warning, if applicable.'
| def start_server_step3(self):
| common.log('OnionShareGui', 'start_server_step3')
if (self._zip_progress_bar is not None):
self.status_bar.removeWidget(self._zip_progress_bar)
self._zip_progress_bar = None
if (web.zip_filesize >= 157286400):
self.filesize_warning.setText(strings._('large_filesize', True))
s... |
'If there\'s an error when trying to start the onion service'
| def start_server_error(self, error):
| common.log('OnionShareGui', 'start_server_error')
self.set_server_active(False)
Alert(error, QtWidgets.QMessageBox.Warning)
self.server_status.stop_server()
self.status_bar.clearMessage()
|
'Stop the onionshare server.'
| def stop_server(self):
| common.log('OnionShareGui', 'stop_server')
if (self.server_status.status != self.server_status.STATUS_STOPPED):
web.stop(self.app.port)
self.app.cleanup()
self.filesize_warning.hide()
self.stop_server_finished.emit()
self.set_server_active(False)
|
'Check for updates in a new thread, if enabled.'
| def check_for_updates(self):
| system = common.get_platform()
if ((system == 'Windows') or (system == 'Darwin')):
if self.settings.get('use_autoupdate'):
def update_available(update_url, installed_version, latest_version):
Alert(strings._('update_available', True).format(update_url, installed_version, late... |
'Check for messages communicated from the web app, and update the GUI accordingly.'
| def check_for_requests(self):
| self.update()
if self.new_download:
self.vbar.setValue(self.vbar.maximum())
self.new_download = False
if (self.server_status.status != self.server_status.STATUS_STARTED):
return
events = []
done = False
while (not done):
try:
r = web.q.get(False)
... |
'When the URL gets copied to the clipboard, display this in the status bar.'
| def copy_url(self):
| common.log('OnionShareGui', 'copy_url')
self.status_bar.showMessage(strings._('gui_copied_url', True), 2000)
|
'When the stealth onion service HidServAuth gets copied to the clipboard, display this in the status bar.'
| def copy_hidservauth(self):
| common.log('OnionShareGui', 'copy_hidservauth')
self.status_bar.showMessage(strings._('gui_copied_hidservauth', True), 2000)
|
'Clear messages from the status bar.'
| def clear_message(self):
| self.status_bar.clearMessage()
|
'Disable the Settings button while an OnionShare server is active.'
| def set_server_active(self, active):
| self.settings_button.setEnabled((not active))
if active:
self.settings_button.setIcon(QtGui.QIcon(common.get_resource_path('images/settings_inactive.png')))
else:
self.settings_button.setIcon(QtGui.QIcon(common.get_resource_path('images/settings.png')))
self.settingsAction.setEnabled((no... |
'Test that `SLUG_REGEX` accounts for the following patterns
There are a few hyphenated words in `wordlist.txt`:
* drop-down
* felt-tip
* t-shirt
* yo-yo
These words cause a few extra potential slug patterns:
* word-word
* hyphenated-word-word
* word-hyphenated-word
* hyphenated-word-hyphenated-word'
| @pytest.mark.parametrize('test_input,expected', (('syrup-enzyme', True), ('caution-friday', True), ('drop-down-thimble', True), ('unmixed-yo-yo', True), ('yo-yo-drop-down', True), ('felt-tip-t-shirt', True), ('hello-world', True), ('Upper-Case', False), ('digits-123', False), ('too-many-hyphens-', False), ('symbols-!@#... | assert (bool(SLUG_REGEX.match(test_input)) == expected)
|
'dir_size() should return the total size (in bytes) of all files
in a particular directory.'
| def test_temp_dir_size(self, temp_dir_1024_delete):
| assert (common.dir_size(temp_dir_1024_delete) == 1024)
|
'get_available_port() should return an open port within the range'
| @pytest.mark.parametrize('port_min,port_max', ((random.randint(1024, 1500), random.randint(1800, 2048)) for _ in range(50)))
def test_returns_an_open_port(self, port_min, port_max):
| port = common.get_available_port(port_min, port_max)
assert (port_min <= port <= port_max)
with socket.socket() as tmpsock:
tmpsock.bind(('127.0.0.1', port))
|
'load_strings() loads English by default'
| def test_load_strings_defaults_to_english(self, locale_en, sys_onionshare_dev_mode):
| strings.load_strings(common)
assert (strings._('wait_for_hs') == 'Waiting for HS to be ready:')
|
'load_strings() loads other languages in different locales'
| def test_load_strings_loads_other_languages(self, locale_fr, sys_onionshare_dev_mode):
| strings.load_strings(common, 'fr')
assert (strings._('wait_for_hs') == 'En attente du HS:')
|
'load_strings() raises a KeyError for an invalid locale'
| def test_load_invalid_locale(self, locale_invalid, sys_onionshare_dev_mode):
| with pytest.raises(KeyError):
strings.load_strings(common, 'XX')
|
'Add a file to the zip archive.'
| def add_file(self, filename):
| self.z.write(filename, os.path.basename(filename), zipfile.ZIP_DEFLATED)
self._size += os.path.getsize(filename)
self.processed_size_callback(self._size)
|
'Add a directory, and all of its children, to the zip archive.'
| def add_dir(self, filename):
| dir_to_strip = (os.path.dirname(filename.rstrip('/')) + '/')
for (dirpath, dirnames, filenames) in os.walk(filename):
for f in filenames:
full_filename = os.path.join(dirpath, f)
if (not os.path.islink(full_filename)):
arc_filename = full_filename[len(dir_to_strip... |
'Close the zip archive.'
| def close(self):
| self.z.close()
|
'If there are any missing settings from self._settings, replace them with
their default values.'
| def fill_in_defaults(self):
| for key in self.default_settings:
if (key not in self._settings):
self._settings[key] = self.default_settings[key]
|
'Returns the path of the settings file.'
| def build_filename(self):
| p = platform.system()
if (p == 'Windows'):
appdata = os.environ['APPDATA']
return '{}\\OnionShare\\onionshare.json'.format(appdata)
elif (p == 'Darwin'):
return os.path.expanduser('~/Library/Application Support/OnionShare/onionshare.json')
else:
return os.path.expandus... |
'Load the settings from file.'
| def load(self):
| common.log('Settings', 'load')
if os.path.exists(self.filename):
try:
common.log('Settings', 'load', 'Trying to load {}'.format(self.filename))
with open(self.filename, 'r') as f:
self._settings = json.loads(f.read())
self.fill_in_defaults... |
'Save settings to file.'
| def save(self):
| common.log('Settings', 'save')
try:
os.makedirs(os.path.dirname(self.filename))
except:
pass
open(self.filename, 'w').write(json.dumps(self._settings))
print strings._('settings_saved').format(self.filename)
|
'Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.'
| def _recvall(self, count):
| data = ''
while (len(data) < count):
d = self.recv((count - len(data)))
if (not d):
raise GeneralProxyError('Connection closed unexpectedly')
data += d
return data
|
'set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxy_type - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The... | def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
| self.proxy = (proxy_type, addr.encode(), port, rdns, (username.encode() if username else None), (password.encode() if password else None))
|
'Returns the bound IP address and port number at the proxy.'
| def get_proxy_sockname(self):
| return self.proxy_sockname
|
'Returns the IP and port number of the proxy.'
| def get_proxy_peername(self):
| return _orig_socket.getpeername(self)
|
'Returns the IP address and port number of the destination
machine (note: get_proxy_peername returns the proxy)'
| def get_peername(self):
| return self.proxy_peername
|
'Negotiates a connection through a SOCKS5 server.'
| def _negotiate_SOCKS5(self, dest_addr, dest_port):
| (proxy_type, addr, port, rdns, username, password) = self.proxy
if (username and password):
self.sendall('\x05\x02\x00\x02')
else:
self.sendall('\x05\x01\x00')
chosen_auth = self._recvall(2)
if (chosen_auth[0:1] != '\x05'):
raise GeneralProxyError('SOCKS5 proxy server ... |
'Negotiates a connection through a SOCKS4 server.'
| def _negotiate_SOCKS4(self, dest_addr, dest_port):
| (proxy_type, addr, port, rdns, username, password) = self.proxy
remote_resolve = False
try:
addr_bytes = socket.inet_aton(dest_addr)
except socket.error:
if rdns:
addr_bytes = '\x00\x00\x00\x01'
remote_resolve = True
else:
addr_bytes = socket.i... |
'Negotiates a connection through an HTTP server.
NOTE: This currently only supports HTTP CONNECT-style proxies.'
| def _negotiate_HTTP(self, dest_addr, dest_port):
| (proxy_type, addr, port, rdns, username, password) = self.proxy
addr = (dest_addr if rdns else socket.gethostbyname(dest_addr))
self.sendall(((((((('CONNECT ' + addr.encode()) + ':') + str(dest_port).encode()) + ' HTTP/1.1\r\n') + 'Host: ') + dest_addr.encode()) + '\r\n\r\n'))
fobj = self.makef... |
'Connects to the specified destination through a proxy.
Uses the same API as socket\'s connect().
To select the proxy server, use set_proxy().
dest_pair - 2-tuple of (IP/hostname, port).'
| def connect(self, dest_pair):
| (proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy
(dest_addr, dest_port) = dest_pair
if ((not isinstance(dest_pair, (list, tuple))) or (len(dest_pair) != 2) or (not isinstance(dest_addr, type(''))) or (not isinstance(dest_port, int))):
raise GeneralProxyError('Invalid de... |
'Start the onionshare onion service.'
| def start_onion_service(self):
| common.log('OnionShare', 'start_onion_service')
self.port = common.get_available_port(17600, 17650)
if self.local_only:
self.onion_host = '127.0.0.1:{0:d}'.format(self.port)
return
self.onion_host = self.onion.start_onion_service(self.port)
if self.stealth:
self.auth_string =... |
'Shut everything down and clean up temporary files, etc.'
| def cleanup(self):
| common.log('OnionShare', 'cleanup')
for filename in self.cleanup_filenames:
if os.path.isfile(filename):
os.remove(filename)
elif os.path.isdir(filename):
shutil.rmtree(filename)
self.cleanup_filenames = []
|
'The main function that segments an entire sentence that contains
Chinese characters into seperated words.
Parameter:
- sentence: The str(unicode) to be segmented.
- cut_all: Model type. True for full pattern, False for accurate pattern.
- HMM: Whether to use the Hidden Markov Model.'
| def cut(self, sentence, cut_all=False, HMM=True):
| sentence = strdecode(sentence)
if cut_all:
re_han = re_han_cut_all
re_skip = re_skip_cut_all
else:
re_han = re_han_default
re_skip = re_skip_default
if cut_all:
cut_block = self.__cut_all
elif HMM:
cut_block = self.__cut_DAG
else:
cut_block... |
'Finer segmentation for search engines.'
| def cut_for_search(self, sentence, HMM=True):
| words = self.cut(sentence, HMM=HMM)
for w in words:
if (len(w) > 2):
for i in xrange((len(w) - 1)):
gram2 = w[i:(i + 2)]
if self.FREQ.get(gram2):
(yield gram2)
if (len(w) > 3):
for i in xrange((len(w) - 2)):
... |
'Load personalized dict to improve detect rate.
Parameter:
- f : A plain text file contains words and their ocurrences.
Can be a file-like object, or the path of the dictionary file,
whose encoding must be utf-8.
Structure of dict file:
word1 freq1 word_type1
word2 freq2 word_type2
Word type may be ignored'
| def load_userdict(self, f):
| self.check_initialized()
if isinstance(f, string_types):
f_name = f
f = open(f, u'rb')
else:
f_name = resolve_filename(f)
for (lineno, ln) in enumerate(f, 1):
line = ln.strip()
if (not isinstance(line, text_type)):
try:
line = line.deco... |
'Add a word to dictionary.
freq and tag can be omitted, freq defaults to be a calculated value
that ensures the word can be cut out.'
| def add_word(self, word, freq=None, tag=None):
| self.check_initialized()
word = strdecode(word)
freq = (int(freq) if (freq is not None) else self.suggest_freq(word, False))
self.FREQ[word] = freq
self.total += freq
if tag:
self.user_word_tag_tab[word] = tag
for ch in xrange(len(word)):
wfrag = word[:(ch + 1)]
if (w... |
'Convenient function for deleting a word.'
| def del_word(self, word):
| self.add_word(word, 0)
|
'Suggest word frequency to force the characters in a word to be
joined or splitted.
Parameter:
- segment : The segments that the word is expected to be cut into,
If the word should be treated as a whole, use a str.
- tune : If True, tune the word frequency.
Note that HMM may affect the final result. If the result doesn... | def suggest_freq(self, segment, tune=False):
| self.check_initialized()
ftotal = float(self.total)
freq = 1
if isinstance(segment, string_types):
word = segment
for seg in self.cut(word, HMM=False):
freq *= (self.FREQ.get(seg, 1) / ftotal)
freq = max((int((freq * self.total)) + 1), self.FREQ.get(word, 1))
else... |
'Tokenize a sentence and yields tuples of (word, start, end)
Parameter:
- sentence: the str(unicode) to be segmented.
- mode: "default" or "search", "search" is for finer segmentation.
- HMM: whether to use the Hidden Markov Model.'
| def tokenize(self, unicode_sentence, mode=u'default', HMM=True):
| if (not isinstance(unicode_sentence, text_type)):
raise ValueError(u'jieba: the input parameter should be unicode.')
start = 0
if (mode == u'default'):
for w in self.cut(unicode_sentence, HMM=HMM):
width = len(w)
(yield (w, start, (start + width)))
... |
'Extract keywords from sentence using TextRank algorithm.
Parameter:
- topK: return how many top keywords. `None` for all possible words.
- withWeight: if True, return a list of (word, weight);
if False, return a list of words.
- allowPOS: the allowed POS list eg. [\'ns\', \'n\', \'vn\', \'v\'].
if the POS of w is not ... | def textrank(self, sentence, topK=20, withWeight=False, allowPOS=(u'ns', u'n', u'vn', u'v'), withFlag=False):
| self.pos_filt = frozenset(allowPOS)
g = UndirectWeightedGraph()
cm = defaultdict(int)
words = tuple(self.tokenizer.cut(sentence))
for (i, wp) in enumerate(words):
if self.pairfilter(wp):
for j in xrange((i + 1), (i + self.span)):
if (j >= len(words)):
... |
'Extract keywords from sentence using TF-IDF algorithm.
Parameter:
- topK: return how many top keywords. `None` for all possible words.
- withWeight: if True, return a list of (word, weight);
if False, return a list of words.
- allowPOS: the allowed POS list eg. [\'ns\', \'n\', \'vn\', \'v\',\'nr\'].
if the POS of w is... | def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False):
| if allowPOS:
allowPOS = frozenset(allowPOS)
words = self.postokenizer.cut(sentence)
else:
words = self.tokenizer.cut(sentence)
freq = {}
for w in words:
if allowPOS:
if (w.flag not in allowPOS):
continue
elif (not withFlag):
... |
':type x: int
:type y: int
:rtype: int'
| def hammingDistance(self, x, y):
| distance = 0
z = (x ^ y)
while z:
distance += 1
z &= (z - 1)
return distance
|
':type x: int
:type y: int
:rtype: int'
| def hammingDistance2(self, x, y):
| return bin((x ^ y)).count('1')
|
'Initialize your data structure here.'
| def __init__(self):
| self.__max_heap = []
self.__min_heap = []
|
'Adds a num into the data structure.
:type num: int
:rtype: void'
| def addNum(self, num):
| if ((not self.__max_heap) or (num > (- self.__max_heap[0]))):
heappush(self.__min_heap, num)
if (len(self.__min_heap) > (len(self.__max_heap) + 1)):
heappush(self.__max_heap, (- heappop(self.__min_heap)))
else:
heappush(self.__max_heap, (- num))
if (len(self.__max_hea... |
'Returns the median of current data stream
:rtype: float'
| def findMedian(self):
| return ((((- self.__max_heap[0]) + self.__min_heap[0]) / 2.0) if (len(self.__min_heap) == len(self.__max_heap)) else self.__min_heap[0])
|
':type s: str
:type k: int
:rtype: int'
| def lengthOfLongestSubstringKDistinct(self, s, k):
| (longest, start, distinct_count, visited) = (0, 0, 0, [0 for _ in xrange(256)])
for (i, char) in enumerate(s):
if (visited[ord(char)] == 0):
distinct_count += 1
visited[ord(char)] += 1
while (distinct_count > k):
visited[ord(s[start])] -= 1
if (visited... |
':type root: TreeNode
:rtype: List[int]'
| def findFrequentTreeSum(self, root):
| def countSubtreeSumHelper(root, counts):
if (not root):
return 0
total = ((root.val + countSubtreeSumHelper(root.left, counts)) + countSubtreeSumHelper(root.right, counts))
counts[total] += 1
return total
counts = collections.defaultdict(int)
countSubtreeSumHelper... |
':type head: ListNode
:rtype: ListNode'
| def deleteDuplicates(self, head):
| dummy = ListNode(0)
(pre, cur) = (dummy, head)
while cur:
if (cur.next and (cur.next.val == cur.val)):
val = cur.val
while (cur and (cur.val == val)):
cur = cur.next
pre.next = cur
else:
pre.next = cur
pre = cur
... |
':type root: TreeNode
:rtype: List[List[int]]'
| def levelOrderBottom(self, root):
| if (root is None):
return []
(result, current) = ([], [root])
while current:
(next_level, vals) = ([], [])
for node in current:
vals.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_lev... |
':type s: str
:type t: str
:rtype: bool'
| def isSubsequence(self, s, t):
| if (not s):
return True
i = 0
for c in t:
if (c == s[i]):
i += 1
if (i == len(s)):
break
return (i == len(s))
|
':type board: List[List[str]]
:rtype: int'
| def countBattleships(self, board):
| if ((not board) or (not board[0])):
return 0
cnt = 0
for i in xrange(len(board)):
for j in xrange(len(board[0])):
cnt += int(((board[i][j] == 'X') and ((i == 0) or (board[(i - 1)][j] != 'X')) and ((j == 0) or (board[i][(j - 1)] != 'X'))))
return cnt
|
':type s: str
:rtype: int'
| def countSubstrings(self, s):
| def manacher(s):
s = (('^#' + '#'.join(s)) + '#$')
P = ([0] * len(s))
(C, R) = (0, 0)
for i in xrange(1, (len(s) - 1)):
i_mirror = ((2 * C) - i)
if (R > i):
P[i] = min((R - i), P[i_mirror])
while (s[((i + 1) + P[i])] == s[((i - 1) -... |
':type matrix: List[List[int]]
:type k: int
:rtype: int'
| def maxSumSubmatrix(self, matrix, k):
| if (not matrix):
return 0
m = min(len(matrix), len(matrix[0]))
n = max(len(matrix), len(matrix[0]))
result = float('-inf')
for i in xrange(m):
sums = ([0] * n)
for j in xrange(i, m):
for l in xrange(n):
sums[l] += (matrix[j][l] if (m == len(matrix)... |
':type matrix: List[List[int]]
:type k: int
:rtype: int'
| def maxSumSubmatrix(self, matrix, k):
| class BST(object, ):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self, val):
curr = self
while curr:
if (curr.val >= val):
if curr.left:
c... |
':type root: TreeNode
:rtype: int'
| def diameterOfBinaryTree(self, root):
| def depth(root, diameter):
if (not root):
return (0, diameter)
(left, diameter) = depth(root.left, diameter)
(right, diameter) = depth(root.right, diameter)
return ((1 + max(left, right)), max(diameter, ((1 + left) + right)))
return (depth(root, 1)[1] - 1)
|
':type nums: List[int]
:type target: int
:rtype: int'
| def threeSumClosest(self, nums, target):
| (nums, result, min_diff, i) = (sorted(nums), float('inf'), float('inf'), 0)
while (i < (len(nums) - 2)):
if ((i == 0) or (nums[i] != nums[(i - 1)])):
(j, k) = ((i + 1), (len(nums) - 1))
while (j < k):
diff = (((nums[i] + nums[j]) + nums[k]) - target)
... |
':type matrix: List[List[int]]
:rtype: int'
| def longestIncreasingPath(self, matrix):
| if (not matrix):
return 0
def longestpath(matrix, i, j, max_lengths):
if max_lengths[i][j]:
return max_lengths[i][j]
max_depth = 0
directions = [(0, (-1)), (0, 1), ((-1), 0), (1, 0)]
for d in directions:
(x, y) = ((i + d[0]), (j + d[1]))
... |
':type n: int
:rtype: int'
| def countNumbersWithUniqueDigits(self, n):
| if (n == 0):
return 1
(count, fk) = (10, 9)
for k in xrange(2, (n + 1)):
fk *= (10 - (k - 1))
count += fk
return count
|
':type str: str
:rtype: bool'
| def repeatedSubstringPattern(self, str):
| def getPrefix(pattern):
prefix = ([(-1)] * len(pattern))
j = (-1)
for i in xrange(1, len(pattern)):
while ((j > (-1)) and (pattern[(j + 1)] != pattern[i])):
j = prefix[j]
if (pattern[(j + 1)] == pattern[i]):
j += 1
prefix[i]... |
':type str: str
:rtype: bool'
| def repeatedSubstringPattern2(self, str):
| if (not str):
return False
ss = (str + str)[1:(-1)]
print ss
return (ss.find(str) != (-1))
|
':type s: str
:rtype: str'
| def reverseVowels(self, s):
| vowels = 'aeiou'
string = list(s)
(i, j) = (0, (len(s) - 1))
while (i < j):
if (string[i].lower() not in vowels):
i += 1
elif (string[j].lower() not in vowels):
j -= 1
else:
(string[i], string[j]) = (string[j], string[i])
i += 1
... |
':type x: int
:rtype: int'
| def reverse(self, x):
| if (x < 0):
return (- self.reverse((- x)))
result = 0
while x:
result = ((result * 10) + (x % 10))
x /= 10
return (result if (result <= 2147483647) else 0)
|
':type x: int
:rtype: int'
| def reverse2(self, x):
| if (x < 0):
x = int((str(x)[::(-1)][(-1)] + str(x)[::(-1)][:(-1)]))
else:
x = int(str(x)[::(-1)])
x = (0 if (abs(x) > 2147483647) else x)
return x
|
':type x: int
:rtype: int'
| def reverse3(self, x):
| s = cmp(x, 0)
r = int(`(s * x)`[::(-1)])
return ((s * r) * (r < (2 ** 31)))
|
':type nums: List[int]
:type target: int
:rtype: int'
| def combinationSum4(self, nums, target):
| dp = ([0] * (target + 1))
dp[0] = 1
nums.sort()
for i in xrange(1, (target + 1)):
for j in xrange(len(nums)):
if (nums[j] <= i):
dp[i] += dp[(i - nums[j])]
else:
break
return dp[target]
|
':type word: str
:rtype: bool'
| def detectCapitalUse(self, word):
| return (word.isupper() or word.islower() or word.istitle())
|
':type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]'
| def multiply(self, A, B):
| (m, n, l) = (len(A), len(A[0]), len(B[0]))
res = [[0 for _ in xrange(l)] for _ in xrange(m)]
for i in xrange(m):
for k in xrange(n):
if A[i][k]:
for j in xrange(l):
res[i][j] += (A[i][k] * B[k][j])
return res
|
':type g: List[int]
:type s: List[int]
:rtype: int'
| def findContentChildren(self, g, s):
| g.sort()
s.sort()
(result, i) = (0, 0)
for j in xrange(len(s)):
if (i == len(g)):
break
if (s[j] >= g[i]):
result += 1
i += 1
return result
|
':type N: int
:rtype: int'
| def maxA(self, N):
| if (N < 7):
return N
if (N == 10):
return 20
n = ((N // 5) + 1)
n3 = (((5 * n) - N) - 1)
n4 = (n - n3)
return ((3 ** n3) * (4 ** n4))
|
':type N: int
:rtype: int'
| def maxA(self, N):
| if (N < 7):
return N
dp = range((N + 1))
for i in xrange(7, (N + 1)):
dp[(i % 6)] = max((dp[((i - 4) % 6)] * 3), (dp[((i - 5) % 6)] * 4))
return dp[(N % 6)]
|
':type num: int
:rtype: str'
| def convertToBase7(self, num):
| if (num < 0):
return ('-' + self.convertToBase7((- num)))
if (num < 7):
return str(num)
return (self.convertToBase7((num // 7)) + str((num % 7)))
|
':type num: int
:rtype: int'
| def findComplement(self, num):
| return (((2 ** (len(bin(num)) - 2)) - 1) - num)
|
':type heightMap: List[List[int]]
:rtype: int'
| def trapRainWater(self, heightMap):
| m = len(heightMap)
if (not m):
return 0
n = len(heightMap[0])
if (not n):
return 0
is_visited = [[False for i in xrange(n)] for j in xrange(m)]
heap = []
for i in xrange(m):
heappush(heap, [heightMap[i][0], i, 0])
is_visited[i][0] = True
heappush(heap,... |
':type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode'
| def addOneRow(self, root, v, d):
| if (d in (0, 1)):
node = TreeNode(v)
if (d == 1):
node.left = root
else:
node.right = root
return node
if (root and (d >= 2)):
root.left = self.addOneRow(root.left, v, ((d - 1) if (d > 2) else 1))
root.right = self.addOneRow(root.right, v, ... |
':type ransomNote: str
:type magazine: str
:rtype: bool'
| def canConstruct(self, ransomNote, magazine):
| counts = ([0] * 26)
letters = 0
for c in ransomNote:
if (counts[(ord(c) - ord('a'))] == 0):
letters += 1
counts[(ord(c) - ord('a'))] += 1
for c in magazine:
counts[(ord(c) - ord('a'))] -= 1
if (counts[(ord(c) - ord('a'))] == 0):
letters -= 1
... |
':type ransomNote: str
:type magazine: str
:rtype: bool'
| def canConstruct(self, ransomNote, magazine):
| return (not (collections.Counter(ransomNote) - collections.Counter(magazine)))
|
':type nums: List[int]
:type m: int
:rtype: int'
| def splitArray(self, nums, m):
| def canSplit(nums, m, s):
(cnt, curr_sum) = (1, 0)
for num in nums:
curr_sum += num
if (curr_sum > s):
curr_sum = num
cnt += 1
return (cnt <= m)
(left, right) = (0, 0)
for num in nums:
left = max(left, num)
right... |
':type matrix: List[List[int]]
:type k: int
:rtype: int'
| def kthSmallest(self, matrix, k):
| kth_smallest = 0
min_heap = []
def push(i, j):
if (len(matrix) > len(matrix[0])):
if ((i < len(matrix[0])) and (j < len(matrix))):
heappush(min_heap, [matrix[j][i], i, j])
elif ((i < len(matrix)) and (j < len(matrix[0]))):
heappush(min_heap, [matrix[i]... |
':type n: int
:rtype: List[str]'
| def fizzBuzz(self, n):
| result = []
for i in xrange(1, (n + 1)):
if ((i % 15) == 0):
result.append('FizzBuzz')
elif ((i % 5) == 0):
result.append('Buzz')
elif ((i % 3) == 0):
result.append('Fizz')
else:
result.append(str(i))
return result
|
':type n: int
:rtype: List[str]'
| def fizzBuzz2(self, n):
| l = [str(x) for x in range((n + 1))]
l3 = range(0, (n + 1), 3)
l5 = range(0, (n + 1), 5)
for i in l3:
l[i] = 'Fizz'
for i in l5:
if (l[i] == 'Fizz'):
l[i] += 'Buzz'
else:
l[i] = 'Buzz'
return l[1:]
|
':type id: int
:type timestamp: str
:rtype: void'
| def put(self, id, timestamp):
| self.__logs.append((id, timestamp))
|
':type s: str
:type e: str
:type gra: str
:rtype: List[int]'
| def retrieve(self, s, e, gra):
| i = self.__granularity[gra]
begin = s[:i]
end = e[:i]
return sorted((id for (id, timestamp) in self.__logs if (begin <= timestamp[:i] <= end)))
|
':type costs: List[List[int]]
:rtype: int'
| def minCost(self, costs):
| if (not costs):
return 0
min_cost = [costs[0], [0, 0, 0]]
n = len(costs)
for i in xrange(1, n):
min_cost[(i % 2)][0] = (costs[i][0] + min(min_cost[((i - 1) % 2)][1], min_cost[((i - 1) % 2)][2]))
min_cost[(i % 2)][1] = (costs[i][1] + min(min_cost[((i - 1) % 2)][0], min_cost[((i - ... |
':type costs: List[List[int]]
:rtype: int'
| def minCost(self, costs):
| if (not costs):
return 0
n = len(costs)
for i in xrange(1, n):
costs[i][0] += min(costs[(i - 1)][1], costs[(i - 1)][2])
costs[i][1] += min(costs[(i - 1)][0], costs[(i - 1)][2])
costs[i][2] += min(costs[(i - 1)][0], costs[(i - 1)][1])
return min(costs[(n - 1)])
|
':type s: TreeNode
:type t: TreeNode
:rtype: bool'
| def isSubtree(self, s, t):
| def isSame(x, y):
if ((not x) and (not y)):
return True
if ((not x) or (not y)):
return False
return ((x.val == y.val) and isSame(x.left, y.left) and isSame(x.right, y.right))
def preOrderTraverse(s, t):
return ((s != None) and (isSame(s, t) or preOrderTra... |
':type matrix: List[List[int]]
:rtype: List[int]'
| def findDiagonalOrder(self, matrix):
| if ((not matrix) or (not matrix[0])):
return []
result = []
(row, col, d) = (0, 0, 0)
dirs = [((-1), 1), (1, (-1))]
for i in xrange((len(matrix) * len(matrix[0]))):
result.append(matrix[row][col])
row += dirs[d][0]
col += dirs[d][1]
if (row >= len(matrix)):
... |
':type nums: List[int]
:type size: int'
| def __init__(self, nums):
| self.__nums = nums
|
'Resets the array to its original configuration and return it.
:rtype: List[int]'
| def reset(self):
| return self.__nums
|
'Returns a random shuffling of the array.
:rtype: List[int]'
| def shuffle(self):
| nums = list(self.__nums)
for i in xrange(len(nums)):
j = random.randint(i, (len(nums) - 1))
(nums[i], nums[j]) = (nums[j], nums[i])
return nums
|
':type s: str
:rtype: int'
| def firstUniqChar(self, s):
| lookup = defaultdict(int)
candidtates = set()
for (i, c) in enumerate(s):
if lookup[c]:
candidtates.discard(lookup[c])
else:
lookup[c] = (i + 1)
candidtates.add((i + 1))
return ((min(candidtates) - 1) if candidtates else (-1))
|
':type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int'
| def shortestDistance(self, maze, start, destination):
| (start, destination) = (tuple(start), tuple(destination))
def neighbors(maze, node):
for dir in [((-1), 0), (0, 1), (0, (-1)), (1, 0)]:
(cur_node, dist) = (list(node), 0)
while ((0 <= (cur_node[0] + dir[0]) < len(maze)) and (0 <= (cur_node[1] + dir[1]) < len(maze[0])) and (not ma... |
':type N: int
:rtype: int'
| def countArrangement(self, N):
| def countArrangementHelper(n, arrangement):
if (n <= 0):
return 1
count = 0
for i in xrange(n):
if (((arrangement[i] % n) == 0) or ((n % arrangement[i]) == 0)):
(arrangement[i], arrangement[(n - 1)]) = (arrangement[(n - 1)], arrangement[i])
... |
':type s: str
:type numRows: int
:rtype: str'
| def convert(self, s, numRows):
| if (numRows == 1):
return s
(step, zigzag) = (((2 * numRows) - 2), '')
for i in xrange(numRows):
for j in xrange(i, len(s), step):
zigzag += s[j]
if ((0 < i < (numRows - 1)) and (((j + step) - (2 * i)) < len(s))):
zigzag += s[((j + step) - (2 * i))]
... |
':type root: TreeNode
:rtype: List[float]'
| def averageOfLevels(self, root):
| result = []
q = collections.deque([root])
while q:
(total, count) = (0, 0)
next_q = collections.deque([])
while q:
n = q.popleft()
total += n.val
count += 1
if n.left:
next_q.append(n.left)
if n.right:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.