repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
akesterson/dpath-python | dpath/util.py | _inner_search | def _inner_search(obj, glob, separator, dirs=True, leaves=False):
"""Search the object paths that match the glob."""
for path in dpath.path.paths(obj, dirs, leaves, skip=True):
if dpath.path.match(path, glob):
yield path | python | def _inner_search(obj, glob, separator, dirs=True, leaves=False):
"""Search the object paths that match the glob."""
for path in dpath.path.paths(obj, dirs, leaves, skip=True):
if dpath.path.match(path, glob):
yield path | [
"def",
"_inner_search",
"(",
"obj",
",",
"glob",
",",
"separator",
",",
"dirs",
"=",
"True",
",",
"leaves",
"=",
"False",
")",
":",
"for",
"path",
"in",
"dpath",
".",
"path",
".",
"paths",
"(",
"obj",
",",
"dirs",
",",
"leaves",
",",
"skip",
"=",
... | Search the object paths that match the glob. | [
"Search",
"the",
"object",
"paths",
"that",
"match",
"the",
"glob",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/util.py#L157-L161 | train | 210,600 |
morse-talk/morse-talk | morse_talk/decoding.py | decode | def decode(code, encoding_type='default'):
"""Converts a string of morse code into English message
The encoded message can also be decoded using the same morse chart
backwards.
>>> code = '... --- ...'
>>> decode(code)
'SOS'
"""
reversed_morsetab = {symbol: character for character,
symbol in list(getattr(encoding, 'morsetab').items())}
encoding_type = encoding_type.lower()
allowed_encoding_type = ['default', 'binary']
if encoding_type == 'default':
# For spacing the words
letters = 0
words = 0
index = {}
for i in range(len(code)):
if code[i:i + 3] == ' ' * 3:
if code[i:i + 7] == ' ' * 7:
words += 1
letters += 1
index[words] = letters
elif code[i + 4] and code[i - 1] != ' ': # Check for ' '
letters += 1
message = [reversed_morsetab[i] for i in code.split()]
for i, (word, letter) in enumerate(list(index.items())):
message.insert(letter + i, ' ')
return ''.join(message)
elif encoding_type == 'binary':
lst = list(map(lambda word: word.split('0' * 3), code.split('0' * 7)))
# list of list of character (each sub list being a word)
for i, word in enumerate(lst):
for j, bin_letter in enumerate(word):
lst[i][j] = binary_lookup[bin_letter]
lst[i] = "".join(lst[i])
s = " ".join(lst)
return s
else:
raise NotImplementedError("encoding_type must be in %s" % allowed_encoding_type) | python | def decode(code, encoding_type='default'):
"""Converts a string of morse code into English message
The encoded message can also be decoded using the same morse chart
backwards.
>>> code = '... --- ...'
>>> decode(code)
'SOS'
"""
reversed_morsetab = {symbol: character for character,
symbol in list(getattr(encoding, 'morsetab').items())}
encoding_type = encoding_type.lower()
allowed_encoding_type = ['default', 'binary']
if encoding_type == 'default':
# For spacing the words
letters = 0
words = 0
index = {}
for i in range(len(code)):
if code[i:i + 3] == ' ' * 3:
if code[i:i + 7] == ' ' * 7:
words += 1
letters += 1
index[words] = letters
elif code[i + 4] and code[i - 1] != ' ': # Check for ' '
letters += 1
message = [reversed_morsetab[i] for i in code.split()]
for i, (word, letter) in enumerate(list(index.items())):
message.insert(letter + i, ' ')
return ''.join(message)
elif encoding_type == 'binary':
lst = list(map(lambda word: word.split('0' * 3), code.split('0' * 7)))
# list of list of character (each sub list being a word)
for i, word in enumerate(lst):
for j, bin_letter in enumerate(word):
lst[i][j] = binary_lookup[bin_letter]
lst[i] = "".join(lst[i])
s = " ".join(lst)
return s
else:
raise NotImplementedError("encoding_type must be in %s" % allowed_encoding_type) | [
"def",
"decode",
"(",
"code",
",",
"encoding_type",
"=",
"'default'",
")",
":",
"reversed_morsetab",
"=",
"{",
"symbol",
":",
"character",
"for",
"character",
",",
"symbol",
"in",
"list",
"(",
"getattr",
"(",
"encoding",
",",
"'morsetab'",
")",
".",
"items... | Converts a string of morse code into English message
The encoded message can also be decoded using the same morse chart
backwards.
>>> code = '... --- ...'
>>> decode(code)
'SOS' | [
"Converts",
"a",
"string",
"of",
"morse",
"code",
"into",
"English",
"message"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/decoding.py#L17-L65 | train | 210,601 |
morse-talk/morse-talk | morse_talk/sound.py | compute_samples | def compute_samples(channels, nsamples=None):
'''
create a generator which computes the samples.
essentially it creates a sequence of the sum of each function in the channel
at each sample in the file for each channel.
'''
return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)), nsamples) | python | def compute_samples(channels, nsamples=None):
'''
create a generator which computes the samples.
essentially it creates a sequence of the sum of each function in the channel
at each sample in the file for each channel.
'''
return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)), nsamples) | [
"def",
"compute_samples",
"(",
"channels",
",",
"nsamples",
"=",
"None",
")",
":",
"return",
"islice",
"(",
"izip",
"(",
"*",
"(",
"imap",
"(",
"sum",
",",
"izip",
"(",
"*",
"channel",
")",
")",
"for",
"channel",
"in",
"channels",
")",
")",
",",
"n... | create a generator which computes the samples.
essentially it creates a sequence of the sum of each function in the channel
at each sample in the file for each channel. | [
"create",
"a",
"generator",
"which",
"computes",
"the",
"samples",
".",
"essentially",
"it",
"creates",
"a",
"sequence",
"of",
"the",
"sum",
"of",
"each",
"function",
"in",
"the",
"channel",
"at",
"each",
"sample",
"in",
"the",
"file",
"for",
"each",
"chan... | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/sound.py#L41-L47 | train | 210,602 |
morse-talk/morse-talk | morse_talk/sound.py | write_wavefile | def write_wavefile(f, samples, nframes=None, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048):
"Write samples to a wavefile."
if nframes is None:
nframes = 0
w = wave.open(f, 'wb')
w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed'))
max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)
# split the samples into chunks (to reduce memory consumption and improve performance)
for chunk in grouper(bufsize, samples):
frames = b''.join(b''.join(struct.pack('h', int(max_amplitude * sample)) for sample in channels) for channels in chunk if channels is not None)
w.writeframesraw(frames)
w.close() | python | def write_wavefile(f, samples, nframes=None, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048):
"Write samples to a wavefile."
if nframes is None:
nframes = 0
w = wave.open(f, 'wb')
w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed'))
max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)
# split the samples into chunks (to reduce memory consumption and improve performance)
for chunk in grouper(bufsize, samples):
frames = b''.join(b''.join(struct.pack('h', int(max_amplitude * sample)) for sample in channels) for channels in chunk if channels is not None)
w.writeframesraw(frames)
w.close() | [
"def",
"write_wavefile",
"(",
"f",
",",
"samples",
",",
"nframes",
"=",
"None",
",",
"nchannels",
"=",
"2",
",",
"sampwidth",
"=",
"2",
",",
"framerate",
"=",
"44100",
",",
"bufsize",
"=",
"2048",
")",
":",
"if",
"nframes",
"is",
"None",
":",
"nframe... | Write samples to a wavefile. | [
"Write",
"samples",
"to",
"a",
"wavefile",
"."
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/sound.py#L50-L65 | train | 210,603 |
morse-talk/morse-talk | morse_talk/sound.py | sine_wave | def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE):
"""
Returns value of a sine wave at a given frequency and framerate
for a given sample i
"""
omega = 2.0 * pi * float(frequency)
sine = sin(omega * (float(i) / float(framerate)))
return float(amplitude) * sine | python | def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE):
"""
Returns value of a sine wave at a given frequency and framerate
for a given sample i
"""
omega = 2.0 * pi * float(frequency)
sine = sin(omega * (float(i) / float(framerate)))
return float(amplitude) * sine | [
"def",
"sine_wave",
"(",
"i",
",",
"frequency",
"=",
"FREQUENCY",
",",
"framerate",
"=",
"FRAMERATE",
",",
"amplitude",
"=",
"AMPLITUDE",
")",
":",
"omega",
"=",
"2.0",
"*",
"pi",
"*",
"float",
"(",
"frequency",
")",
"sine",
"=",
"sin",
"(",
"omega",
... | Returns value of a sine wave at a given frequency and framerate
for a given sample i | [
"Returns",
"value",
"of",
"a",
"sine",
"wave",
"at",
"a",
"given",
"frequency",
"and",
"framerate",
"for",
"a",
"given",
"sample",
"i"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/sound.py#L68-L75 | train | 210,604 |
morse-talk/morse-talk | morse_talk/sound.py | generate_wave | def generate_wave(message, wpm=WPM, framerate=FRAMERATE, skip_frame=0, amplitude=AMPLITUDE, frequency=FREQUENCY, word_ref=WORD):
"""
Generate binary Morse code of message at a given code speed wpm and framerate
Parameters
----------
word : string
wpm : int or float - word per minute
framerate : nb of samples / seconds
word_spaced : bool - calculate with spaces between 2 words (default is False)
skip_frame : int - nb of frame to skip
Returns
-------
value : float
"""
lst_bin = _encode_binary(message)
if amplitude > 1.0:
amplitude = 1.0
if amplitude < 0.0:
amplitude = 0.0
seconds_per_dot = _seconds_per_dot(word_ref) # =1.2
for i in count(skip_frame):
bit = morse_bin(i=i, lst_bin=lst_bin, wpm=wpm, framerate=framerate, default_value=0.0, seconds_per_dot=seconds_per_dot)
sine = sine_wave(i=i, frequency=frequency, framerate=framerate, amplitude=amplitude)
yield sine * bit | python | def generate_wave(message, wpm=WPM, framerate=FRAMERATE, skip_frame=0, amplitude=AMPLITUDE, frequency=FREQUENCY, word_ref=WORD):
"""
Generate binary Morse code of message at a given code speed wpm and framerate
Parameters
----------
word : string
wpm : int or float - word per minute
framerate : nb of samples / seconds
word_spaced : bool - calculate with spaces between 2 words (default is False)
skip_frame : int - nb of frame to skip
Returns
-------
value : float
"""
lst_bin = _encode_binary(message)
if amplitude > 1.0:
amplitude = 1.0
if amplitude < 0.0:
amplitude = 0.0
seconds_per_dot = _seconds_per_dot(word_ref) # =1.2
for i in count(skip_frame):
bit = morse_bin(i=i, lst_bin=lst_bin, wpm=wpm, framerate=framerate, default_value=0.0, seconds_per_dot=seconds_per_dot)
sine = sine_wave(i=i, frequency=frequency, framerate=framerate, amplitude=amplitude)
yield sine * bit | [
"def",
"generate_wave",
"(",
"message",
",",
"wpm",
"=",
"WPM",
",",
"framerate",
"=",
"FRAMERATE",
",",
"skip_frame",
"=",
"0",
",",
"amplitude",
"=",
"AMPLITUDE",
",",
"frequency",
"=",
"FREQUENCY",
",",
"word_ref",
"=",
"WORD",
")",
":",
"lst_bin",
"=... | Generate binary Morse code of message at a given code speed wpm and framerate
Parameters
----------
word : string
wpm : int or float - word per minute
framerate : nb of samples / seconds
word_spaced : bool - calculate with spaces between 2 words (default is False)
skip_frame : int - nb of frame to skip
Returns
-------
value : float | [
"Generate",
"binary",
"Morse",
"code",
"of",
"message",
"at",
"a",
"given",
"code",
"speed",
"wpm",
"and",
"framerate"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/sound.py#L78-L104 | train | 210,605 |
morse-talk/morse-talk | morse_talk/encoding.py | encode | def encode(message, encoding_type='default', letter_sep=' ' * 3, strip=True):
"""Converts a string of message into morse
Two types of marks are there. One is short mark, dot(.) or "dit" and
other is long mark, dash(-) or "dah". After every dit or dah, there is
a one dot duration or one unit log gap.
Between every letter, there is a short gap (three units long).
Between every word, there is a medium gap (seven units long).
When encoding is changed to binary, the short mark(dot) is denoted by 1
and the long mark(dash) is denoted by 111. The intra character gap between
letters is represented by 0.
The short gap is represented by 000 and the medium gap by 0000000.
>>> message = "SOS"
>>> encode(message)
'... --- ...'
>>> message = " SOS"
>>> encode(message, strip=False)
' ... --- ...'
Parameters
----------
message : String
encoding : Type of encoding
Supported types are default(morse) and binary.
Returns
-------
encoded_message : String
"""
if strip:
message = message.strip() # No trailing or leading spaces
encoding_type = encoding_type.lower()
allowed_encoding_type = ['default', 'binary']
if encoding_type == 'default':
return _encode_to_morse_string(message, letter_sep)
elif encoding_type == 'binary':
return _encode_to_binary_string(message, on='1', off='0')
else:
raise NotImplementedError("encoding_type must be in %s" % allowed_encoding_type) | python | def encode(message, encoding_type='default', letter_sep=' ' * 3, strip=True):
"""Converts a string of message into morse
Two types of marks are there. One is short mark, dot(.) or "dit" and
other is long mark, dash(-) or "dah". After every dit or dah, there is
a one dot duration or one unit log gap.
Between every letter, there is a short gap (three units long).
Between every word, there is a medium gap (seven units long).
When encoding is changed to binary, the short mark(dot) is denoted by 1
and the long mark(dash) is denoted by 111. The intra character gap between
letters is represented by 0.
The short gap is represented by 000 and the medium gap by 0000000.
>>> message = "SOS"
>>> encode(message)
'... --- ...'
>>> message = " SOS"
>>> encode(message, strip=False)
' ... --- ...'
Parameters
----------
message : String
encoding : Type of encoding
Supported types are default(morse) and binary.
Returns
-------
encoded_message : String
"""
if strip:
message = message.strip() # No trailing or leading spaces
encoding_type = encoding_type.lower()
allowed_encoding_type = ['default', 'binary']
if encoding_type == 'default':
return _encode_to_morse_string(message, letter_sep)
elif encoding_type == 'binary':
return _encode_to_binary_string(message, on='1', off='0')
else:
raise NotImplementedError("encoding_type must be in %s" % allowed_encoding_type) | [
"def",
"encode",
"(",
"message",
",",
"encoding_type",
"=",
"'default'",
",",
"letter_sep",
"=",
"' '",
"*",
"3",
",",
"strip",
"=",
"True",
")",
":",
"if",
"strip",
":",
"message",
"=",
"message",
".",
"strip",
"(",
")",
"# No trailing or leading spaces",... | Converts a string of message into morse
Two types of marks are there. One is short mark, dot(.) or "dit" and
other is long mark, dash(-) or "dah". After every dit or dah, there is
a one dot duration or one unit log gap.
Between every letter, there is a short gap (three units long).
Between every word, there is a medium gap (seven units long).
When encoding is changed to binary, the short mark(dot) is denoted by 1
and the long mark(dash) is denoted by 111. The intra character gap between
letters is represented by 0.
The short gap is represented by 000 and the medium gap by 0000000.
>>> message = "SOS"
>>> encode(message)
'... --- ...'
>>> message = " SOS"
>>> encode(message, strip=False)
' ... --- ...'
Parameters
----------
message : String
encoding : Type of encoding
Supported types are default(morse) and binary.
Returns
-------
encoded_message : String | [
"Converts",
"a",
"string",
"of",
"message",
"into",
"morse"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/encoding.py#L145-L191 | train | 210,606 |
morse-talk/morse-talk | morse_talk/plot.py | plot | def plot(message, duration=1, ax=None):
"""
Plot a message
Returns: ax a Matplotlib Axe
"""
lst_bin = _encode_binary(message)
x, y = _create_x_y(lst_bin, duration)
ax = _create_ax(ax)
ax.plot(x, y, linewidth=2.0)
delta_y = 0.1
ax.set_ylim(-delta_y, 1 + delta_y)
ax.set_yticks([0, 1])
delta_x = 0.5 * duration
ax.set_xlim(-delta_x, len(lst_bin) * duration + delta_x)
return ax | python | def plot(message, duration=1, ax=None):
"""
Plot a message
Returns: ax a Matplotlib Axe
"""
lst_bin = _encode_binary(message)
x, y = _create_x_y(lst_bin, duration)
ax = _create_ax(ax)
ax.plot(x, y, linewidth=2.0)
delta_y = 0.1
ax.set_ylim(-delta_y, 1 + delta_y)
ax.set_yticks([0, 1])
delta_x = 0.5 * duration
ax.set_xlim(-delta_x, len(lst_bin) * duration + delta_x)
return ax | [
"def",
"plot",
"(",
"message",
",",
"duration",
"=",
"1",
",",
"ax",
"=",
"None",
")",
":",
"lst_bin",
"=",
"_encode_binary",
"(",
"message",
")",
"x",
",",
"y",
"=",
"_create_x_y",
"(",
"lst_bin",
",",
"duration",
")",
"ax",
"=",
"_create_ax",
"(",
... | Plot a message
Returns: ax a Matplotlib Axe | [
"Plot",
"a",
"message"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/plot.py#L56-L71 | train | 210,607 |
morse-talk/morse-talk | morse_talk/utils.py | _repeat_word | def _repeat_word(word, N, word_space=" "):
"""
Return a repeated string
>>> word = "PARIS"
>>> _repeat_word(word, 5)
'PARIS PARIS PARIS PARIS PARIS'
>>> _repeat_word(word, 5, word_space="")
'PARISPARISPARISPARISPARIS'
"""
message = (word_space + word) * N
message = message[len(word_space):]
return message | python | def _repeat_word(word, N, word_space=" "):
"""
Return a repeated string
>>> word = "PARIS"
>>> _repeat_word(word, 5)
'PARIS PARIS PARIS PARIS PARIS'
>>> _repeat_word(word, 5, word_space="")
'PARISPARISPARISPARISPARIS'
"""
message = (word_space + word) * N
message = message[len(word_space):]
return message | [
"def",
"_repeat_word",
"(",
"word",
",",
"N",
",",
"word_space",
"=",
"\" \"",
")",
":",
"message",
"=",
"(",
"word_space",
"+",
"word",
")",
"*",
"N",
"message",
"=",
"message",
"[",
"len",
"(",
"word_space",
")",
":",
"]",
"return",
"message"
] | Return a repeated string
>>> word = "PARIS"
>>> _repeat_word(word, 5)
'PARIS PARIS PARIS PARIS PARIS'
>>> _repeat_word(word, 5, word_space="")
'PARISPARISPARISPARISPARIS' | [
"Return",
"a",
"repeated",
"string"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/utils.py#L27-L41 | train | 210,608 |
morse-talk/morse-talk | morse_talk/utils.py | mlength | def mlength(message, N=1, word_spaced=True):
"""
Returns Morse length
>>> message = "PARIS"
>>> mlength(message)
50
>>> mlength(message, 5)
250
"""
message = _repeat_word(message, N)
if word_spaced:
message = message + " E"
lst_bin = _encode_binary(message)
N = len(lst_bin)
if word_spaced:
N -= 1 # E is one "dit" so we remove it
return N | python | def mlength(message, N=1, word_spaced=True):
"""
Returns Morse length
>>> message = "PARIS"
>>> mlength(message)
50
>>> mlength(message, 5)
250
"""
message = _repeat_word(message, N)
if word_spaced:
message = message + " E"
lst_bin = _encode_binary(message)
N = len(lst_bin)
if word_spaced:
N -= 1 # E is one "dit" so we remove it
return N | [
"def",
"mlength",
"(",
"message",
",",
"N",
"=",
"1",
",",
"word_spaced",
"=",
"True",
")",
":",
"message",
"=",
"_repeat_word",
"(",
"message",
",",
"N",
")",
"if",
"word_spaced",
":",
"message",
"=",
"message",
"+",
"\" E\"",
"lst_bin",
"=",
"_encode... | Returns Morse length
>>> message = "PARIS"
>>> mlength(message)
50
>>> mlength(message, 5)
250 | [
"Returns",
"Morse",
"length"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/utils.py#L44-L61 | train | 210,609 |
morse-talk/morse-talk | morse_talk/utils.py | _timing_representation | def _timing_representation(message):
"""
Returns timing representation of a message like
1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
M------ O---------- R------ S---- E C---------- O---------- D------ E
===.===...===.===.===...=.===.=...=.=.=...=.......===.=.===.=...===.===.===...===.=.=...=
spoken reprentation:
M O R S E C O D E
-- --- .-. ... . (space) -.-. --- -.. .
"""
s = _encode_to_binary_string(message, on="=", off=".")
N = len(s)
s += '\n' + _numbers_decades(N)
s += '\n' + _numbers_units(N)
s += '\n'
s += '\n' + _timing_char(message)
return s | python | def _timing_representation(message):
"""
Returns timing representation of a message like
1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
M------ O---------- R------ S---- E C---------- O---------- D------ E
===.===...===.===.===...=.===.=...=.=.=...=.......===.=.===.=...===.===.===...===.=.=...=
spoken reprentation:
M O R S E C O D E
-- --- .-. ... . (space) -.-. --- -.. .
"""
s = _encode_to_binary_string(message, on="=", off=".")
N = len(s)
s += '\n' + _numbers_decades(N)
s += '\n' + _numbers_units(N)
s += '\n'
s += '\n' + _timing_char(message)
return s | [
"def",
"_timing_representation",
"(",
"message",
")",
":",
"s",
"=",
"_encode_to_binary_string",
"(",
"message",
",",
"on",
"=",
"\"=\"",
",",
"off",
"=",
"\".\"",
")",
"N",
"=",
"len",
"(",
"s",
")",
"s",
"+=",
"'\\n'",
"+",
"_numbers_decades",
"(",
"... | Returns timing representation of a message like
1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
M------ O---------- R------ S---- E C---------- O---------- D------ E
===.===...===.===.===...=.===.=...=.=.=...=.......===.=.===.=...===.===.===...===.=.=...=
spoken reprentation:
M O R S E C O D E
-- --- .-. ... . (space) -.-. --- -.. . | [
"Returns",
"timing",
"representation",
"of",
"a",
"message",
"like"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/utils.py#L253-L273 | train | 210,610 |
morse-talk/morse-talk | morse_talk/utils.py | display | def display(message, wpm, element_duration, word_ref, strip=False):
"""
Display
text message
morse code
binary morse code
"""
fmt = "{0:>8s}: '{1}'"
key = "text"
if strip:
print(fmt.format(key, message.strip()))
else:
print(fmt.format(key, message.strip()))
print(fmt.format("morse", mtalk.encode(message, strip=strip)))
print(fmt.format("bin", mtalk.encode(message, encoding_type='binary', strip=strip)))
print("")
print("{0:>8s}:".format("timing"))
print(_timing_representation(message))
print("")
print("{0:>8s}:".format("spoken reprentation"))
print(_spoken_representation(message))
print("")
print("code speed : %s wpm" % wpm)
print("element_duration : %s s" % element_duration)
print("reference word : %r" % word_ref)
print("") | python | def display(message, wpm, element_duration, word_ref, strip=False):
"""
Display
text message
morse code
binary morse code
"""
fmt = "{0:>8s}: '{1}'"
key = "text"
if strip:
print(fmt.format(key, message.strip()))
else:
print(fmt.format(key, message.strip()))
print(fmt.format("morse", mtalk.encode(message, strip=strip)))
print(fmt.format("bin", mtalk.encode(message, encoding_type='binary', strip=strip)))
print("")
print("{0:>8s}:".format("timing"))
print(_timing_representation(message))
print("")
print("{0:>8s}:".format("spoken reprentation"))
print(_spoken_representation(message))
print("")
print("code speed : %s wpm" % wpm)
print("element_duration : %s s" % element_duration)
print("reference word : %r" % word_ref)
print("") | [
"def",
"display",
"(",
"message",
",",
"wpm",
",",
"element_duration",
",",
"word_ref",
",",
"strip",
"=",
"False",
")",
":",
"fmt",
"=",
"\"{0:>8s}: '{1}'\"",
"key",
"=",
"\"text\"",
"if",
"strip",
":",
"print",
"(",
"fmt",
".",
"format",
"(",
"key",
... | Display
text message
morse code
binary morse code | [
"Display",
"text",
"message",
"morse",
"code",
"binary",
"morse",
"code"
] | 71e09ace0aa554d28cada5ee658e43758305b8fa | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/utils.py#L371-L396 | train | 210,611 |
MattParr/python-atws | atws/picklist.py | FieldPicklist.lookup | def lookup(self, label):
''' take a field_name_label and return the id'''
if self.is_child:
try:
return self._children[label]
except KeyError:
self._children[label] = ChildFieldPicklist(self.parent,
label,
self.field_name)
return self._children[label]
else:
return get_label_value(label, self._picklist) | python | def lookup(self, label):
''' take a field_name_label and return the id'''
if self.is_child:
try:
return self._children[label]
except KeyError:
self._children[label] = ChildFieldPicklist(self.parent,
label,
self.field_name)
return self._children[label]
else:
return get_label_value(label, self._picklist) | [
"def",
"lookup",
"(",
"self",
",",
"label",
")",
":",
"if",
"self",
".",
"is_child",
":",
"try",
":",
"return",
"self",
".",
"_children",
"[",
"label",
"]",
"except",
"KeyError",
":",
"self",
".",
"_children",
"[",
"label",
"]",
"=",
"ChildFieldPicklis... | take a field_name_label and return the id | [
"take",
"a",
"field_name_label",
"and",
"return",
"the",
"id"
] | 2128baf85d00dcc290ecf911d6c636ac0abe5f33 | https://github.com/MattParr/python-atws/blob/2128baf85d00dcc290ecf911d6c636ac0abe5f33/atws/picklist.py#L208-L219 | train | 210,612 |
MattParr/python-atws | atws/picklist.py | FieldPicklist.reverse_lookup | def reverse_lookup(self, value, condition=is_active):
''' take a field_name_id and return the label '''
label = get_value_label(value, self._picklist, condition=condition)
return label | python | def reverse_lookup(self, value, condition=is_active):
''' take a field_name_id and return the label '''
label = get_value_label(value, self._picklist, condition=condition)
return label | [
"def",
"reverse_lookup",
"(",
"self",
",",
"value",
",",
"condition",
"=",
"is_active",
")",
":",
"label",
"=",
"get_value_label",
"(",
"value",
",",
"self",
".",
"_picklist",
",",
"condition",
"=",
"condition",
")",
"return",
"label"
] | take a field_name_id and return the label | [
"take",
"a",
"field_name_id",
"and",
"return",
"the",
"label"
] | 2128baf85d00dcc290ecf911d6c636ac0abe5f33 | https://github.com/MattParr/python-atws/blob/2128baf85d00dcc290ecf911d6c636ac0abe5f33/atws/picklist.py#L222-L225 | train | 210,613 |
treethought/flask-assistant | flask_assistant/response.py | build_item | def build_item(
title, key=None, synonyms=None, description=None, img_url=None, alt_text=None
):
"""Builds an item that may be added to List or Carousel"""
item = {
"info": {"key": key or title, "synonyms": synonyms or []},
"title": title,
"description": description,
"image": {
"imageUri": img_url or "",
"accessibilityText": alt_text or "{} img".format(title),
},
}
return item | python | def build_item(
title, key=None, synonyms=None, description=None, img_url=None, alt_text=None
):
"""Builds an item that may be added to List or Carousel"""
item = {
"info": {"key": key or title, "synonyms": synonyms or []},
"title": title,
"description": description,
"image": {
"imageUri": img_url or "",
"accessibilityText": alt_text or "{} img".format(title),
},
}
return item | [
"def",
"build_item",
"(",
"title",
",",
"key",
"=",
"None",
",",
"synonyms",
"=",
"None",
",",
"description",
"=",
"None",
",",
"img_url",
"=",
"None",
",",
"alt_text",
"=",
"None",
")",
":",
"item",
"=",
"{",
"\"info\"",
":",
"{",
"\"key\"",
":",
... | Builds an item that may be added to List or Carousel | [
"Builds",
"an",
"item",
"that",
"may",
"be",
"added",
"to",
"List",
"or",
"Carousel"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/response.py#L201-L214 | train | 210,614 |
treethought/flask-assistant | flask_assistant/response.py | _Response.suggest | def suggest(self, *replies):
"""Use suggestion chips to hint at responses to continue or pivot the conversation"""
chips = []
for r in replies:
chips.append({"title": r})
# NOTE: both of these formats work in the dialogflow console,
# but only the first (suggestions) appears in actual Google Assistant
# native chips for GA
self._messages.append(
{"platform": "ACTIONS_ON_GOOGLE", "suggestions": {"suggestions": chips}}
)
# # quick replies for other platforms
# self._messages.append(
# {
# "platform": "ACTIONS_ON_GOOGLE",
# "quickReplies": {"title": None, "quickReplies": replies},
# }
# )
return self | python | def suggest(self, *replies):
"""Use suggestion chips to hint at responses to continue or pivot the conversation"""
chips = []
for r in replies:
chips.append({"title": r})
# NOTE: both of these formats work in the dialogflow console,
# but only the first (suggestions) appears in actual Google Assistant
# native chips for GA
self._messages.append(
{"platform": "ACTIONS_ON_GOOGLE", "suggestions": {"suggestions": chips}}
)
# # quick replies for other platforms
# self._messages.append(
# {
# "platform": "ACTIONS_ON_GOOGLE",
# "quickReplies": {"title": None, "quickReplies": replies},
# }
# )
return self | [
"def",
"suggest",
"(",
"self",
",",
"*",
"replies",
")",
":",
"chips",
"=",
"[",
"]",
"for",
"r",
"in",
"replies",
":",
"chips",
".",
"append",
"(",
"{",
"\"title\"",
":",
"r",
"}",
")",
"# NOTE: both of these formats work in the dialogflow console,",
"# but... | Use suggestion chips to hint at responses to continue or pivot the conversation | [
"Use",
"suggestion",
"chips",
"to",
"hint",
"at",
"responses",
"to",
"continue",
"or",
"pivot",
"the",
"conversation"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/response.py#L99-L121 | train | 210,615 |
treethought/flask-assistant | flask_assistant/response.py | _Response.link_out | def link_out(self, name, url):
"""Presents a chip similar to suggestion, but instead links to a url"""
self._messages.append(
{
"platform": "ACTIONS_ON_GOOGLE",
"linkOutSuggestion": {"destinationName": name, "uri": url},
}
)
return self | python | def link_out(self, name, url):
"""Presents a chip similar to suggestion, but instead links to a url"""
self._messages.append(
{
"platform": "ACTIONS_ON_GOOGLE",
"linkOutSuggestion": {"destinationName": name, "uri": url},
}
)
return self | [
"def",
"link_out",
"(",
"self",
",",
"name",
",",
"url",
")",
":",
"self",
".",
"_messages",
".",
"append",
"(",
"{",
"\"platform\"",
":",
"\"ACTIONS_ON_GOOGLE\"",
",",
"\"linkOutSuggestion\"",
":",
"{",
"\"destinationName\"",
":",
"name",
",",
"\"uri\"",
":... | Presents a chip similar to suggestion, but instead links to a url | [
"Presents",
"a",
"chip",
"similar",
"to",
"suggestion",
"but",
"instead",
"links",
"to",
"a",
"url"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/response.py#L123-L132 | train | 210,616 |
treethought/flask-assistant | flask_assistant/response.py | _Response.build_list | def build_list(self, title=None, items=None):
"""Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and does not modify the existing response object
Therefore, to add items, must be assigned to new variable
or call the method directly after initializing list
example usage:
simple = ask('I speak this text')
mylist = simple.build_list('List Title')
mylist.add_item('Item1', 'key1')
mylist.add_item('Item2', 'key2')
return mylist
Arguments:
title {str} -- Title displayed at top of list card
Returns:
_ListSelector -- [_Response object exposing the add_item method]
"""
list_card = _ListSelector(
self._speech, display_text=self._display_text, title=title, items=items
)
return list_card | python | def build_list(self, title=None, items=None):
"""Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and does not modify the existing response object
Therefore, to add items, must be assigned to new variable
or call the method directly after initializing list
example usage:
simple = ask('I speak this text')
mylist = simple.build_list('List Title')
mylist.add_item('Item1', 'key1')
mylist.add_item('Item2', 'key2')
return mylist
Arguments:
title {str} -- Title displayed at top of list card
Returns:
_ListSelector -- [_Response object exposing the add_item method]
"""
list_card = _ListSelector(
self._speech, display_text=self._display_text, title=title, items=items
)
return list_card | [
"def",
"build_list",
"(",
"self",
",",
"title",
"=",
"None",
",",
"items",
"=",
"None",
")",
":",
"list_card",
"=",
"_ListSelector",
"(",
"self",
".",
"_speech",
",",
"display_text",
"=",
"self",
".",
"_display_text",
",",
"title",
"=",
"title",
",",
"... | Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and does not modify the existing response object
Therefore, to add items, must be assigned to new variable
or call the method directly after initializing list
example usage:
simple = ask('I speak this text')
mylist = simple.build_list('List Title')
mylist.add_item('Item1', 'key1')
mylist.add_item('Item2', 'key2')
return mylist
Arguments:
title {str} -- Title displayed at top of list card
Returns:
_ListSelector -- [_Response object exposing the add_item method] | [
"Presents",
"the",
"user",
"with",
"a",
"vertical",
"list",
"of",
"multiple",
"items",
"."
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/response.py#L161-L192 | train | 210,617 |
treethought/flask-assistant | flask_assistant/response.py | _CardWithItems.add_item | def add_item(self, title, key, synonyms=None, description=None, img_url=None):
"""Adds item to a list or carousel card.
A list must contain at least 2 items, each requiring a title and object key.
Arguments:
title {str} -- Name of the item object
key {str} -- Key refering to the item.
This string will be used to send a query to your app if selected
Keyword Arguments:
synonyms {list} -- Words and phrases the user may send to select the item
(default: {None})
description {str} -- A description of the item (default: {None})
img_url {str} -- URL of the image to represent the item (default: {None})
"""
item = build_item(title, key, synonyms, description, img_url)
self._items.append(item)
return self | python | def add_item(self, title, key, synonyms=None, description=None, img_url=None):
"""Adds item to a list or carousel card.
A list must contain at least 2 items, each requiring a title and object key.
Arguments:
title {str} -- Name of the item object
key {str} -- Key refering to the item.
This string will be used to send a query to your app if selected
Keyword Arguments:
synonyms {list} -- Words and phrases the user may send to select the item
(default: {None})
description {str} -- A description of the item (default: {None})
img_url {str} -- URL of the image to represent the item (default: {None})
"""
item = build_item(title, key, synonyms, description, img_url)
self._items.append(item)
return self | [
"def",
"add_item",
"(",
"self",
",",
"title",
",",
"key",
",",
"synonyms",
"=",
"None",
",",
"description",
"=",
"None",
",",
"img_url",
"=",
"None",
")",
":",
"item",
"=",
"build_item",
"(",
"title",
",",
"key",
",",
"synonyms",
",",
"description",
... | Adds item to a list or carousel card.
A list must contain at least 2 items, each requiring a title and object key.
Arguments:
title {str} -- Name of the item object
key {str} -- Key refering to the item.
This string will be used to send a query to your app if selected
Keyword Arguments:
synonyms {list} -- Words and phrases the user may send to select the item
(default: {None})
description {str} -- A description of the item (default: {None})
img_url {str} -- URL of the image to represent the item (default: {None}) | [
"Adds",
"item",
"to",
"a",
"list",
"or",
"carousel",
"card",
"."
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/response.py#L231-L249 | train | 210,618 |
treethought/flask-assistant | api_ai/api.py | ApiAi.get_intent | def get_intent(self, intent_id):
"""Returns the intent object with the given intent_id"""
endpoint = self._intent_uri(intent_id=intent_id)
return self._get(endpoint) | python | def get_intent(self, intent_id):
"""Returns the intent object with the given intent_id"""
endpoint = self._intent_uri(intent_id=intent_id)
return self._get(endpoint) | [
"def",
"get_intent",
"(",
"self",
",",
"intent_id",
")",
":",
"endpoint",
"=",
"self",
".",
"_intent_uri",
"(",
"intent_id",
"=",
"intent_id",
")",
"return",
"self",
".",
"_get",
"(",
"endpoint",
")"
] | Returns the intent object with the given intent_id | [
"Returns",
"the",
"intent",
"object",
"with",
"the",
"given",
"intent_id"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/api.py#L86-L89 | train | 210,619 |
treethought/flask-assistant | api_ai/api.py | ApiAi.post_intent | def post_intent(self, intent_json):
"""Sends post request to create a new intent"""
endpoint = self._intent_uri()
return self._post(endpoint, data=intent_json) | python | def post_intent(self, intent_json):
"""Sends post request to create a new intent"""
endpoint = self._intent_uri()
return self._post(endpoint, data=intent_json) | [
"def",
"post_intent",
"(",
"self",
",",
"intent_json",
")",
":",
"endpoint",
"=",
"self",
".",
"_intent_uri",
"(",
")",
"return",
"self",
".",
"_post",
"(",
"endpoint",
",",
"data",
"=",
"intent_json",
")"
] | Sends post request to create a new intent | [
"Sends",
"post",
"request",
"to",
"create",
"a",
"new",
"intent"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/api.py#L91-L94 | train | 210,620 |
treethought/flask-assistant | api_ai/api.py | ApiAi.put_intent | def put_intent(self, intent_id, intent_json):
"""Send a put request to update the intent with intent_id"""
endpoint = self._intent_uri(intent_id)
return self._put(endpoint, intent_json) | python | def put_intent(self, intent_id, intent_json):
"""Send a put request to update the intent with intent_id"""
endpoint = self._intent_uri(intent_id)
return self._put(endpoint, intent_json) | [
"def",
"put_intent",
"(",
"self",
",",
"intent_id",
",",
"intent_json",
")",
":",
"endpoint",
"=",
"self",
".",
"_intent_uri",
"(",
"intent_id",
")",
"return",
"self",
".",
"_put",
"(",
"endpoint",
",",
"intent_json",
")"
] | Send a put request to update the intent with intent_id | [
"Send",
"a",
"put",
"request",
"to",
"update",
"the",
"intent",
"with",
"intent_id"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/api.py#L96-L99 | train | 210,621 |
treethought/flask-assistant | flask_assistant/core.py | find_assistant | def find_assistant(): # Taken from Flask-ask courtesy of @voutilad
"""
Find our instance of Assistant, navigating Local's and possible blueprints.
Note: This only supports returning a reference to the first instance
of Assistant found.
"""
if hasattr(current_app, "assist"):
return getattr(current_app, "assist")
else:
if hasattr(current_app, "blueprints"):
blueprints = getattr(current_app, "blueprints")
for blueprint_name in blueprints:
if hasattr(blueprints[blueprint_name], "assist"):
return getattr(blueprints[blueprint_name], "assist") | python | def find_assistant(): # Taken from Flask-ask courtesy of @voutilad
"""
Find our instance of Assistant, navigating Local's and possible blueprints.
Note: This only supports returning a reference to the first instance
of Assistant found.
"""
if hasattr(current_app, "assist"):
return getattr(current_app, "assist")
else:
if hasattr(current_app, "blueprints"):
blueprints = getattr(current_app, "blueprints")
for blueprint_name in blueprints:
if hasattr(blueprints[blueprint_name], "assist"):
return getattr(blueprints[blueprint_name], "assist") | [
"def",
"find_assistant",
"(",
")",
":",
"# Taken from Flask-ask courtesy of @voutilad",
"if",
"hasattr",
"(",
"current_app",
",",
"\"assist\"",
")",
":",
"return",
"getattr",
"(",
"current_app",
",",
"\"assist\"",
")",
"else",
":",
"if",
"hasattr",
"(",
"current_a... | Find our instance of Assistant, navigating Local's and possible blueprints.
Note: This only supports returning a reference to the first instance
of Assistant found. | [
"Find",
"our",
"instance",
"of",
"Assistant",
"navigating",
"Local",
"s",
"and",
"possible",
"blueprints",
"."
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/core.py#L17-L31 | train | 210,622 |
treethought/flask-assistant | flask_assistant/core.py | Assistant.action | def action(
self,
intent_name,
is_fallback=False,
mapping={},
convert={},
default={},
with_context=[],
events=[],
*args,
**kw
):
"""Decorates an intent_name's Action view function.
The wrapped function is called when a request with the
given intent_name is recieved along with all required parameters.
"""
def decorator(f):
action_funcs = self._intent_action_funcs.get(intent_name, [])
action_funcs.append(f)
self._intent_action_funcs[intent_name] = action_funcs
self._intent_mappings[intent_name] = mapping
self._intent_converts[intent_name] = convert
self._intent_defaults[intent_name] = default
self._intent_fallbacks[intent_name] = is_fallback
self._intent_events[intent_name] = events
self._register_context_to_func(intent_name, with_context)
@wraps(f)
def wrapper(*args, **kw):
self._flask_assitant_view_func(*args, **kw)
return f
return decorator | python | def action(
self,
intent_name,
is_fallback=False,
mapping={},
convert={},
default={},
with_context=[],
events=[],
*args,
**kw
):
"""Decorates an intent_name's Action view function.
The wrapped function is called when a request with the
given intent_name is recieved along with all required parameters.
"""
def decorator(f):
action_funcs = self._intent_action_funcs.get(intent_name, [])
action_funcs.append(f)
self._intent_action_funcs[intent_name] = action_funcs
self._intent_mappings[intent_name] = mapping
self._intent_converts[intent_name] = convert
self._intent_defaults[intent_name] = default
self._intent_fallbacks[intent_name] = is_fallback
self._intent_events[intent_name] = events
self._register_context_to_func(intent_name, with_context)
@wraps(f)
def wrapper(*args, **kw):
self._flask_assitant_view_func(*args, **kw)
return f
return decorator | [
"def",
"action",
"(",
"self",
",",
"intent_name",
",",
"is_fallback",
"=",
"False",
",",
"mapping",
"=",
"{",
"}",
",",
"convert",
"=",
"{",
"}",
",",
"default",
"=",
"{",
"}",
",",
"with_context",
"=",
"[",
"]",
",",
"events",
"=",
"[",
"]",
","... | Decorates an intent_name's Action view function.
The wrapped function is called when a request with the
given intent_name is recieved along with all required parameters. | [
"Decorates",
"an",
"intent_name",
"s",
"Action",
"view",
"function",
"."
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/core.py#L275-L311 | train | 210,623 |
treethought/flask-assistant | flask_assistant/core.py | Assistant.prompt_for | def prompt_for(self, next_param, intent_name):
"""Decorates a function to prompt for an action's required parameter.
The wrapped function is called if next_param was not recieved with the given intent's
request and is required for the fulfillment of the intent's action.
Arguments:
next_param {str} -- name of the parameter required for action function
intent_name {str} -- name of the intent the dependent action belongs to
"""
def decorator(f):
prompts = self._intent_prompts.get(intent_name)
if prompts:
prompts[next_param] = f
else:
self._intent_prompts[intent_name] = {}
self._intent_prompts[intent_name][next_param] = f
@wraps(f)
def wrapper(*args, **kw):
self._flask_assitant_view_func(*args, **kw)
return f
return decorator | python | def prompt_for(self, next_param, intent_name):
"""Decorates a function to prompt for an action's required parameter.
The wrapped function is called if next_param was not recieved with the given intent's
request and is required for the fulfillment of the intent's action.
Arguments:
next_param {str} -- name of the parameter required for action function
intent_name {str} -- name of the intent the dependent action belongs to
"""
def decorator(f):
prompts = self._intent_prompts.get(intent_name)
if prompts:
prompts[next_param] = f
else:
self._intent_prompts[intent_name] = {}
self._intent_prompts[intent_name][next_param] = f
@wraps(f)
def wrapper(*args, **kw):
self._flask_assitant_view_func(*args, **kw)
return f
return decorator | [
"def",
"prompt_for",
"(",
"self",
",",
"next_param",
",",
"intent_name",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"prompts",
"=",
"self",
".",
"_intent_prompts",
".",
"get",
"(",
"intent_name",
")",
"if",
"prompts",
":",
"prompts",
"[",
"next_pa... | Decorates a function to prompt for an action's required parameter.
The wrapped function is called if next_param was not recieved with the given intent's
request and is required for the fulfillment of the intent's action.
Arguments:
next_param {str} -- name of the parameter required for action function
intent_name {str} -- name of the intent the dependent action belongs to | [
"Decorates",
"a",
"function",
"to",
"prompt",
"for",
"an",
"action",
"s",
"required",
"parameter",
"."
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/core.py#L313-L338 | train | 210,624 |
treethought/flask-assistant | flask_assistant/core.py | Assistant._context_views | def _context_views(self):
"""Returns view functions for which the context requirements are met"""
possible_views = []
for func in self._func_contexts:
if self._context_satified(func):
logger.debug("{} context conditions satisified".format(func.__name__))
possible_views.append(func)
return possible_views | python | def _context_views(self):
"""Returns view functions for which the context requirements are met"""
possible_views = []
for func in self._func_contexts:
if self._context_satified(func):
logger.debug("{} context conditions satisified".format(func.__name__))
possible_views.append(func)
return possible_views | [
"def",
"_context_views",
"(",
"self",
")",
":",
"possible_views",
"=",
"[",
"]",
"for",
"func",
"in",
"self",
".",
"_func_contexts",
":",
"if",
"self",
".",
"_context_satified",
"(",
"func",
")",
":",
"logger",
".",
"debug",
"(",
"\"{} context conditions sat... | Returns view functions for which the context requirements are met | [
"Returns",
"view",
"functions",
"for",
"which",
"the",
"context",
"requirements",
"are",
"met"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/core.py#L585-L593 | train | 210,625 |
treethought/flask-assistant | flask_assistant/utils.py | get_assistant | def get_assistant(filename):
"""Imports a module from filename as a string, returns the contained Assistant object"""
agent_name = os.path.splitext(filename)[0]
try:
agent_module = import_with_3(
agent_name, os.path.join(os.getcwd(), filename))
except ImportError:
agent_module = import_with_2(
agent_name, os.path.join(os.getcwd(), filename))
for name, obj in agent_module.__dict__.items():
if isinstance(obj, Assistant):
return obj | python | def get_assistant(filename):
"""Imports a module from filename as a string, returns the contained Assistant object"""
agent_name = os.path.splitext(filename)[0]
try:
agent_module = import_with_3(
agent_name, os.path.join(os.getcwd(), filename))
except ImportError:
agent_module = import_with_2(
agent_name, os.path.join(os.getcwd(), filename))
for name, obj in agent_module.__dict__.items():
if isinstance(obj, Assistant):
return obj | [
"def",
"get_assistant",
"(",
"filename",
")",
":",
"agent_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
"try",
":",
"agent_module",
"=",
"import_with_3",
"(",
"agent_name",
",",
"os",
".",
"path",
".",
"join",
"("... | Imports a module from filename as a string, returns the contained Assistant object | [
"Imports",
"a",
"module",
"from",
"filename",
"as",
"a",
"string",
"returns",
"the",
"contained",
"Assistant",
"object"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/utils.py#L25-L40 | train | 210,626 |
treethought/flask-assistant | api_ai/models.py | UserDefinedExample._annotate_params | def _annotate_params(self, word):
"""Annotates a given word for the UserSays data field of an Intent object.
Annotations are created using the entity map within the user_says.yaml template.
"""
annotation = {}
annotation['text'] = word
annotation['meta'] = '@' + self.entity_map[word]
annotation['alias'] = self.entity_map[word].replace('sys.', '')
annotation['userDefined'] = True
self.data.append(annotation) | python | def _annotate_params(self, word):
"""Annotates a given word for the UserSays data field of an Intent object.
Annotations are created using the entity map within the user_says.yaml template.
"""
annotation = {}
annotation['text'] = word
annotation['meta'] = '@' + self.entity_map[word]
annotation['alias'] = self.entity_map[word].replace('sys.', '')
annotation['userDefined'] = True
self.data.append(annotation) | [
"def",
"_annotate_params",
"(",
"self",
",",
"word",
")",
":",
"annotation",
"=",
"{",
"}",
"annotation",
"[",
"'text'",
"]",
"=",
"word",
"annotation",
"[",
"'meta'",
"]",
"=",
"'@'",
"+",
"self",
".",
"entity_map",
"[",
"word",
"]",
"annotation",
"["... | Annotates a given word for the UserSays data field of an Intent object.
Annotations are created using the entity map within the user_says.yaml template. | [
"Annotates",
"a",
"given",
"word",
"for",
"the",
"UserSays",
"data",
"field",
"of",
"an",
"Intent",
"object",
"."
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/models.py#L173-L183 | train | 210,627 |
treethought/flask-assistant | api_ai/schema_handlers.py | IntentGenerator.app_intents | def app_intents(self):
"""Returns a list of Intent objects created from the assistant's acion functions"""
from_app = []
for intent_name in self.assist._intent_action_funcs:
intent = self.build_intent(intent_name)
from_app.append(intent)
return from_app | python | def app_intents(self):
"""Returns a list of Intent objects created from the assistant's acion functions"""
from_app = []
for intent_name in self.assist._intent_action_funcs:
intent = self.build_intent(intent_name)
from_app.append(intent)
return from_app | [
"def",
"app_intents",
"(",
"self",
")",
":",
"from_app",
"=",
"[",
"]",
"for",
"intent_name",
"in",
"self",
".",
"assist",
".",
"_intent_action_funcs",
":",
"intent",
"=",
"self",
".",
"build_intent",
"(",
"intent_name",
")",
"from_app",
".",
"append",
"("... | Returns a list of Intent objects created from the assistant's acion functions | [
"Returns",
"a",
"list",
"of",
"Intent",
"objects",
"created",
"from",
"the",
"assistant",
"s",
"acion",
"functions"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/schema_handlers.py#L112-L118 | train | 210,628 |
treethought/flask-assistant | api_ai/schema_handlers.py | IntentGenerator.build_intent | def build_intent(self, intent_name):
"""Builds an Intent object of the given name"""
# TODO: contexts
is_fallback = self.assist._intent_fallbacks[intent_name]
contexts = self.assist._required_contexts[intent_name]
events = self.assist._intent_events[intent_name]
new_intent = Intent(intent_name, fallback_intent=is_fallback, contexts=contexts, events=events)
self.build_action(new_intent)
self.build_user_says(new_intent) # TODO
return new_intent | python | def build_intent(self, intent_name):
"""Builds an Intent object of the given name"""
# TODO: contexts
is_fallback = self.assist._intent_fallbacks[intent_name]
contexts = self.assist._required_contexts[intent_name]
events = self.assist._intent_events[intent_name]
new_intent = Intent(intent_name, fallback_intent=is_fallback, contexts=contexts, events=events)
self.build_action(new_intent)
self.build_user_says(new_intent) # TODO
return new_intent | [
"def",
"build_intent",
"(",
"self",
",",
"intent_name",
")",
":",
"# TODO: contexts",
"is_fallback",
"=",
"self",
".",
"assist",
".",
"_intent_fallbacks",
"[",
"intent_name",
"]",
"contexts",
"=",
"self",
".",
"assist",
".",
"_required_contexts",
"[",
"intent_na... | Builds an Intent object of the given name | [
"Builds",
"an",
"Intent",
"object",
"of",
"the",
"given",
"name"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/schema_handlers.py#L120-L129 | train | 210,629 |
treethought/flask-assistant | api_ai/schema_handlers.py | IntentGenerator.parse_params | def parse_params(self, intent_name):
"""Parses params from an intent's action decorator and view function.
Returns a list of parameter field dicts to be included in the intent object's response field.
"""
params = []
action_func = self.assist._intent_action_funcs[intent_name][0]
argspec = inspect.getargspec(action_func)
param_entity_map = self.assist._intent_mappings.get(intent_name)
args, defaults = argspec.args, argspec.defaults
default_map = {}
if defaults:
default_map = dict(zip(args[-len(defaults):], defaults))
# import ipdb; ipdb.set_trace()
for arg in args:
param_info = {}
param_entity = param_entity_map.get(arg, arg)
param_name = param_entity.replace('sys.', '')
# param_name = arg
param_info['name'] = param_name
param_info['value'] = '$' + param_name
param_info['dataType'] = '@' + param_entity
param_info['prompts'] = [] # TODO: fill in provided prompts
param_info['required'] = arg not in default_map
param_info['isList'] = isinstance(default_map.get(arg), list)
if param_info['isList']:
param_info['defaultValue'] = ''
else:
param_info['defaultValue'] = default_map.get(arg, '')
params.append(param_info)
return params | python | def parse_params(self, intent_name):
"""Parses params from an intent's action decorator and view function.
Returns a list of parameter field dicts to be included in the intent object's response field.
"""
params = []
action_func = self.assist._intent_action_funcs[intent_name][0]
argspec = inspect.getargspec(action_func)
param_entity_map = self.assist._intent_mappings.get(intent_name)
args, defaults = argspec.args, argspec.defaults
default_map = {}
if defaults:
default_map = dict(zip(args[-len(defaults):], defaults))
# import ipdb; ipdb.set_trace()
for arg in args:
param_info = {}
param_entity = param_entity_map.get(arg, arg)
param_name = param_entity.replace('sys.', '')
# param_name = arg
param_info['name'] = param_name
param_info['value'] = '$' + param_name
param_info['dataType'] = '@' + param_entity
param_info['prompts'] = [] # TODO: fill in provided prompts
param_info['required'] = arg not in default_map
param_info['isList'] = isinstance(default_map.get(arg), list)
if param_info['isList']:
param_info['defaultValue'] = ''
else:
param_info['defaultValue'] = default_map.get(arg, '')
params.append(param_info)
return params | [
"def",
"parse_params",
"(",
"self",
",",
"intent_name",
")",
":",
"params",
"=",
"[",
"]",
"action_func",
"=",
"self",
".",
"assist",
".",
"_intent_action_funcs",
"[",
"intent_name",
"]",
"[",
"0",
"]",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
... | Parses params from an intent's action decorator and view function.
Returns a list of parameter field dicts to be included in the intent object's response field. | [
"Parses",
"params",
"from",
"an",
"intent",
"s",
"action",
"decorator",
"and",
"view",
"function",
"."
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/schema_handlers.py#L137-L173 | train | 210,630 |
treethought/flask-assistant | api_ai/schema_handlers.py | IntentGenerator.push_intent | def push_intent(self, intent):
"""Registers or updates an intent and returns the intent_json with an ID"""
if intent.id:
print('Updating {} intent'.format(intent.name))
self.update(intent)
else:
print('Registering {} intent'.format(intent.name))
intent = self.register(intent)
return intent | python | def push_intent(self, intent):
"""Registers or updates an intent and returns the intent_json with an ID"""
if intent.id:
print('Updating {} intent'.format(intent.name))
self.update(intent)
else:
print('Registering {} intent'.format(intent.name))
intent = self.register(intent)
return intent | [
"def",
"push_intent",
"(",
"self",
",",
"intent",
")",
":",
"if",
"intent",
".",
"id",
":",
"print",
"(",
"'Updating {} intent'",
".",
"format",
"(",
"intent",
".",
"name",
")",
")",
"self",
".",
"update",
"(",
"intent",
")",
"else",
":",
"print",
"(... | Registers or updates an intent and returns the intent_json with an ID | [
"Registers",
"or",
"updates",
"an",
"intent",
"and",
"returns",
"the",
"intent_json",
"with",
"an",
"ID"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/schema_handlers.py#L208-L216 | train | 210,631 |
treethought/flask-assistant | api_ai/schema_handlers.py | IntentGenerator.register | def register(self, intent):
"""Registers a new intent and returns the Intent object with an ID"""
response = self.api.post_intent(intent.serialize)
print(response)
print()
if response['status']['code'] == 200:
intent.id = response['id']
elif response['status']['code'] == 409: # intent already exists
intent.id = next(i.id for i in self.api.agent_intents if i.name == intent.name)
self.update(intent)
return intent | python | def register(self, intent):
"""Registers a new intent and returns the Intent object with an ID"""
response = self.api.post_intent(intent.serialize)
print(response)
print()
if response['status']['code'] == 200:
intent.id = response['id']
elif response['status']['code'] == 409: # intent already exists
intent.id = next(i.id for i in self.api.agent_intents if i.name == intent.name)
self.update(intent)
return intent | [
"def",
"register",
"(",
"self",
",",
"intent",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"post_intent",
"(",
"intent",
".",
"serialize",
")",
"print",
"(",
"response",
")",
"print",
"(",
")",
"if",
"response",
"[",
"'status'",
"]",
"[",
"'c... | Registers a new intent and returns the Intent object with an ID | [
"Registers",
"a",
"new",
"intent",
"and",
"returns",
"the",
"Intent",
"object",
"with",
"an",
"ID"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/schema_handlers.py#L218-L228 | train | 210,632 |
treethought/flask-assistant | api_ai/schema_handlers.py | EntityGenerator.register | def register(self, entity):
"""Registers a new entity and returns the entity object with an ID"""
response = self.api.post_entity(entity.serialize)
print(response)
print()
if response['status']['code'] == 200:
entity.id = response['id']
if response['status']['code'] == 409: # entity already exists
entity.id = next(i.id for i in self.api.agent_entities if i.name == entity.name)
self.update(entity)
return entity | python | def register(self, entity):
"""Registers a new entity and returns the entity object with an ID"""
response = self.api.post_entity(entity.serialize)
print(response)
print()
if response['status']['code'] == 200:
entity.id = response['id']
if response['status']['code'] == 409: # entity already exists
entity.id = next(i.id for i in self.api.agent_entities if i.name == entity.name)
self.update(entity)
return entity | [
"def",
"register",
"(",
"self",
",",
"entity",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"post_entity",
"(",
"entity",
".",
"serialize",
")",
"print",
"(",
"response",
")",
"print",
"(",
")",
"if",
"response",
"[",
"'status'",
"]",
"[",
"'c... | Registers a new entity and returns the entity object with an ID | [
"Registers",
"a",
"new",
"entity",
"and",
"returns",
"the",
"entity",
"object",
"with",
"an",
"ID"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/schema_handlers.py#L271-L281 | train | 210,633 |
treethought/flask-assistant | api_ai/schema_handlers.py | EntityGenerator.push_entity | def push_entity(self, entity):
"""Registers or updates an entity and returns the entity_json with an ID"""
if entity.id:
print('Updating {} entity'.format(entity.name))
self.update(entity)
else:
print('Registering {} entity'.format(entity.name))
entity = self.register(entity)
return entity | python | def push_entity(self, entity):
"""Registers or updates an entity and returns the entity_json with an ID"""
if entity.id:
print('Updating {} entity'.format(entity.name))
self.update(entity)
else:
print('Registering {} entity'.format(entity.name))
entity = self.register(entity)
return entity | [
"def",
"push_entity",
"(",
"self",
",",
"entity",
")",
":",
"if",
"entity",
".",
"id",
":",
"print",
"(",
"'Updating {} entity'",
".",
"format",
"(",
"entity",
".",
"name",
")",
")",
"self",
".",
"update",
"(",
"entity",
")",
"else",
":",
"print",
"(... | Registers or updates an entity and returns the entity_json with an ID | [
"Registers",
"or",
"updates",
"an",
"entity",
"and",
"returns",
"the",
"entity_json",
"with",
"an",
"ID"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/api_ai/schema_handlers.py#L290-L298 | train | 210,634 |
treethought/flask-assistant | flask_assistant/hass.py | HassRemote.set_state | def set_state(self, entity_id, new_state, **kwargs):
"Updates or creates the current state of an entity."
return remote.set_state(self.api, new_state, **kwargs) | python | def set_state(self, entity_id, new_state, **kwargs):
"Updates or creates the current state of an entity."
return remote.set_state(self.api, new_state, **kwargs) | [
"def",
"set_state",
"(",
"self",
",",
"entity_id",
",",
"new_state",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"remote",
".",
"set_state",
"(",
"self",
".",
"api",
",",
"new_state",
",",
"*",
"*",
"kwargs",
")"
] | Updates or creates the current state of an entity. | [
"Updates",
"or",
"creates",
"the",
"current",
"state",
"of",
"an",
"entity",
"."
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/hass.py#L48-L50 | train | 210,635 |
treethought/flask-assistant | flask_assistant/hass.py | HassRemote.is_state | def is_state(self, entity_id, state):
"""Checks if the entity has the given state"""
return remote.is_state(self.api, entity_id, state) | python | def is_state(self, entity_id, state):
"""Checks if the entity has the given state"""
return remote.is_state(self.api, entity_id, state) | [
"def",
"is_state",
"(",
"self",
",",
"entity_id",
",",
"state",
")",
":",
"return",
"remote",
".",
"is_state",
"(",
"self",
".",
"api",
",",
"entity_id",
",",
"state",
")"
] | Checks if the entity has the given state | [
"Checks",
"if",
"the",
"entity",
"has",
"the",
"given",
"state"
] | 9331b9796644dfa987bcd97a13e78e9ab62923d3 | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/hass.py#L52-L54 | train | 210,636 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.etag | def etag(self, etag):
"""
Set the ETag of the resource.
:param etag: the ETag
"""
if not isinstance(etag, bytes):
etag = bytes(etag, "utf-8")
self._etag.append(etag) | python | def etag(self, etag):
"""
Set the ETag of the resource.
:param etag: the ETag
"""
if not isinstance(etag, bytes):
etag = bytes(etag, "utf-8")
self._etag.append(etag) | [
"def",
"etag",
"(",
"self",
",",
"etag",
")",
":",
"if",
"not",
"isinstance",
"(",
"etag",
",",
"bytes",
")",
":",
"etag",
"=",
"bytes",
"(",
"etag",
",",
"\"utf-8\"",
")",
"self",
".",
"_etag",
".",
"append",
"(",
"etag",
")"
] | Set the ETag of the resource.
:param etag: the ETag | [
"Set",
"the",
"ETag",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L110-L118 | train | 210,637 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.payload | def payload(self, p):
"""
Set the payload of the resource.
:param p: the new payload
"""
if isinstance(p, tuple):
k = p[0]
v = p[1]
self.actual_content_type = k
self._payload[k] = v
else:
self._payload = {defines.Content_types["text/plain"]: p} | python | def payload(self, p):
"""
Set the payload of the resource.
:param p: the new payload
"""
if isinstance(p, tuple):
k = p[0]
v = p[1]
self.actual_content_type = k
self._payload[k] = v
else:
self._payload = {defines.Content_types["text/plain"]: p} | [
"def",
"payload",
"(",
"self",
",",
"p",
")",
":",
"if",
"isinstance",
"(",
"p",
",",
"tuple",
")",
":",
"k",
"=",
"p",
"[",
"0",
"]",
"v",
"=",
"p",
"[",
"1",
"]",
"self",
".",
"actual_content_type",
"=",
"k",
"self",
".",
"_payload",
"[",
"... | Set the payload of the resource.
:param p: the new payload | [
"Set",
"the",
"payload",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L186-L198 | train | 210,638 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.content_type | def content_type(self):
"""
Get the CoRE Link Format ct attribute of the resource.
:return: the CoRE Link Format ct attribute
"""
value = ""
lst = self._attributes.get("ct")
if lst is not None and len(lst) > 0:
value = "ct="
for v in lst:
value += str(v) + " "
if len(value) > 0:
value = value[:-1]
return value | python | def content_type(self):
"""
Get the CoRE Link Format ct attribute of the resource.
:return: the CoRE Link Format ct attribute
"""
value = ""
lst = self._attributes.get("ct")
if lst is not None and len(lst) > 0:
value = "ct="
for v in lst:
value += str(v) + " "
if len(value) > 0:
value = value[:-1]
return value | [
"def",
"content_type",
"(",
"self",
")",
":",
"value",
"=",
"\"\"",
"lst",
"=",
"self",
".",
"_attributes",
".",
"get",
"(",
"\"ct\"",
")",
"if",
"lst",
"is",
"not",
"None",
"and",
"len",
"(",
"lst",
")",
">",
"0",
":",
"value",
"=",
"\"ct=\"",
"... | Get the CoRE Link Format ct attribute of the resource.
:return: the CoRE Link Format ct attribute | [
"Get",
"the",
"CoRE",
"Link",
"Format",
"ct",
"attribute",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L284-L298 | train | 210,639 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.content_type | def content_type(self, lst):
"""
Set the CoRE Link Format ct attribute of the resource.
:param lst: the list of CoRE Link Format ct attribute of the resource
"""
value = []
if isinstance(lst, str):
ct = defines.Content_types[lst]
self.add_content_type(ct)
elif isinstance(lst, list):
for ct in lst:
self.add_content_type(ct) | python | def content_type(self, lst):
"""
Set the CoRE Link Format ct attribute of the resource.
:param lst: the list of CoRE Link Format ct attribute of the resource
"""
value = []
if isinstance(lst, str):
ct = defines.Content_types[lst]
self.add_content_type(ct)
elif isinstance(lst, list):
for ct in lst:
self.add_content_type(ct) | [
"def",
"content_type",
"(",
"self",
",",
"lst",
")",
":",
"value",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"lst",
",",
"str",
")",
":",
"ct",
"=",
"defines",
".",
"Content_types",
"[",
"lst",
"]",
"self",
".",
"add_content_type",
"(",
"ct",
")",
"e... | Set the CoRE Link Format ct attribute of the resource.
:param lst: the list of CoRE Link Format ct attribute of the resource | [
"Set",
"the",
"CoRE",
"Link",
"Format",
"ct",
"attribute",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L301-L313 | train | 210,640 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.add_content_type | def add_content_type(self, ct):
"""
Add a CoRE Link Format ct attribute to the resource.
:param ct: the CoRE Link Format ct attribute
"""
lst = self._attributes.get("ct")
if lst is None:
lst = []
if isinstance(ct, str):
ct = defines.Content_types[ct]
lst.append(ct)
self._attributes["ct"] = lst | python | def add_content_type(self, ct):
"""
Add a CoRE Link Format ct attribute to the resource.
:param ct: the CoRE Link Format ct attribute
"""
lst = self._attributes.get("ct")
if lst is None:
lst = []
if isinstance(ct, str):
ct = defines.Content_types[ct]
lst.append(ct)
self._attributes["ct"] = lst | [
"def",
"add_content_type",
"(",
"self",
",",
"ct",
")",
":",
"lst",
"=",
"self",
".",
"_attributes",
".",
"get",
"(",
"\"ct\"",
")",
"if",
"lst",
"is",
"None",
":",
"lst",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"ct",
",",
"str",
")",
":",
"ct",
... | Add a CoRE Link Format ct attribute to the resource.
:param ct: the CoRE Link Format ct attribute | [
"Add",
"a",
"CoRE",
"Link",
"Format",
"ct",
"attribute",
"to",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L315-L327 | train | 210,641 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.resource_type | def resource_type(self):
"""
Get the CoRE Link Format rt attribute of the resource.
:return: the CoRE Link Format rt attribute
"""
value = "rt="
lst = self._attributes.get("rt")
if lst is None:
value = ""
else:
value += "\"" + str(lst) + "\""
return value | python | def resource_type(self):
"""
Get the CoRE Link Format rt attribute of the resource.
:return: the CoRE Link Format rt attribute
"""
value = "rt="
lst = self._attributes.get("rt")
if lst is None:
value = ""
else:
value += "\"" + str(lst) + "\""
return value | [
"def",
"resource_type",
"(",
"self",
")",
":",
"value",
"=",
"\"rt=\"",
"lst",
"=",
"self",
".",
"_attributes",
".",
"get",
"(",
"\"rt\"",
")",
"if",
"lst",
"is",
"None",
":",
"value",
"=",
"\"\"",
"else",
":",
"value",
"+=",
"\"\\\"\"",
"+",
"str",
... | Get the CoRE Link Format rt attribute of the resource.
:return: the CoRE Link Format rt attribute | [
"Get",
"the",
"CoRE",
"Link",
"Format",
"rt",
"attribute",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L330-L342 | train | 210,642 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.resource_type | def resource_type(self, rt):
"""
Set the CoRE Link Format rt attribute of the resource.
:param rt: the CoRE Link Format rt attribute
"""
if not isinstance(rt, str):
rt = str(rt)
self._attributes["rt"] = rt | python | def resource_type(self, rt):
"""
Set the CoRE Link Format rt attribute of the resource.
:param rt: the CoRE Link Format rt attribute
"""
if not isinstance(rt, str):
rt = str(rt)
self._attributes["rt"] = rt | [
"def",
"resource_type",
"(",
"self",
",",
"rt",
")",
":",
"if",
"not",
"isinstance",
"(",
"rt",
",",
"str",
")",
":",
"rt",
"=",
"str",
"(",
"rt",
")",
"self",
".",
"_attributes",
"[",
"\"rt\"",
"]",
"=",
"rt"
] | Set the CoRE Link Format rt attribute of the resource.
:param rt: the CoRE Link Format rt attribute | [
"Set",
"the",
"CoRE",
"Link",
"Format",
"rt",
"attribute",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L345-L353 | train | 210,643 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.interface_type | def interface_type(self):
"""
Get the CoRE Link Format if attribute of the resource.
:return: the CoRE Link Format if attribute
"""
value = "if="
lst = self._attributes.get("if")
if lst is None:
value = ""
else:
value += "\"" + str(lst) + "\""
return value | python | def interface_type(self):
"""
Get the CoRE Link Format if attribute of the resource.
:return: the CoRE Link Format if attribute
"""
value = "if="
lst = self._attributes.get("if")
if lst is None:
value = ""
else:
value += "\"" + str(lst) + "\""
return value | [
"def",
"interface_type",
"(",
"self",
")",
":",
"value",
"=",
"\"if=\"",
"lst",
"=",
"self",
".",
"_attributes",
".",
"get",
"(",
"\"if\"",
")",
"if",
"lst",
"is",
"None",
":",
"value",
"=",
"\"\"",
"else",
":",
"value",
"+=",
"\"\\\"\"",
"+",
"str",... | Get the CoRE Link Format if attribute of the resource.
:return: the CoRE Link Format if attribute | [
"Get",
"the",
"CoRE",
"Link",
"Format",
"if",
"attribute",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L356-L368 | train | 210,644 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.interface_type | def interface_type(self, ift):
"""
Set the CoRE Link Format if attribute of the resource.
:param ift: the CoRE Link Format if attribute
"""
if not isinstance(ift, str):
ift = str(ift)
self._attributes["if"] = ift | python | def interface_type(self, ift):
"""
Set the CoRE Link Format if attribute of the resource.
:param ift: the CoRE Link Format if attribute
"""
if not isinstance(ift, str):
ift = str(ift)
self._attributes["if"] = ift | [
"def",
"interface_type",
"(",
"self",
",",
"ift",
")",
":",
"if",
"not",
"isinstance",
"(",
"ift",
",",
"str",
")",
":",
"ift",
"=",
"str",
"(",
"ift",
")",
"self",
".",
"_attributes",
"[",
"\"if\"",
"]",
"=",
"ift"
] | Set the CoRE Link Format if attribute of the resource.
:param ift: the CoRE Link Format if attribute | [
"Set",
"the",
"CoRE",
"Link",
"Format",
"if",
"attribute",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L371-L379 | train | 210,645 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.maximum_size_estimated | def maximum_size_estimated(self):
"""
Get the CoRE Link Format sz attribute of the resource.
:return: the CoRE Link Format sz attribute
"""
value = "sz="
lst = self._attributes.get("sz")
if lst is None:
value = ""
else:
value += "\"" + str(lst) + "\""
return value | python | def maximum_size_estimated(self):
"""
Get the CoRE Link Format sz attribute of the resource.
:return: the CoRE Link Format sz attribute
"""
value = "sz="
lst = self._attributes.get("sz")
if lst is None:
value = ""
else:
value += "\"" + str(lst) + "\""
return value | [
"def",
"maximum_size_estimated",
"(",
"self",
")",
":",
"value",
"=",
"\"sz=\"",
"lst",
"=",
"self",
".",
"_attributes",
".",
"get",
"(",
"\"sz\"",
")",
"if",
"lst",
"is",
"None",
":",
"value",
"=",
"\"\"",
"else",
":",
"value",
"+=",
"\"\\\"\"",
"+",
... | Get the CoRE Link Format sz attribute of the resource.
:return: the CoRE Link Format sz attribute | [
"Get",
"the",
"CoRE",
"Link",
"Format",
"sz",
"attribute",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L382-L394 | train | 210,646 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.maximum_size_estimated | def maximum_size_estimated(self, sz):
"""
Set the CoRE Link Format sz attribute of the resource.
:param sz: the CoRE Link Format sz attribute
"""
if not isinstance(sz, str):
sz = str(sz)
self._attributes["sz"] = sz | python | def maximum_size_estimated(self, sz):
"""
Set the CoRE Link Format sz attribute of the resource.
:param sz: the CoRE Link Format sz attribute
"""
if not isinstance(sz, str):
sz = str(sz)
self._attributes["sz"] = sz | [
"def",
"maximum_size_estimated",
"(",
"self",
",",
"sz",
")",
":",
"if",
"not",
"isinstance",
"(",
"sz",
",",
"str",
")",
":",
"sz",
"=",
"str",
"(",
"sz",
")",
"self",
".",
"_attributes",
"[",
"\"sz\"",
"]",
"=",
"sz"
] | Set the CoRE Link Format sz attribute of the resource.
:param sz: the CoRE Link Format sz attribute | [
"Set",
"the",
"CoRE",
"Link",
"Format",
"sz",
"attribute",
"of",
"the",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L397-L405 | train | 210,647 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.init_resource | def init_resource(self, request, res):
"""
Helper function to initialize a new resource.
:param request: the request that generate the new resource
:param res: the resource
:return: the edited resource
"""
res.location_query = request.uri_query
res.payload = (request.content_type, request.payload)
return res | python | def init_resource(self, request, res):
"""
Helper function to initialize a new resource.
:param request: the request that generate the new resource
:param res: the resource
:return: the edited resource
"""
res.location_query = request.uri_query
res.payload = (request.content_type, request.payload)
return res | [
"def",
"init_resource",
"(",
"self",
",",
"request",
",",
"res",
")",
":",
"res",
".",
"location_query",
"=",
"request",
".",
"uri_query",
"res",
".",
"payload",
"=",
"(",
"request",
".",
"content_type",
",",
"request",
".",
"payload",
")",
"return",
"re... | Helper function to initialize a new resource.
:param request: the request that generate the new resource
:param res: the resource
:return: the edited resource | [
"Helper",
"function",
"to",
"initialize",
"a",
"new",
"resource",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L417-L427 | train | 210,648 |
Tanganelli/CoAPthon3 | coapthon/resources/resource.py | Resource.edit_resource | def edit_resource(self, request):
"""
Helper function to edit a resource
:param request: the request that edit the resource
"""
self.location_query = request.uri_query
self.payload = (request.content_type, request.payload) | python | def edit_resource(self, request):
"""
Helper function to edit a resource
:param request: the request that edit the resource
"""
self.location_query = request.uri_query
self.payload = (request.content_type, request.payload) | [
"def",
"edit_resource",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"location_query",
"=",
"request",
".",
"uri_query",
"self",
".",
"payload",
"=",
"(",
"request",
".",
"content_type",
",",
"request",
".",
"payload",
")"
] | Helper function to edit a resource
:param request: the request that edit the resource | [
"Helper",
"function",
"to",
"edit",
"a",
"resource"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L429-L436 | train | 210,649 |
Tanganelli/CoAPthon3 | coapthon/layers/blocklayer.py | BlockLayer.receive_request | def receive_request(self, transaction):
"""
Handles the Blocks option in a incoming request.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction
"""
if transaction.request.block2 is not None:
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
num, m, size = transaction.request.block2
if key_token in self._block2_receive:
self._block2_receive[key_token].num = num
self._block2_receive[key_token].size = size
self._block2_receive[key_token].m = m
del transaction.request.block2
else:
# early negotiation
byte = 0
self._block2_receive[key_token] = BlockItem(byte, num, m, size)
del transaction.request.block2
elif transaction.request.block1 is not None:
# POST or PUT
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
num, m, size = transaction.request.block1
if key_token in self._block1_receive:
content_type = transaction.request.content_type
if num != self._block1_receive[key_token].num \
or content_type != self._block1_receive[key_token].content_type:
# Error Incomplete
return self.incomplete(transaction)
self._block1_receive[key_token].payload += transaction.request.payload
else:
# first block
if num != 0:
# Error Incomplete
return self.incomplete(transaction)
content_type = transaction.request.content_type
self._block1_receive[key_token] = BlockItem(size, num, m, size, transaction.request.payload,
content_type)
if m == 0:
transaction.request.payload = self._block1_receive[key_token].payload
# end of blockwise
del transaction.request.block1
transaction.block_transfer = False
del self._block1_receive[key_token]
return transaction
else:
# Continue
transaction.block_transfer = True
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
transaction.response.code = defines.Codes.CONTINUE.number
transaction.response.block1 = (num, m, size)
num += 1
byte = size
self._block1_receive[key_token].byte = byte
self._block1_receive[key_token].num = num
self._block1_receive[key_token].size = size
self._block1_receive[key_token].m = m
return transaction | python | def receive_request(self, transaction):
"""
Handles the Blocks option in a incoming request.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction
"""
if transaction.request.block2 is not None:
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
num, m, size = transaction.request.block2
if key_token in self._block2_receive:
self._block2_receive[key_token].num = num
self._block2_receive[key_token].size = size
self._block2_receive[key_token].m = m
del transaction.request.block2
else:
# early negotiation
byte = 0
self._block2_receive[key_token] = BlockItem(byte, num, m, size)
del transaction.request.block2
elif transaction.request.block1 is not None:
# POST or PUT
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
num, m, size = transaction.request.block1
if key_token in self._block1_receive:
content_type = transaction.request.content_type
if num != self._block1_receive[key_token].num \
or content_type != self._block1_receive[key_token].content_type:
# Error Incomplete
return self.incomplete(transaction)
self._block1_receive[key_token].payload += transaction.request.payload
else:
# first block
if num != 0:
# Error Incomplete
return self.incomplete(transaction)
content_type = transaction.request.content_type
self._block1_receive[key_token] = BlockItem(size, num, m, size, transaction.request.payload,
content_type)
if m == 0:
transaction.request.payload = self._block1_receive[key_token].payload
# end of blockwise
del transaction.request.block1
transaction.block_transfer = False
del self._block1_receive[key_token]
return transaction
else:
# Continue
transaction.block_transfer = True
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
transaction.response.code = defines.Codes.CONTINUE.number
transaction.response.block1 = (num, m, size)
num += 1
byte = size
self._block1_receive[key_token].byte = byte
self._block1_receive[key_token].num = num
self._block1_receive[key_token].size = size
self._block1_receive[key_token].m = m
return transaction | [
"def",
"receive_request",
"(",
"self",
",",
"transaction",
")",
":",
"if",
"transaction",
".",
"request",
".",
"block2",
"is",
"not",
"None",
":",
"host",
",",
"port",
"=",
"transaction",
".",
"request",
".",
"source",
"key_token",
"=",
"hash",
"(",
"str... | Handles the Blocks option in a incoming request.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction | [
"Handles",
"the",
"Blocks",
"option",
"in",
"a",
"incoming",
"request",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/blocklayer.py#L41-L109 | train | 210,650 |
Tanganelli/CoAPthon3 | coapthon/layers/blocklayer.py | BlockLayer.send_response | def send_response(self, transaction):
"""
Handles the Blocks option in a outgoing response.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction
"""
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
if (key_token in self._block2_receive and transaction.response.payload is not None) or \
(transaction.response.payload is not None and len(transaction.response.payload) > defines.MAX_PAYLOAD):
if key_token in self._block2_receive:
byte = self._block2_receive[key_token].byte
size = self._block2_receive[key_token].size
num = self._block2_receive[key_token].num
else:
byte = 0
num = 0
size = defines.MAX_PAYLOAD
m = 1
self._block2_receive[key_token] = BlockItem(byte, num, m, size)
if len(transaction.response.payload) > (byte + size):
m = 1
else:
m = 0
transaction.response.payload = transaction.response.payload[byte:byte + size]
del transaction.response.block2
transaction.response.block2 = (num, m, size)
self._block2_receive[key_token].byte += size
self._block2_receive[key_token].num += 1
if m == 0:
del self._block2_receive[key_token]
return transaction | python | def send_response(self, transaction):
"""
Handles the Blocks option in a outgoing response.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction
"""
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
if (key_token in self._block2_receive and transaction.response.payload is not None) or \
(transaction.response.payload is not None and len(transaction.response.payload) > defines.MAX_PAYLOAD):
if key_token in self._block2_receive:
byte = self._block2_receive[key_token].byte
size = self._block2_receive[key_token].size
num = self._block2_receive[key_token].num
else:
byte = 0
num = 0
size = defines.MAX_PAYLOAD
m = 1
self._block2_receive[key_token] = BlockItem(byte, num, m, size)
if len(transaction.response.payload) > (byte + size):
m = 1
else:
m = 0
transaction.response.payload = transaction.response.payload[byte:byte + size]
del transaction.response.block2
transaction.response.block2 = (num, m, size)
self._block2_receive[key_token].byte += size
self._block2_receive[key_token].num += 1
if m == 0:
del self._block2_receive[key_token]
return transaction | [
"def",
"send_response",
"(",
"self",
",",
"transaction",
")",
":",
"host",
",",
"port",
"=",
"transaction",
".",
"request",
".",
"source",
"key_token",
"=",
"hash",
"(",
"str",
"(",
"host",
")",
"+",
"str",
"(",
"port",
")",
"+",
"str",
"(",
"transac... | Handles the Blocks option in a outgoing response.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction | [
"Handles",
"the",
"Blocks",
"option",
"in",
"a",
"outgoing",
"response",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/blocklayer.py#L201-L241 | train | 210,651 |
Tanganelli/CoAPthon3 | coapthon/layers/blocklayer.py | BlockLayer.send_request | def send_request(self, request):
"""
Handles the Blocks option in a outgoing request.
:type request: Request
:param request: the outgoing request
:return: the edited request
"""
assert isinstance(request, Request)
if request.block1 or (request.payload is not None and len(request.payload) > defines.MAX_PAYLOAD):
host, port = request.destination
key_token = hash(str(host) + str(port) + str(request.token))
if request.block1:
num, m, size = request.block1
else:
num = 0
m = 1
size = defines.MAX_PAYLOAD
self._block1_sent[key_token] = BlockItem(size, num, m, size, request.payload, request.content_type)
request.payload = request.payload[0:size]
del request.block1
request.block1 = (num, m, size)
elif request.block2:
host, port = request.destination
key_token = hash(str(host) + str(port) + str(request.token))
num, m, size = request.block2
item = BlockItem(size, num, m, size, "", None)
self._block2_sent[key_token] = item
return request
return request | python | def send_request(self, request):
"""
Handles the Blocks option in a outgoing request.
:type request: Request
:param request: the outgoing request
:return: the edited request
"""
assert isinstance(request, Request)
if request.block1 or (request.payload is not None and len(request.payload) > defines.MAX_PAYLOAD):
host, port = request.destination
key_token = hash(str(host) + str(port) + str(request.token))
if request.block1:
num, m, size = request.block1
else:
num = 0
m = 1
size = defines.MAX_PAYLOAD
self._block1_sent[key_token] = BlockItem(size, num, m, size, request.payload, request.content_type)
request.payload = request.payload[0:size]
del request.block1
request.block1 = (num, m, size)
elif request.block2:
host, port = request.destination
key_token = hash(str(host) + str(port) + str(request.token))
num, m, size = request.block2
item = BlockItem(size, num, m, size, "", None)
self._block2_sent[key_token] = item
return request
return request | [
"def",
"send_request",
"(",
"self",
",",
"request",
")",
":",
"assert",
"isinstance",
"(",
"request",
",",
"Request",
")",
"if",
"request",
".",
"block1",
"or",
"(",
"request",
".",
"payload",
"is",
"not",
"None",
"and",
"len",
"(",
"request",
".",
"pa... | Handles the Blocks option in a outgoing request.
:type request: Request
:param request: the outgoing request
:return: the edited request | [
"Handles",
"the",
"Blocks",
"option",
"in",
"a",
"outgoing",
"request",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/blocklayer.py#L243-L273 | train | 210,652 |
Tanganelli/CoAPthon3 | coapthon/layers/blocklayer.py | BlockLayer.incomplete | def incomplete(transaction):
"""
Notifies incomplete blockwise exchange.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction
"""
transaction.block_transfer = True
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
transaction.response.code = defines.Codes.REQUEST_ENTITY_INCOMPLETE.number
return transaction | python | def incomplete(transaction):
"""
Notifies incomplete blockwise exchange.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction
"""
transaction.block_transfer = True
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
transaction.response.code = defines.Codes.REQUEST_ENTITY_INCOMPLETE.number
return transaction | [
"def",
"incomplete",
"(",
"transaction",
")",
":",
"transaction",
".",
"block_transfer",
"=",
"True",
"transaction",
".",
"response",
"=",
"Response",
"(",
")",
"transaction",
".",
"response",
".",
"destination",
"=",
"transaction",
".",
"request",
".",
"sourc... | Notifies incomplete blockwise exchange.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction | [
"Notifies",
"incomplete",
"blockwise",
"exchange",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/blocklayer.py#L276-L290 | train | 210,653 |
Tanganelli/CoAPthon3 | coapthon/layers/blocklayer.py | BlockLayer.error | def error(transaction, code): # pragma: no cover
"""
Notifies generic error on blockwise exchange.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction
"""
transaction.block_transfer = True
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.type = defines.Types["RST"]
transaction.response.token = transaction.request.token
transaction.response.code = code
return transaction | python | def error(transaction, code): # pragma: no cover
"""
Notifies generic error on blockwise exchange.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction
"""
transaction.block_transfer = True
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.type = defines.Types["RST"]
transaction.response.token = transaction.request.token
transaction.response.code = code
return transaction | [
"def",
"error",
"(",
"transaction",
",",
"code",
")",
":",
"# pragma: no cover",
"transaction",
".",
"block_transfer",
"=",
"True",
"transaction",
".",
"response",
"=",
"Response",
"(",
")",
"transaction",
".",
"response",
".",
"destination",
"=",
"transaction",... | Notifies generic error on blockwise exchange.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction | [
"Notifies",
"generic",
"error",
"on",
"blockwise",
"exchange",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/blocklayer.py#L293-L308 | train | 210,654 |
Tanganelli/CoAPthon3 | coapthon/layers/observelayer.py | ObserveLayer.send_request | def send_request(self, request):
"""
Add itself to the observing list
:param request: the request
:return: the request unmodified
"""
if request.observe == 0:
# Observe request
host, port = request.destination
key_token = hash(str(host) + str(port) + str(request.token))
self._relations[key_token] = ObserveItem(time.time(), None, True, None)
return request | python | def send_request(self, request):
"""
Add itself to the observing list
:param request: the request
:return: the request unmodified
"""
if request.observe == 0:
# Observe request
host, port = request.destination
key_token = hash(str(host) + str(port) + str(request.token))
self._relations[key_token] = ObserveItem(time.time(), None, True, None)
return request | [
"def",
"send_request",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"observe",
"==",
"0",
":",
"# Observe request",
"host",
",",
"port",
"=",
"request",
".",
"destination",
"key_token",
"=",
"hash",
"(",
"str",
"(",
"host",
")",
"+",
"s... | Add itself to the observing list
:param request: the request
:return: the request unmodified | [
"Add",
"itself",
"to",
"the",
"observing",
"list"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/observelayer.py#L33-L47 | train | 210,655 |
Tanganelli/CoAPthon3 | coapthon/layers/observelayer.py | ObserveLayer.receive_response | def receive_response(self, transaction):
"""
Sets notification's parameters.
:type transaction: Transaction
:param transaction: the transaction
:rtype : Transaction
:return: the modified transaction
"""
host, port = transaction.response.source
key_token = hash(str(host) + str(port) + str(transaction.response.token))
if key_token in self._relations and transaction.response.type == defines.Types["CON"]:
transaction.notification = True
return transaction | python | def receive_response(self, transaction):
"""
Sets notification's parameters.
:type transaction: Transaction
:param transaction: the transaction
:rtype : Transaction
:return: the modified transaction
"""
host, port = transaction.response.source
key_token = hash(str(host) + str(port) + str(transaction.response.token))
if key_token in self._relations and transaction.response.type == defines.Types["CON"]:
transaction.notification = True
return transaction | [
"def",
"receive_response",
"(",
"self",
",",
"transaction",
")",
":",
"host",
",",
"port",
"=",
"transaction",
".",
"response",
".",
"source",
"key_token",
"=",
"hash",
"(",
"str",
"(",
"host",
")",
"+",
"str",
"(",
"port",
")",
"+",
"str",
"(",
"tra... | Sets notification's parameters.
:type transaction: Transaction
:param transaction: the transaction
:rtype : Transaction
:return: the modified transaction | [
"Sets",
"notification",
"s",
"parameters",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/observelayer.py#L49-L62 | train | 210,656 |
Tanganelli/CoAPthon3 | coapthon/layers/observelayer.py | ObserveLayer.send_empty | def send_empty(self, message):
"""
Eventually remove from the observer list in case of a RST message.
:type message: Message
:param message: the message
:return: the message unmodified
"""
host, port = message.destination
key_token = hash(str(host) + str(port) + str(message.token))
if key_token in self._relations and message.type == defines.Types["RST"]:
del self._relations[key_token]
return message | python | def send_empty(self, message):
"""
Eventually remove from the observer list in case of a RST message.
:type message: Message
:param message: the message
:return: the message unmodified
"""
host, port = message.destination
key_token = hash(str(host) + str(port) + str(message.token))
if key_token in self._relations and message.type == defines.Types["RST"]:
del self._relations[key_token]
return message | [
"def",
"send_empty",
"(",
"self",
",",
"message",
")",
":",
"host",
",",
"port",
"=",
"message",
".",
"destination",
"key_token",
"=",
"hash",
"(",
"str",
"(",
"host",
")",
"+",
"str",
"(",
"port",
")",
"+",
"str",
"(",
"message",
".",
"token",
")"... | Eventually remove from the observer list in case of a RST message.
:type message: Message
:param message: the message
:return: the message unmodified | [
"Eventually",
"remove",
"from",
"the",
"observer",
"list",
"in",
"case",
"of",
"a",
"RST",
"message",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/observelayer.py#L64-L76 | train | 210,657 |
Tanganelli/CoAPthon3 | coapthon/layers/observelayer.py | ObserveLayer.receive_request | def receive_request(self, transaction):
"""
Manage the observe option in the request end eventually initialize the client for adding to
the list of observers or remove from the list.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the modified transaction
"""
if transaction.request.observe == 0:
# Observe request
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
non_counter = 0
if key_token in self._relations:
# Renew registration
allowed = True
else:
allowed = False
self._relations[key_token] = ObserveItem(time.time(), non_counter, allowed, transaction)
elif transaction.request.observe == 1:
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
logger.info("Remove Subscriber")
try:
del self._relations[key_token]
except KeyError:
pass
return transaction | python | def receive_request(self, transaction):
"""
Manage the observe option in the request end eventually initialize the client for adding to
the list of observers or remove from the list.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the modified transaction
"""
if transaction.request.observe == 0:
# Observe request
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
non_counter = 0
if key_token in self._relations:
# Renew registration
allowed = True
else:
allowed = False
self._relations[key_token] = ObserveItem(time.time(), non_counter, allowed, transaction)
elif transaction.request.observe == 1:
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
logger.info("Remove Subscriber")
try:
del self._relations[key_token]
except KeyError:
pass
return transaction | [
"def",
"receive_request",
"(",
"self",
",",
"transaction",
")",
":",
"if",
"transaction",
".",
"request",
".",
"observe",
"==",
"0",
":",
"# Observe request",
"host",
",",
"port",
"=",
"transaction",
".",
"request",
".",
"source",
"key_token",
"=",
"hash",
... | Manage the observe option in the request end eventually initialize the client for adding to
the list of observers or remove from the list.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the modified transaction | [
"Manage",
"the",
"observe",
"option",
"in",
"the",
"request",
"end",
"eventually",
"initialize",
"the",
"client",
"for",
"adding",
"to",
"the",
"list",
"of",
"observers",
"or",
"remove",
"from",
"the",
"list",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/observelayer.py#L78-L108 | train | 210,658 |
Tanganelli/CoAPthon3 | coapthon/layers/observelayer.py | ObserveLayer.receive_empty | def receive_empty(self, empty, transaction):
"""
Manage the observe feature to remove a client in case of a RST message receveide in reply to a notification.
:type empty: Message
:param empty: the received message
:type transaction: Transaction
:param transaction: the transaction that owns the notification message
:rtype : Transaction
:return: the modified transaction
"""
if empty.type == defines.Types["RST"]:
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
logger.info("Remove Subscriber")
try:
del self._relations[key_token]
except KeyError:
pass
transaction.completed = True
return transaction | python | def receive_empty(self, empty, transaction):
"""
Manage the observe feature to remove a client in case of a RST message receveide in reply to a notification.
:type empty: Message
:param empty: the received message
:type transaction: Transaction
:param transaction: the transaction that owns the notification message
:rtype : Transaction
:return: the modified transaction
"""
if empty.type == defines.Types["RST"]:
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
logger.info("Remove Subscriber")
try:
del self._relations[key_token]
except KeyError:
pass
transaction.completed = True
return transaction | [
"def",
"receive_empty",
"(",
"self",
",",
"empty",
",",
"transaction",
")",
":",
"if",
"empty",
".",
"type",
"==",
"defines",
".",
"Types",
"[",
"\"RST\"",
"]",
":",
"host",
",",
"port",
"=",
"transaction",
".",
"request",
".",
"source",
"key_token",
"... | Manage the observe feature to remove a client in case of a RST message receveide in reply to a notification.
:type empty: Message
:param empty: the received message
:type transaction: Transaction
:param transaction: the transaction that owns the notification message
:rtype : Transaction
:return: the modified transaction | [
"Manage",
"the",
"observe",
"feature",
"to",
"remove",
"a",
"client",
"in",
"case",
"of",
"a",
"RST",
"message",
"receveide",
"in",
"reply",
"to",
"a",
"notification",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/observelayer.py#L110-L130 | train | 210,659 |
Tanganelli/CoAPthon3 | coapthon/layers/observelayer.py | ObserveLayer.send_response | def send_response(self, transaction):
"""
Finalize to add the client to the list of observer.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:return: the transaction unmodified
"""
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
if key_token in self._relations:
if transaction.response.code == defines.Codes.CONTENT.number:
if transaction.resource is not None and transaction.resource.observable:
transaction.response.observe = transaction.resource.observe_count
self._relations[key_token].allowed = True
self._relations[key_token].transaction = transaction
self._relations[key_token].timestamp = time.time()
else:
del self._relations[key_token]
elif transaction.response.code >= defines.Codes.ERROR_LOWER_BOUND:
del self._relations[key_token]
return transaction | python | def send_response(self, transaction):
"""
Finalize to add the client to the list of observer.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:return: the transaction unmodified
"""
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
if key_token in self._relations:
if transaction.response.code == defines.Codes.CONTENT.number:
if transaction.resource is not None and transaction.resource.observable:
transaction.response.observe = transaction.resource.observe_count
self._relations[key_token].allowed = True
self._relations[key_token].transaction = transaction
self._relations[key_token].timestamp = time.time()
else:
del self._relations[key_token]
elif transaction.response.code >= defines.Codes.ERROR_LOWER_BOUND:
del self._relations[key_token]
return transaction | [
"def",
"send_response",
"(",
"self",
",",
"transaction",
")",
":",
"host",
",",
"port",
"=",
"transaction",
".",
"request",
".",
"source",
"key_token",
"=",
"hash",
"(",
"str",
"(",
"host",
")",
"+",
"str",
"(",
"port",
")",
"+",
"str",
"(",
"transac... | Finalize to add the client to the list of observer.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:return: the transaction unmodified | [
"Finalize",
"to",
"add",
"the",
"client",
"to",
"the",
"list",
"of",
"observer",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/observelayer.py#L132-L154 | train | 210,660 |
Tanganelli/CoAPthon3 | coapthon/layers/observelayer.py | ObserveLayer.notify | def notify(self, resource, root=None):
"""
Prepare notification for the resource to all interested observers.
:rtype: list
:param resource: the resource for which send a new notification
:param root: deprecated
:return: the list of transactions to be notified
"""
ret = []
if root is not None:
resource_list = root.with_prefix_resource(resource.path)
else:
resource_list = [resource]
for key in list(self._relations.keys()):
if self._relations[key].transaction.resource in resource_list:
if self._relations[key].non_counter > defines.MAX_NON_NOTIFICATIONS \
or self._relations[key].transaction.request.type == defines.Types["CON"]:
self._relations[key].transaction.response.type = defines.Types["CON"]
self._relations[key].non_counter = 0
elif self._relations[key].transaction.request.type == defines.Types["NON"]:
self._relations[key].non_counter += 1
self._relations[key].transaction.response.type = defines.Types["NON"]
self._relations[key].transaction.resource = resource
del self._relations[key].transaction.response.mid
del self._relations[key].transaction.response.token
ret.append(self._relations[key].transaction)
return ret | python | def notify(self, resource, root=None):
"""
Prepare notification for the resource to all interested observers.
:rtype: list
:param resource: the resource for which send a new notification
:param root: deprecated
:return: the list of transactions to be notified
"""
ret = []
if root is not None:
resource_list = root.with_prefix_resource(resource.path)
else:
resource_list = [resource]
for key in list(self._relations.keys()):
if self._relations[key].transaction.resource in resource_list:
if self._relations[key].non_counter > defines.MAX_NON_NOTIFICATIONS \
or self._relations[key].transaction.request.type == defines.Types["CON"]:
self._relations[key].transaction.response.type = defines.Types["CON"]
self._relations[key].non_counter = 0
elif self._relations[key].transaction.request.type == defines.Types["NON"]:
self._relations[key].non_counter += 1
self._relations[key].transaction.response.type = defines.Types["NON"]
self._relations[key].transaction.resource = resource
del self._relations[key].transaction.response.mid
del self._relations[key].transaction.response.token
ret.append(self._relations[key].transaction)
return ret | [
"def",
"notify",
"(",
"self",
",",
"resource",
",",
"root",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"root",
"is",
"not",
"None",
":",
"resource_list",
"=",
"root",
".",
"with_prefix_resource",
"(",
"resource",
".",
"path",
")",
"else",
":"... | Prepare notification for the resource to all interested observers.
:rtype: list
:param resource: the resource for which send a new notification
:param root: deprecated
:return: the list of transactions to be notified | [
"Prepare",
"notification",
"for",
"the",
"resource",
"to",
"all",
"interested",
"observers",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/observelayer.py#L156-L183 | train | 210,661 |
Tanganelli/CoAPthon3 | coapthon/layers/observelayer.py | ObserveLayer.remove_subscriber | def remove_subscriber(self, message):
"""
Remove a subscriber based on token.
:param message: the message
"""
logger.debug("Remove Subcriber")
host, port = message.destination
key_token = hash(str(host) + str(port) + str(message.token))
try:
self._relations[key_token].transaction.completed = True
del self._relations[key_token]
except KeyError:
logger.warning("No Subscriber") | python | def remove_subscriber(self, message):
"""
Remove a subscriber based on token.
:param message: the message
"""
logger.debug("Remove Subcriber")
host, port = message.destination
key_token = hash(str(host) + str(port) + str(message.token))
try:
self._relations[key_token].transaction.completed = True
del self._relations[key_token]
except KeyError:
logger.warning("No Subscriber") | [
"def",
"remove_subscriber",
"(",
"self",
",",
"message",
")",
":",
"logger",
".",
"debug",
"(",
"\"Remove Subcriber\"",
")",
"host",
",",
"port",
"=",
"message",
".",
"destination",
"key_token",
"=",
"hash",
"(",
"str",
"(",
"host",
")",
"+",
"str",
"(",... | Remove a subscriber based on token.
:param message: the message | [
"Remove",
"a",
"subscriber",
"based",
"on",
"token",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/observelayer.py#L185-L198 | train | 210,662 |
Tanganelli/CoAPthon3 | coapthon/forward_proxy/coap.py | CoAP.purge | def purge(self):
"""
Clean old transactions
"""
while not self.stopped.isSet():
self.stopped.wait(timeout=defines.EXCHANGE_LIFETIME)
self._messageLayer.purge() | python | def purge(self):
"""
Clean old transactions
"""
while not self.stopped.isSet():
self.stopped.wait(timeout=defines.EXCHANGE_LIFETIME)
self._messageLayer.purge() | [
"def",
"purge",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"stopped",
".",
"isSet",
"(",
")",
":",
"self",
".",
"stopped",
".",
"wait",
"(",
"timeout",
"=",
"defines",
".",
"EXCHANGE_LIFETIME",
")",
"self",
".",
"_messageLayer",
".",
"purge",
... | Clean old transactions | [
"Clean",
"old",
"transactions"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/forward_proxy/coap.py#L122-L128 | train | 210,663 |
Tanganelli/CoAPthon3 | coapthon/forward_proxy/coap.py | CoAP.send_datagram | def send_datagram(self, message):
"""
Send a message through the udp socket.
:type message: Message
:param message: the message to send
"""
if not self.stopped.isSet():
host, port = message.destination
logger.debug("send_datagram - " + str(message))
serializer = Serializer()
message = serializer.serialize(message)
self._socket.sendto(message, (host, port)) | python | def send_datagram(self, message):
"""
Send a message through the udp socket.
:type message: Message
:param message: the message to send
"""
if not self.stopped.isSet():
host, port = message.destination
logger.debug("send_datagram - " + str(message))
serializer = Serializer()
message = serializer.serialize(message)
self._socket.sendto(message, (host, port)) | [
"def",
"send_datagram",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"stopped",
".",
"isSet",
"(",
")",
":",
"host",
",",
"port",
"=",
"message",
".",
"destination",
"logger",
".",
"debug",
"(",
"\"send_datagram - \"",
"+",
"str",
"... | Send a message through the udp socket.
:type message: Message
:param message: the message to send | [
"Send",
"a",
"message",
"through",
"the",
"udp",
"socket",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/forward_proxy/coap.py#L263-L277 | train | 210,664 |
Tanganelli/CoAPthon3 | coapthon/forward_proxy/coap.py | CoAP._retransmit | def _retransmit(self, transaction, message, future_time, retransmit_count):
"""
Thread function to retransmit the message in the future
:param transaction: the transaction that owns the message that needs retransmission
:param message: the message that needs the retransmission task
:param future_time: the amount of time to wait before a new attempt
:param retransmit_count: the number of retransmissions
"""
with transaction:
while retransmit_count < defines.MAX_RETRANSMIT and (not message.acknowledged and not message.rejected) \
and not self.stopped.isSet():
transaction.retransmit_stop.wait(timeout=future_time)
if not message.acknowledged and not message.rejected and not self.stopped.isSet():
retransmit_count += 1
future_time *= 2
self.send_datagram(message)
if message.acknowledged or message.rejected:
message.timeouted = False
else:
logger.warning("Give up on message {message}".format(message=message.line_print))
message.timeouted = True
if message.observe is not None:
self._observeLayer.remove_subscriber(message)
try:
self.to_be_stopped.remove(transaction.retransmit_stop)
except ValueError:
pass
transaction.retransmit_stop = None
transaction.retransmit_thread = None | python | def _retransmit(self, transaction, message, future_time, retransmit_count):
"""
Thread function to retransmit the message in the future
:param transaction: the transaction that owns the message that needs retransmission
:param message: the message that needs the retransmission task
:param future_time: the amount of time to wait before a new attempt
:param retransmit_count: the number of retransmissions
"""
with transaction:
while retransmit_count < defines.MAX_RETRANSMIT and (not message.acknowledged and not message.rejected) \
and not self.stopped.isSet():
transaction.retransmit_stop.wait(timeout=future_time)
if not message.acknowledged and not message.rejected and not self.stopped.isSet():
retransmit_count += 1
future_time *= 2
self.send_datagram(message)
if message.acknowledged or message.rejected:
message.timeouted = False
else:
logger.warning("Give up on message {message}".format(message=message.line_print))
message.timeouted = True
if message.observe is not None:
self._observeLayer.remove_subscriber(message)
try:
self.to_be_stopped.remove(transaction.retransmit_stop)
except ValueError:
pass
transaction.retransmit_stop = None
transaction.retransmit_thread = None | [
"def",
"_retransmit",
"(",
"self",
",",
"transaction",
",",
"message",
",",
"future_time",
",",
"retransmit_count",
")",
":",
"with",
"transaction",
":",
"while",
"retransmit_count",
"<",
"defines",
".",
"MAX_RETRANSMIT",
"and",
"(",
"not",
"message",
".",
"ac... | Thread function to retransmit the message in the future
:param transaction: the transaction that owns the message that needs retransmission
:param message: the message that needs the retransmission task
:param future_time: the amount of time to wait before a new attempt
:param retransmit_count: the number of retransmissions | [
"Thread",
"function",
"to",
"retransmit",
"the",
"message",
"in",
"the",
"future"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/forward_proxy/coap.py#L297-L328 | train | 210,665 |
Tanganelli/CoAPthon3 | coapthon/forward_proxy/coap.py | CoAP._start_separate_timer | def _start_separate_timer(self, transaction):
"""
Start a thread to handle separate mode.
:type transaction: Transaction
:param transaction: the transaction that is in processing
:rtype : the Timer object
"""
t = threading.Timer(defines.ACK_TIMEOUT, self._send_ack, (transaction,))
t.start()
return t | python | def _start_separate_timer(self, transaction):
"""
Start a thread to handle separate mode.
:type transaction: Transaction
:param transaction: the transaction that is in processing
:rtype : the Timer object
"""
t = threading.Timer(defines.ACK_TIMEOUT, self._send_ack, (transaction,))
t.start()
return t | [
"def",
"_start_separate_timer",
"(",
"self",
",",
"transaction",
")",
":",
"t",
"=",
"threading",
".",
"Timer",
"(",
"defines",
".",
"ACK_TIMEOUT",
",",
"self",
".",
"_send_ack",
",",
"(",
"transaction",
",",
")",
")",
"t",
".",
"start",
"(",
")",
"ret... | Start a thread to handle separate mode.
:type transaction: Transaction
:param transaction: the transaction that is in processing
:rtype : the Timer object | [
"Start",
"a",
"thread",
"to",
"handle",
"separate",
"mode",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/forward_proxy/coap.py#L330-L340 | train | 210,666 |
Tanganelli/CoAPthon3 | coapthon/reverse_proxy/coap.py | CoAP.parse_config | def parse_config(self):
"""
Parse the xml file with remote servers and discover resources on each found server.
"""
tree = ElementTree.parse(self.file_xml)
root = tree.getroot()
for server in root.findall('server'):
destination = server.text
name = server.get("name")
self.discover_remote(destination, name) | python | def parse_config(self):
"""
Parse the xml file with remote servers and discover resources on each found server.
"""
tree = ElementTree.parse(self.file_xml)
root = tree.getroot()
for server in root.findall('server'):
destination = server.text
name = server.get("name")
self.discover_remote(destination, name) | [
"def",
"parse_config",
"(",
"self",
")",
":",
"tree",
"=",
"ElementTree",
".",
"parse",
"(",
"self",
".",
"file_xml",
")",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"for",
"server",
"in",
"root",
".",
"findall",
"(",
"'server'",
")",
":",
"desti... | Parse the xml file with remote servers and discover resources on each found server. | [
"Parse",
"the",
"xml",
"file",
"with",
"remote",
"servers",
"and",
"discover",
"resources",
"on",
"each",
"found",
"server",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/reverse_proxy/coap.py#L130-L139 | train | 210,667 |
Tanganelli/CoAPthon3 | coapthon/reverse_proxy/coap.py | CoAP.discover_remote | def discover_remote(self, destination, name):
"""
Discover resources on remote servers.
:param destination: the remote server (ip, port)
:type destination: tuple
:param name: the name of the remote server
:type name: String
"""
assert (isinstance(destination, str))
if destination.startswith("["):
split = destination.split("]", 1)
host = split[0][1:]
port = int(split[1][1:])
else:
split = destination.split(":", 1)
host = split[0]
port = int(split[1])
server = (host, port)
client = HelperClient(server)
response = client.discover()
client.stop()
self.discover_remote_results(response, name) | python | def discover_remote(self, destination, name):
"""
Discover resources on remote servers.
:param destination: the remote server (ip, port)
:type destination: tuple
:param name: the name of the remote server
:type name: String
"""
assert (isinstance(destination, str))
if destination.startswith("["):
split = destination.split("]", 1)
host = split[0][1:]
port = int(split[1][1:])
else:
split = destination.split(":", 1)
host = split[0]
port = int(split[1])
server = (host, port)
client = HelperClient(server)
response = client.discover()
client.stop()
self.discover_remote_results(response, name) | [
"def",
"discover_remote",
"(",
"self",
",",
"destination",
",",
"name",
")",
":",
"assert",
"(",
"isinstance",
"(",
"destination",
",",
"str",
")",
")",
"if",
"destination",
".",
"startswith",
"(",
"\"[\"",
")",
":",
"split",
"=",
"destination",
".",
"sp... | Discover resources on remote servers.
:param destination: the remote server (ip, port)
:type destination: tuple
:param name: the name of the remote server
:type name: String | [
"Discover",
"resources",
"on",
"remote",
"servers",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/reverse_proxy/coap.py#L141-L163 | train | 210,668 |
Tanganelli/CoAPthon3 | coapthon/reverse_proxy/coap.py | CoAP.discover_remote_results | def discover_remote_results(self, response, name):
"""
Create a new remote server resource for each valid discover response.
:param response: the response to the discovery request
:param name: the server name
"""
host, port = response.source
if response.code == defines.Codes.CONTENT.number:
resource = Resource('server', self, visible=True, observable=False, allow_children=True)
self.add_resource(name, resource)
self._mapping[name] = (host, port)
self.parse_core_link_format(response.payload, name, (host, port))
else:
logger.error("Server: " + response.source + " isn't valid.") | python | def discover_remote_results(self, response, name):
"""
Create a new remote server resource for each valid discover response.
:param response: the response to the discovery request
:param name: the server name
"""
host, port = response.source
if response.code == defines.Codes.CONTENT.number:
resource = Resource('server', self, visible=True, observable=False, allow_children=True)
self.add_resource(name, resource)
self._mapping[name] = (host, port)
self.parse_core_link_format(response.payload, name, (host, port))
else:
logger.error("Server: " + response.source + " isn't valid.") | [
"def",
"discover_remote_results",
"(",
"self",
",",
"response",
",",
"name",
")",
":",
"host",
",",
"port",
"=",
"response",
".",
"source",
"if",
"response",
".",
"code",
"==",
"defines",
".",
"Codes",
".",
"CONTENT",
".",
"number",
":",
"resource",
"=",... | Create a new remote server resource for each valid discover response.
:param response: the response to the discovery request
:param name: the server name | [
"Create",
"a",
"new",
"remote",
"server",
"resource",
"for",
"each",
"valid",
"discover",
"response",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/reverse_proxy/coap.py#L165-L180 | train | 210,669 |
Tanganelli/CoAPthon3 | coapthon/reverse_proxy/coap.py | CoAP.parse_core_link_format | def parse_core_link_format(self, link_format, base_path, remote_server):
"""
Parse discovery results.
:param link_format: the payload of the response to the discovery request
:param base_path: the base path used to create child resources discovered on the remote server
:param remote_server: the (ip, port) of the remote server
"""
while len(link_format) > 0:
pattern = "<([^>]*)>;"
result = re.match(pattern, link_format)
path = result.group(1)
path = path.split("/")
path = path[1:][0]
link_format = link_format[result.end(1) + 2:]
pattern = "([^<,])*"
result = re.match(pattern, link_format)
attributes = result.group(0)
dict_att = {}
if len(attributes) > 0:
attributes = attributes.split(";")
for att in attributes:
a = att.split("=")
if len(a) > 1:
dict_att[a[0]] = a[1]
else:
dict_att[a[0]] = a[0]
link_format = link_format[result.end(0) + 1:]
# TODO handle observing
resource = RemoteResource('server', remote_server, path, coap_server=self, visible=True, observable=False,
allow_children=True)
resource.attributes = dict_att
self.add_resource(base_path + "/" + path, resource)
logger.info(self.root.dump()) | python | def parse_core_link_format(self, link_format, base_path, remote_server):
"""
Parse discovery results.
:param link_format: the payload of the response to the discovery request
:param base_path: the base path used to create child resources discovered on the remote server
:param remote_server: the (ip, port) of the remote server
"""
while len(link_format) > 0:
pattern = "<([^>]*)>;"
result = re.match(pattern, link_format)
path = result.group(1)
path = path.split("/")
path = path[1:][0]
link_format = link_format[result.end(1) + 2:]
pattern = "([^<,])*"
result = re.match(pattern, link_format)
attributes = result.group(0)
dict_att = {}
if len(attributes) > 0:
attributes = attributes.split(";")
for att in attributes:
a = att.split("=")
if len(a) > 1:
dict_att[a[0]] = a[1]
else:
dict_att[a[0]] = a[0]
link_format = link_format[result.end(0) + 1:]
# TODO handle observing
resource = RemoteResource('server', remote_server, path, coap_server=self, visible=True, observable=False,
allow_children=True)
resource.attributes = dict_att
self.add_resource(base_path + "/" + path, resource)
logger.info(self.root.dump()) | [
"def",
"parse_core_link_format",
"(",
"self",
",",
"link_format",
",",
"base_path",
",",
"remote_server",
")",
":",
"while",
"len",
"(",
"link_format",
")",
">",
"0",
":",
"pattern",
"=",
"\"<([^>]*)>;\"",
"result",
"=",
"re",
".",
"match",
"(",
"pattern",
... | Parse discovery results.
:param link_format: the payload of the response to the discovery request
:param base_path: the base path used to create child resources discovered on the remote server
:param remote_server: the (ip, port) of the remote server | [
"Parse",
"discovery",
"results",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/reverse_proxy/coap.py#L182-L216 | train | 210,670 |
Tanganelli/CoAPthon3 | coapthon/reverse_proxy/coap.py | CoAP.receive_datagram | def receive_datagram(self, args):
"""
Handle messages coming from the udp socket.
:param args: (data, client_address)
"""
data, client_address = args
serializer = Serializer()
message = serializer.deserialize(data, client_address)
if isinstance(message, int):
logger.error("receive_datagram - BAD REQUEST")
rst = Message()
rst.destination = client_address
rst.type = defines.Types["RST"]
rst.code = message
self.send_datagram(rst)
return
logger.debug("receive_datagram - " + str(message))
if isinstance(message, Request):
transaction = self._messageLayer.receive_request(message)
if transaction.request.duplicated and transaction.completed:
logger.debug("message duplicated,transaction completed")
transaction = self._observeLayer.send_response(transaction)
transaction = self._blockLayer.send_response(transaction)
transaction = self._messageLayer.send_response(transaction)
self.send_datagram(transaction.response)
return
elif transaction.request.duplicated and not transaction.completed:
logger.debug("message duplicated,transaction NOT completed")
self._send_ack(transaction)
return
transaction.separate_timer = self._start_separate_timer(transaction)
transaction = self._blockLayer.receive_request(transaction)
if transaction.block_transfer:
self._stop_separate_timer(transaction.separate_timer)
transaction = self._messageLayer.send_response(transaction)
self.send_datagram(transaction.response)
return
transaction = self._observeLayer.receive_request(transaction)
"""
call to the cache layer to check if there's a cached response for the request
if not, call the forward layer
"""
if self._cacheLayer is not None:
transaction = self._cacheLayer.receive_request(transaction)
if transaction.cacheHit is False:
logger.debug(transaction.request)
transaction = self._forwardLayer.receive_request_reverse(transaction)
logger.debug(transaction.response)
transaction = self._observeLayer.send_response(transaction)
transaction = self._blockLayer.send_response(transaction)
transaction = self._cacheLayer.send_response(transaction)
else:
transaction = self._forwardLayer.receive_request_reverse(transaction)
transaction = self._observeLayer.send_response(transaction)
transaction = self._blockLayer.send_response(transaction)
self._stop_separate_timer(transaction.separate_timer)
transaction = self._messageLayer.send_response(transaction)
if transaction.response is not None:
if transaction.response.type == defines.Types["CON"]:
self._start_retrasmission(transaction, transaction.response)
self.send_datagram(transaction.response)
elif isinstance(message, Message):
transaction = self._messageLayer.receive_empty(message)
if transaction is not None:
transaction = self._blockLayer.receive_empty(message, transaction)
self._observeLayer.receive_empty(message, transaction)
else: # pragma: no cover
logger.error("Received response from %s", message.source) | python | def receive_datagram(self, args):
"""
Handle messages coming from the udp socket.
:param args: (data, client_address)
"""
data, client_address = args
serializer = Serializer()
message = serializer.deserialize(data, client_address)
if isinstance(message, int):
logger.error("receive_datagram - BAD REQUEST")
rst = Message()
rst.destination = client_address
rst.type = defines.Types["RST"]
rst.code = message
self.send_datagram(rst)
return
logger.debug("receive_datagram - " + str(message))
if isinstance(message, Request):
transaction = self._messageLayer.receive_request(message)
if transaction.request.duplicated and transaction.completed:
logger.debug("message duplicated,transaction completed")
transaction = self._observeLayer.send_response(transaction)
transaction = self._blockLayer.send_response(transaction)
transaction = self._messageLayer.send_response(transaction)
self.send_datagram(transaction.response)
return
elif transaction.request.duplicated and not transaction.completed:
logger.debug("message duplicated,transaction NOT completed")
self._send_ack(transaction)
return
transaction.separate_timer = self._start_separate_timer(transaction)
transaction = self._blockLayer.receive_request(transaction)
if transaction.block_transfer:
self._stop_separate_timer(transaction.separate_timer)
transaction = self._messageLayer.send_response(transaction)
self.send_datagram(transaction.response)
return
transaction = self._observeLayer.receive_request(transaction)
"""
call to the cache layer to check if there's a cached response for the request
if not, call the forward layer
"""
if self._cacheLayer is not None:
transaction = self._cacheLayer.receive_request(transaction)
if transaction.cacheHit is False:
logger.debug(transaction.request)
transaction = self._forwardLayer.receive_request_reverse(transaction)
logger.debug(transaction.response)
transaction = self._observeLayer.send_response(transaction)
transaction = self._blockLayer.send_response(transaction)
transaction = self._cacheLayer.send_response(transaction)
else:
transaction = self._forwardLayer.receive_request_reverse(transaction)
transaction = self._observeLayer.send_response(transaction)
transaction = self._blockLayer.send_response(transaction)
self._stop_separate_timer(transaction.separate_timer)
transaction = self._messageLayer.send_response(transaction)
if transaction.response is not None:
if transaction.response.type == defines.Types["CON"]:
self._start_retrasmission(transaction, transaction.response)
self.send_datagram(transaction.response)
elif isinstance(message, Message):
transaction = self._messageLayer.receive_empty(message)
if transaction is not None:
transaction = self._blockLayer.receive_empty(message, transaction)
self._observeLayer.receive_empty(message, transaction)
else: # pragma: no cover
logger.error("Received response from %s", message.source) | [
"def",
"receive_datagram",
"(",
"self",
",",
"args",
")",
":",
"data",
",",
"client_address",
"=",
"args",
"serializer",
"=",
"Serializer",
"(",
")",
"message",
"=",
"serializer",
".",
"deserialize",
"(",
"data",
",",
"client_address",
")",
"if",
"isinstance... | Handle messages coming from the udp socket.
:param args: (data, client_address) | [
"Handle",
"messages",
"coming",
"from",
"the",
"udp",
"socket",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/reverse_proxy/coap.py#L256-L344 | train | 210,671 |
Tanganelli/CoAPthon3 | coapthon/client/helperclient.py | HelperClient._wait_response | def _wait_response(self, message):
"""
Private function to get responses from the server.
:param message: the received message
"""
if message is None or message.code != defines.Codes.CONTINUE.number:
self.queue.put(message) | python | def _wait_response(self, message):
"""
Private function to get responses from the server.
:param message: the received message
"""
if message is None or message.code != defines.Codes.CONTINUE.number:
self.queue.put(message) | [
"def",
"_wait_response",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
"is",
"None",
"or",
"message",
".",
"code",
"!=",
"defines",
".",
"Codes",
".",
"CONTINUE",
".",
"number",
":",
"self",
".",
"queue",
".",
"put",
"(",
"message",
")"
] | Private function to get responses from the server.
:param message: the received message | [
"Private",
"function",
"to",
"get",
"responses",
"from",
"the",
"server",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/helperclient.py#L32-L39 | train | 210,672 |
Tanganelli/CoAPthon3 | coapthon/client/helperclient.py | HelperClient._thread_body | def _thread_body(self, request, callback):
"""
Private function. Send a request, wait for response and call the callback function.
:param request: the request to send
:param callback: the callback function
"""
self.protocol.send_message(request)
while not self.protocol.stopped.isSet():
response = self.queue.get(block=True)
callback(response) | python | def _thread_body(self, request, callback):
"""
Private function. Send a request, wait for response and call the callback function.
:param request: the request to send
:param callback: the callback function
"""
self.protocol.send_message(request)
while not self.protocol.stopped.isSet():
response = self.queue.get(block=True)
callback(response) | [
"def",
"_thread_body",
"(",
"self",
",",
"request",
",",
"callback",
")",
":",
"self",
".",
"protocol",
".",
"send_message",
"(",
"request",
")",
"while",
"not",
"self",
".",
"protocol",
".",
"stopped",
".",
"isSet",
"(",
")",
":",
"response",
"=",
"se... | Private function. Send a request, wait for response and call the callback function.
:param request: the request to send
:param callback: the callback function | [
"Private",
"function",
".",
"Send",
"a",
"request",
"wait",
"for",
"response",
"and",
"call",
"the",
"callback",
"function",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/helperclient.py#L54-L64 | train | 210,673 |
Tanganelli/CoAPthon3 | coapthon/client/helperclient.py | HelperClient.cancel_observing | def cancel_observing(self, response, send_rst): # pragma: no cover
"""
Delete observing on the remote server.
:param response: the last received response
:param send_rst: if explicitly send RST message
:type send_rst: bool
"""
if send_rst:
message = Message()
message.destination = self.server
message.code = defines.Codes.EMPTY.number
message.type = defines.Types["RST"]
message.token = response.token
message.mid = response.mid
self.protocol.send_message(message)
self.stop() | python | def cancel_observing(self, response, send_rst): # pragma: no cover
"""
Delete observing on the remote server.
:param response: the last received response
:param send_rst: if explicitly send RST message
:type send_rst: bool
"""
if send_rst:
message = Message()
message.destination = self.server
message.code = defines.Codes.EMPTY.number
message.type = defines.Types["RST"]
message.token = response.token
message.mid = response.mid
self.protocol.send_message(message)
self.stop() | [
"def",
"cancel_observing",
"(",
"self",
",",
"response",
",",
"send_rst",
")",
":",
"# pragma: no cover",
"if",
"send_rst",
":",
"message",
"=",
"Message",
"(",
")",
"message",
".",
"destination",
"=",
"self",
".",
"server",
"message",
".",
"code",
"=",
"d... | Delete observing on the remote server.
:param response: the last received response
:param send_rst: if explicitly send RST message
:type send_rst: bool | [
"Delete",
"observing",
"on",
"the",
"remote",
"server",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/helperclient.py#L66-L82 | train | 210,674 |
Tanganelli/CoAPthon3 | coapthon/client/helperclient.py | HelperClient.observe | def observe(self, path, callback, timeout=None, **kwargs): # pragma: no cover
"""
Perform a GET with observe on a certain path.
:param path: the path
:param callback: the callback function to invoke upon notifications
:param timeout: the timeout of the request
:return: the response to the observe request
"""
request = self.mk_request(defines.Codes.GET, path)
request.observe = 0
for k, v in kwargs.items():
if hasattr(request, k):
setattr(request, k, v)
return self.send_request(request, callback, timeout) | python | def observe(self, path, callback, timeout=None, **kwargs): # pragma: no cover
"""
Perform a GET with observe on a certain path.
:param path: the path
:param callback: the callback function to invoke upon notifications
:param timeout: the timeout of the request
:return: the response to the observe request
"""
request = self.mk_request(defines.Codes.GET, path)
request.observe = 0
for k, v in kwargs.items():
if hasattr(request, k):
setattr(request, k, v)
return self.send_request(request, callback, timeout) | [
"def",
"observe",
"(",
"self",
",",
"path",
",",
"callback",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"request",
"=",
"self",
".",
"mk_request",
"(",
"defines",
".",
"Codes",
".",
"GET",
",",
"path",
")",
... | Perform a GET with observe on a certain path.
:param path: the path
:param callback: the callback function to invoke upon notifications
:param timeout: the timeout of the request
:return: the response to the observe request | [
"Perform",
"a",
"GET",
"with",
"observe",
"on",
"a",
"certain",
"path",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/helperclient.py#L120-L136 | train | 210,675 |
Tanganelli/CoAPthon3 | coapthon/client/helperclient.py | HelperClient.delete | def delete(self, path, callback=None, timeout=None, **kwargs): # pragma: no cover
"""
Perform a DELETE on a certain path.
:param path: the path
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response
"""
request = self.mk_request(defines.Codes.DELETE, path)
for k, v in kwargs.items():
if hasattr(request, k):
setattr(request, k, v)
return self.send_request(request, callback, timeout) | python | def delete(self, path, callback=None, timeout=None, **kwargs): # pragma: no cover
"""
Perform a DELETE on a certain path.
:param path: the path
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response
"""
request = self.mk_request(defines.Codes.DELETE, path)
for k, v in kwargs.items():
if hasattr(request, k):
setattr(request, k, v)
return self.send_request(request, callback, timeout) | [
"def",
"delete",
"(",
"self",
",",
"path",
",",
"callback",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"request",
"=",
"self",
".",
"mk_request",
"(",
"defines",
".",
"Codes",
".",
"DELETE",
",",
... | Perform a DELETE on a certain path.
:param path: the path
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response | [
"Perform",
"a",
"DELETE",
"on",
"a",
"certain",
"path",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/helperclient.py#L138-L153 | train | 210,676 |
Tanganelli/CoAPthon3 | coapthon/client/helperclient.py | HelperClient.post | def post(self, path, payload, callback=None, timeout=None, no_response=False, **kwargs): # pragma: no cover
"""
Perform a POST on a certain path.
:param path: the path
:param payload: the request payload
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response
"""
request = self.mk_request(defines.Codes.POST, path)
request.token = generate_random_token(2)
request.payload = payload
if no_response:
request.add_no_response()
request.type = defines.Types["NON"]
for k, v in kwargs.items():
if hasattr(request, k):
setattr(request, k, v)
return self.send_request(request, callback, timeout, no_response=no_response) | python | def post(self, path, payload, callback=None, timeout=None, no_response=False, **kwargs): # pragma: no cover
"""
Perform a POST on a certain path.
:param path: the path
:param payload: the request payload
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response
"""
request = self.mk_request(defines.Codes.POST, path)
request.token = generate_random_token(2)
request.payload = payload
if no_response:
request.add_no_response()
request.type = defines.Types["NON"]
for k, v in kwargs.items():
if hasattr(request, k):
setattr(request, k, v)
return self.send_request(request, callback, timeout, no_response=no_response) | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"payload",
",",
"callback",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"no_response",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"request",
"=",
"self",
".",
"mk_request",
"(... | Perform a POST on a certain path.
:param path: the path
:param payload: the request payload
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response | [
"Perform",
"a",
"POST",
"on",
"a",
"certain",
"path",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/helperclient.py#L155-L177 | train | 210,677 |
Tanganelli/CoAPthon3 | coapthon/client/helperclient.py | HelperClient.discover | def discover(self, callback=None, timeout=None, **kwargs): # pragma: no cover
"""
Perform a Discover request on the server.
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response
"""
request = self.mk_request(defines.Codes.GET, defines.DISCOVERY_URL)
for k, v in kwargs.items():
if hasattr(request, k):
setattr(request, k, v)
return self.send_request(request, callback, timeout) | python | def discover(self, callback=None, timeout=None, **kwargs): # pragma: no cover
"""
Perform a Discover request on the server.
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response
"""
request = self.mk_request(defines.Codes.GET, defines.DISCOVERY_URL)
for k, v in kwargs.items():
if hasattr(request, k):
setattr(request, k, v)
return self.send_request(request, callback, timeout) | [
"def",
"discover",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"request",
"=",
"self",
".",
"mk_request",
"(",
"defines",
".",
"Codes",
".",
"GET",
",",
"defines",
"."... | Perform a Discover request on the server.
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response | [
"Perform",
"a",
"Discover",
"request",
"on",
"the",
"server",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/helperclient.py#L203-L217 | train | 210,678 |
Tanganelli/CoAPthon3 | coapthon/client/helperclient.py | HelperClient.send_request | def send_request(self, request, callback=None, timeout=None, no_response=False): # pragma: no cover
"""
Send a request to the remote server.
:param request: the request to send
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response
"""
if callback is not None:
thread = threading.Thread(target=self._thread_body, args=(request, callback))
thread.start()
else:
self.protocol.send_message(request)
if no_response:
return
try:
response = self.queue.get(block=True, timeout=timeout)
except Empty:
#if timeout is set
response = None
return response | python | def send_request(self, request, callback=None, timeout=None, no_response=False): # pragma: no cover
"""
Send a request to the remote server.
:param request: the request to send
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response
"""
if callback is not None:
thread = threading.Thread(target=self._thread_body, args=(request, callback))
thread.start()
else:
self.protocol.send_message(request)
if no_response:
return
try:
response = self.queue.get(block=True, timeout=timeout)
except Empty:
#if timeout is set
response = None
return response | [
"def",
"send_request",
"(",
"self",
",",
"request",
",",
"callback",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"no_response",
"=",
"False",
")",
":",
"# pragma: no cover",
"if",
"callback",
"is",
"not",
"None",
":",
"thread",
"=",
"threading",
".",
... | Send a request to the remote server.
:param request: the request to send
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response | [
"Send",
"a",
"request",
"to",
"the",
"remote",
"server",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/helperclient.py#L219-L240 | train | 210,679 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxy.run | def run(self):
"""
Start the proxy.
"""
server_address = (self.ip, self.hc_port)
hc_proxy = HTTPServer(server_address, HCProxyHandler)
logger.info('Starting HTTP-CoAP Proxy...')
hc_proxy.serve_forever() | python | def run(self):
"""
Start the proxy.
"""
server_address = (self.ip, self.hc_port)
hc_proxy = HTTPServer(server_address, HCProxyHandler)
logger.info('Starting HTTP-CoAP Proxy...')
hc_proxy.serve_forever() | [
"def",
"run",
"(",
"self",
")",
":",
"server_address",
"=",
"(",
"self",
".",
"ip",
",",
"self",
".",
"hc_port",
")",
"hc_proxy",
"=",
"HTTPServer",
"(",
"server_address",
",",
"HCProxyHandler",
")",
"logger",
".",
"info",
"(",
"'Starting HTTP-CoAP Proxy...'... | Start the proxy. | [
"Start",
"the",
"proxy",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L46-L53 | train | 210,680 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxy.get_formatted_path | def get_formatted_path(path):
"""
Uniform the path string
:param path: the path
:return: the uniform path
"""
if path[0] != '/':
path = '/' + path
if path[-1] != '/':
path = '{0}/'.format(path)
return path | python | def get_formatted_path(path):
"""
Uniform the path string
:param path: the path
:return: the uniform path
"""
if path[0] != '/':
path = '/' + path
if path[-1] != '/':
path = '{0}/'.format(path)
return path | [
"def",
"get_formatted_path",
"(",
"path",
")",
":",
"if",
"path",
"[",
"0",
"]",
"!=",
"'/'",
":",
"path",
"=",
"'/'",
"+",
"path",
"if",
"path",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"path",
"=",
"'{0}/'",
".",
"format",
"(",
"path",
")",
"ret... | Uniform the path string
:param path: the path
:return: the uniform path | [
"Uniform",
"the",
"path",
"string"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L56-L67 | train | 210,681 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | CoapUri.get_payload | def get_payload(self):
"""
Return the query string of the uri.
:return: the query string as a list
"""
temp = self.get_uri_as_list()
query_string = temp[4]
if query_string == "":
return None # Bad request error code
query_string_as_list = str.split(query_string, "=")
return query_string_as_list[1] | python | def get_payload(self):
"""
Return the query string of the uri.
:return: the query string as a list
"""
temp = self.get_uri_as_list()
query_string = temp[4]
if query_string == "":
return None # Bad request error code
query_string_as_list = str.split(query_string, "=")
return query_string_as_list[1] | [
"def",
"get_payload",
"(",
"self",
")",
":",
"temp",
"=",
"self",
".",
"get_uri_as_list",
"(",
")",
"query_string",
"=",
"temp",
"[",
"4",
"]",
"if",
"query_string",
"==",
"\"\"",
":",
"return",
"None",
"# Bad request error code",
"query_string_as_list",
"=",
... | Return the query string of the uri.
:return: the query string as a list | [
"Return",
"the",
"query",
"string",
"of",
"the",
"uri",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L84-L95 | train | 210,682 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.do_initial_operations | def do_initial_operations(self):
"""
Setup the client for interact with remote server
"""
if not self.request_hc_path_corresponds():
# the http URI of the request is not the same of the one specified by the admin for the hc proxy,
# so I do not answer
# For example the admin setup the http proxy URI like: "http://127.0.0.1:8080:/my_hc_path/" and the URI of
# the requests asks for "http://127.0.0.1:8080:/another_hc_path/"
return
self.set_coap_uri()
self.client = HelperClient(server=(self.coap_uri.host, self.coap_uri.port)) | python | def do_initial_operations(self):
"""
Setup the client for interact with remote server
"""
if not self.request_hc_path_corresponds():
# the http URI of the request is not the same of the one specified by the admin for the hc proxy,
# so I do not answer
# For example the admin setup the http proxy URI like: "http://127.0.0.1:8080:/my_hc_path/" and the URI of
# the requests asks for "http://127.0.0.1:8080:/another_hc_path/"
return
self.set_coap_uri()
self.client = HelperClient(server=(self.coap_uri.host, self.coap_uri.port)) | [
"def",
"do_initial_operations",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"request_hc_path_corresponds",
"(",
")",
":",
"# the http URI of the request is not the same of the one specified by the admin for the hc proxy,",
"# so I do not answer",
"# For example the admin setup t... | Setup the client for interact with remote server | [
"Setup",
"the",
"client",
"for",
"interact",
"with",
"remote",
"server"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L112-L123 | train | 210,683 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.do_GET | def do_GET(self):
"""
Perform a GET request
"""
self.do_initial_operations()
coap_response = self.client.get(self.coap_uri.path)
self.client.stop()
logger.info("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | python | def do_GET(self):
"""
Perform a GET request
"""
self.do_initial_operations()
coap_response = self.client.get(self.coap_uri.path)
self.client.stop()
logger.info("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | [
"def",
"do_GET",
"(",
"self",
")",
":",
"self",
".",
"do_initial_operations",
"(",
")",
"coap_response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"coap_uri",
".",
"path",
")",
"self",
".",
"client",
".",
"stop",
"(",
")",
"logger",
"... | Perform a GET request | [
"Perform",
"a",
"GET",
"request"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L125-L133 | train | 210,684 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.do_HEAD | def do_HEAD(self):
"""
Perform a HEAD request
"""
self.do_initial_operations()
# the HEAD method is not present in CoAP, so we treat it
# like if it was a GET and then we exclude the body from the response
# with send_body=False we say that we do not need the body, because it is a HEAD request
coap_response = self.client.get(self.coap_uri.path)
self.client.stop()
logger.info("Server response: %s", coap_response.pretty_print())
self.set_http_header(coap_response) | python | def do_HEAD(self):
"""
Perform a HEAD request
"""
self.do_initial_operations()
# the HEAD method is not present in CoAP, so we treat it
# like if it was a GET and then we exclude the body from the response
# with send_body=False we say that we do not need the body, because it is a HEAD request
coap_response = self.client.get(self.coap_uri.path)
self.client.stop()
logger.info("Server response: %s", coap_response.pretty_print())
self.set_http_header(coap_response) | [
"def",
"do_HEAD",
"(",
"self",
")",
":",
"self",
".",
"do_initial_operations",
"(",
")",
"# the HEAD method is not present in CoAP, so we treat it",
"# like if it was a GET and then we exclude the body from the response",
"# with send_body=False we say that we do not need the body, because... | Perform a HEAD request | [
"Perform",
"a",
"HEAD",
"request"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L135-L146 | train | 210,685 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.do_POST | def do_POST(self):
"""
Perform a POST request
"""
# Doesn't do anything with posted data
# print "uri: ", self.client_address, self.path
self.do_initial_operations()
payload = self.coap_uri.get_payload()
if payload is None:
logger.error("BAD POST REQUEST")
self.send_error(BAD_REQUEST)
return
coap_response = self.client.post(self.coap_uri.path, payload)
self.client.stop()
logger.info("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | python | def do_POST(self):
"""
Perform a POST request
"""
# Doesn't do anything with posted data
# print "uri: ", self.client_address, self.path
self.do_initial_operations()
payload = self.coap_uri.get_payload()
if payload is None:
logger.error("BAD POST REQUEST")
self.send_error(BAD_REQUEST)
return
coap_response = self.client.post(self.coap_uri.path, payload)
self.client.stop()
logger.info("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | [
"def",
"do_POST",
"(",
"self",
")",
":",
"# Doesn't do anything with posted data",
"# print \"uri: \", self.client_address, self.path",
"self",
".",
"do_initial_operations",
"(",
")",
"payload",
"=",
"self",
".",
"coap_uri",
".",
"get_payload",
"(",
")",
"if",
"payload"... | Perform a POST request | [
"Perform",
"a",
"POST",
"request"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L148-L163 | train | 210,686 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.do_PUT | def do_PUT(self):
"""
Perform a PUT request
"""
self.do_initial_operations()
payload = self.coap_uri.get_payload()
if payload is None:
logger.error("BAD PUT REQUEST")
self.send_error(BAD_REQUEST)
return
logger.debug(payload)
coap_response = self.client.put(self.coap_uri.path, payload)
self.client.stop()
logger.debug("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | python | def do_PUT(self):
"""
Perform a PUT request
"""
self.do_initial_operations()
payload = self.coap_uri.get_payload()
if payload is None:
logger.error("BAD PUT REQUEST")
self.send_error(BAD_REQUEST)
return
logger.debug(payload)
coap_response = self.client.put(self.coap_uri.path, payload)
self.client.stop()
logger.debug("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | [
"def",
"do_PUT",
"(",
"self",
")",
":",
"self",
".",
"do_initial_operations",
"(",
")",
"payload",
"=",
"self",
".",
"coap_uri",
".",
"get_payload",
"(",
")",
"if",
"payload",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"\"BAD PUT REQUEST\"",
")",
"s... | Perform a PUT request | [
"Perform",
"a",
"PUT",
"request"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L165-L179 | train | 210,687 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.do_DELETE | def do_DELETE(self):
"""
Perform a DELETE request
"""
self.do_initial_operations()
coap_response = self.client.delete(self.coap_uri.path)
self.client.stop()
logger.debug("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | python | def do_DELETE(self):
"""
Perform a DELETE request
"""
self.do_initial_operations()
coap_response = self.client.delete(self.coap_uri.path)
self.client.stop()
logger.debug("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | [
"def",
"do_DELETE",
"(",
"self",
")",
":",
"self",
".",
"do_initial_operations",
"(",
")",
"coap_response",
"=",
"self",
".",
"client",
".",
"delete",
"(",
"self",
".",
"coap_uri",
".",
"path",
")",
"self",
".",
"client",
".",
"stop",
"(",
")",
"logger... | Perform a DELETE request | [
"Perform",
"a",
"DELETE",
"request"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L181-L189 | train | 210,688 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.request_hc_path_corresponds | def request_hc_path_corresponds(self):
"""
Tells if the hc path of the request corresponds to that specified by the admin
:return: a boolean that says if it corresponds or not
"""
uri_path = self.path.split(COAP_PREFACE)
request_hc_path = uri_path[0]
logger.debug("HCPATH: %s", hc_path)
# print HC_PATH
logger.debug("URI: %s", request_hc_path)
if hc_path != request_hc_path:
return False
else:
return True | python | def request_hc_path_corresponds(self):
"""
Tells if the hc path of the request corresponds to that specified by the admin
:return: a boolean that says if it corresponds or not
"""
uri_path = self.path.split(COAP_PREFACE)
request_hc_path = uri_path[0]
logger.debug("HCPATH: %s", hc_path)
# print HC_PATH
logger.debug("URI: %s", request_hc_path)
if hc_path != request_hc_path:
return False
else:
return True | [
"def",
"request_hc_path_corresponds",
"(",
"self",
")",
":",
"uri_path",
"=",
"self",
".",
"path",
".",
"split",
"(",
"COAP_PREFACE",
")",
"request_hc_path",
"=",
"uri_path",
"[",
"0",
"]",
"logger",
".",
"debug",
"(",
"\"HCPATH: %s\"",
",",
"hc_path",
")",
... | Tells if the hc path of the request corresponds to that specified by the admin
:return: a boolean that says if it corresponds or not | [
"Tells",
"if",
"the",
"hc",
"path",
"of",
"the",
"request",
"corresponds",
"to",
"that",
"specified",
"by",
"the",
"admin"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L209-L223 | train | 210,689 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.set_http_header | def set_http_header(self, coap_response):
"""
Sets http headers.
:param coap_response: the coap response
"""
logger.debug(
("Server: %s\n"\
"codice risposta: %s\n"\
"PROXED: %s\n"\
"payload risposta: %s"),
coap_response.source,
coap_response.code,
CoAP_HTTP[Codes.LIST[coap_response.code].name],
coap_response.payload)
self.send_response(int(CoAP_HTTP[Codes.LIST[coap_response.code].name]))
self.send_header('Content-type', 'text/html')
self.end_headers() | python | def set_http_header(self, coap_response):
"""
Sets http headers.
:param coap_response: the coap response
"""
logger.debug(
("Server: %s\n"\
"codice risposta: %s\n"\
"PROXED: %s\n"\
"payload risposta: %s"),
coap_response.source,
coap_response.code,
CoAP_HTTP[Codes.LIST[coap_response.code].name],
coap_response.payload)
self.send_response(int(CoAP_HTTP[Codes.LIST[coap_response.code].name]))
self.send_header('Content-type', 'text/html')
self.end_headers() | [
"def",
"set_http_header",
"(",
"self",
",",
"coap_response",
")",
":",
"logger",
".",
"debug",
"(",
"(",
"\"Server: %s\\n\"",
"\"codice risposta: %s\\n\"",
"\"PROXED: %s\\n\"",
"\"payload risposta: %s\"",
")",
",",
"coap_response",
".",
"source",
",",
"coap_response",
... | Sets http headers.
:param coap_response: the coap response | [
"Sets",
"http",
"headers",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L225-L242 | train | 210,690 |
Tanganelli/CoAPthon3 | coapthon/http_proxy/http_coap_proxy.py | HCProxyHandler.set_http_body | def set_http_body(self, coap_response):
"""
Set http body.
:param coap_response: the coap response
"""
if coap_response.payload is not None:
body = "<html><body><h1>", coap_response.payload, "</h1></body></html>"
self.wfile.write("".join(body))
else:
self.wfile.write("<html><body><h1>None</h1></body></html>") | python | def set_http_body(self, coap_response):
"""
Set http body.
:param coap_response: the coap response
"""
if coap_response.payload is not None:
body = "<html><body><h1>", coap_response.payload, "</h1></body></html>"
self.wfile.write("".join(body))
else:
self.wfile.write("<html><body><h1>None</h1></body></html>") | [
"def",
"set_http_body",
"(",
"self",
",",
"coap_response",
")",
":",
"if",
"coap_response",
".",
"payload",
"is",
"not",
"None",
":",
"body",
"=",
"\"<html><body><h1>\"",
",",
"coap_response",
".",
"payload",
",",
"\"</h1></body></html>\"",
"self",
".",
"wfile",... | Set http body.
:param coap_response: the coap response | [
"Set",
"http",
"body",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L244-L254 | train | 210,691 |
Tanganelli/CoAPthon3 | coapthon/utils.py | parse_blockwise | def parse_blockwise(value):
"""
Parse Blockwise option.
:param value: option value
:return: num, m, size
"""
length = byte_len(value)
if length == 1:
num = value & 0xF0
num >>= 4
m = value & 0x08
m >>= 3
size = value & 0x07
elif length == 2:
num = value & 0xFFF0
num >>= 4
m = value & 0x0008
m >>= 3
size = value & 0x0007
else:
num = value & 0xFFFFF0
num >>= 4
m = value & 0x000008
m >>= 3
size = value & 0x000007
return num, int(m), pow(2, (size + 4)) | python | def parse_blockwise(value):
"""
Parse Blockwise option.
:param value: option value
:return: num, m, size
"""
length = byte_len(value)
if length == 1:
num = value & 0xF0
num >>= 4
m = value & 0x08
m >>= 3
size = value & 0x07
elif length == 2:
num = value & 0xFFF0
num >>= 4
m = value & 0x0008
m >>= 3
size = value & 0x0007
else:
num = value & 0xFFFFF0
num >>= 4
m = value & 0x000008
m >>= 3
size = value & 0x000007
return num, int(m), pow(2, (size + 4)) | [
"def",
"parse_blockwise",
"(",
"value",
")",
":",
"length",
"=",
"byte_len",
"(",
"value",
")",
"if",
"length",
"==",
"1",
":",
"num",
"=",
"value",
"&",
"0xF0",
"num",
">>=",
"4",
"m",
"=",
"value",
"&",
"0x08",
"m",
">>=",
"3",
"size",
"=",
"va... | Parse Blockwise option.
:param value: option value
:return: num, m, size | [
"Parse",
"Blockwise",
"option",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/utils.py#L57-L84 | train | 210,692 |
Tanganelli/CoAPthon3 | coapthon/utils.py | byte_len | def byte_len(int_type):
"""
Get the number of byte needed to encode the int passed.
:param int_type: the int to be converted
:return: the number of bits needed to encode the int passed.
"""
length = 0
while int_type:
int_type >>= 1
length += 1
if length > 0:
if length % 8 != 0:
length = int(length / 8) + 1
else:
length = int(length / 8)
return length | python | def byte_len(int_type):
"""
Get the number of byte needed to encode the int passed.
:param int_type: the int to be converted
:return: the number of bits needed to encode the int passed.
"""
length = 0
while int_type:
int_type >>= 1
length += 1
if length > 0:
if length % 8 != 0:
length = int(length / 8) + 1
else:
length = int(length / 8)
return length | [
"def",
"byte_len",
"(",
"int_type",
")",
":",
"length",
"=",
"0",
"while",
"int_type",
":",
"int_type",
">>=",
"1",
"length",
"+=",
"1",
"if",
"length",
">",
"0",
":",
"if",
"length",
"%",
"8",
"!=",
"0",
":",
"length",
"=",
"int",
"(",
"length",
... | Get the number of byte needed to encode the int passed.
:param int_type: the int to be converted
:return: the number of bits needed to encode the int passed. | [
"Get",
"the",
"number",
"of",
"byte",
"needed",
"to",
"encode",
"the",
"int",
"passed",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/utils.py#L87-L103 | train | 210,693 |
Tanganelli/CoAPthon3 | coapthon/messages/option.py | Option.value | def value(self):
"""
Return the option value.
:return: the option value in the correct format depending on the option
"""
if type(self._value) is None:
self._value = bytearray()
opt_type = defines.OptionRegistry.LIST[self._number].value_type
if opt_type == defines.INTEGER:
if byte_len(self._value) > 0:
return int(self._value)
else:
return defines.OptionRegistry.LIST[self._number].default
return self._value | python | def value(self):
"""
Return the option value.
:return: the option value in the correct format depending on the option
"""
if type(self._value) is None:
self._value = bytearray()
opt_type = defines.OptionRegistry.LIST[self._number].value_type
if opt_type == defines.INTEGER:
if byte_len(self._value) > 0:
return int(self._value)
else:
return defines.OptionRegistry.LIST[self._number].default
return self._value | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"type",
"(",
"self",
".",
"_value",
")",
"is",
"None",
":",
"self",
".",
"_value",
"=",
"bytearray",
"(",
")",
"opt_type",
"=",
"defines",
".",
"OptionRegistry",
".",
"LIST",
"[",
"self",
".",
"_number",
... | Return the option value.
:return: the option value in the correct format depending on the option | [
"Return",
"the",
"option",
"value",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/option.py#L38-L52 | train | 210,694 |
Tanganelli/CoAPthon3 | coapthon/messages/option.py | Option.value | def value(self, value):
"""
Set the value of the option.
:param value: the option value
"""
opt_type = defines.OptionRegistry.LIST[self._number].value_type
if opt_type == defines.INTEGER:
if type(value) is not int:
value = int(value)
if byte_len(value) == 0:
value = 0
elif opt_type == defines.STRING:
if type(value) is not str:
value = str(value)
elif opt_type == defines.OPAQUE:
if type(value) is bytes:
pass
else:
if value is not None:
value = bytes(value, "utf-8")
self._value = value | python | def value(self, value):
"""
Set the value of the option.
:param value: the option value
"""
opt_type = defines.OptionRegistry.LIST[self._number].value_type
if opt_type == defines.INTEGER:
if type(value) is not int:
value = int(value)
if byte_len(value) == 0:
value = 0
elif opt_type == defines.STRING:
if type(value) is not str:
value = str(value)
elif opt_type == defines.OPAQUE:
if type(value) is bytes:
pass
else:
if value is not None:
value = bytes(value, "utf-8")
self._value = value | [
"def",
"value",
"(",
"self",
",",
"value",
")",
":",
"opt_type",
"=",
"defines",
".",
"OptionRegistry",
".",
"LIST",
"[",
"self",
".",
"_number",
"]",
".",
"value_type",
"if",
"opt_type",
"==",
"defines",
".",
"INTEGER",
":",
"if",
"type",
"(",
"value"... | Set the value of the option.
:param value: the option value | [
"Set",
"the",
"value",
"of",
"the",
"option",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/option.py#L55-L77 | train | 210,695 |
Tanganelli/CoAPthon3 | coapthon/messages/option.py | Option.length | def length(self):
"""
Return the value length
:rtype : int
"""
if isinstance(self._value, int):
return byte_len(self._value)
if self._value is None:
return 0
return len(self._value) | python | def length(self):
"""
Return the value length
:rtype : int
"""
if isinstance(self._value, int):
return byte_len(self._value)
if self._value is None:
return 0
return len(self._value) | [
"def",
"length",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_value",
",",
"int",
")",
":",
"return",
"byte_len",
"(",
"self",
".",
"_value",
")",
"if",
"self",
".",
"_value",
"is",
"None",
":",
"return",
"0",
"return",
"len",
"("... | Return the value length
:rtype : int | [
"Return",
"the",
"value",
"length"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/option.py#L80-L90 | train | 210,696 |
Tanganelli/CoAPthon3 | coapthon/messages/option.py | Option.is_safe | def is_safe(self):
"""
Check if the option is safe.
:rtype : bool
:return: True, if option is safe
"""
if self._number == defines.OptionRegistry.URI_HOST.number \
or self._number == defines.OptionRegistry.URI_PORT.number \
or self._number == defines.OptionRegistry.URI_PATH.number \
or self._number == defines.OptionRegistry.MAX_AGE.number \
or self._number == defines.OptionRegistry.URI_QUERY.number \
or self._number == defines.OptionRegistry.PROXY_URI.number \
or self._number == defines.OptionRegistry.PROXY_SCHEME.number:
return False
return True | python | def is_safe(self):
"""
Check if the option is safe.
:rtype : bool
:return: True, if option is safe
"""
if self._number == defines.OptionRegistry.URI_HOST.number \
or self._number == defines.OptionRegistry.URI_PORT.number \
or self._number == defines.OptionRegistry.URI_PATH.number \
or self._number == defines.OptionRegistry.MAX_AGE.number \
or self._number == defines.OptionRegistry.URI_QUERY.number \
or self._number == defines.OptionRegistry.PROXY_URI.number \
or self._number == defines.OptionRegistry.PROXY_SCHEME.number:
return False
return True | [
"def",
"is_safe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_number",
"==",
"defines",
".",
"OptionRegistry",
".",
"URI_HOST",
".",
"number",
"or",
"self",
".",
"_number",
"==",
"defines",
".",
"OptionRegistry",
".",
"URI_PORT",
".",
"number",
"or",
"se... | Check if the option is safe.
:rtype : bool
:return: True, if option is safe | [
"Check",
"if",
"the",
"option",
"is",
"safe",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/option.py#L92-L107 | train | 210,697 |
Tanganelli/CoAPthon3 | coapthon/defines.py | OptionRegistry.get_option_flags | def get_option_flags(option_num):
"""
Get Critical, UnSafe, NoCacheKey flags from the option number
as per RFC 7252, section 5.4.6
:param option_num: option number
:return: option flags
:rtype: 3-tuple (critical, unsafe, no-cache)
"""
opt_bytes = array.array('B', '\0\0')
if option_num < 256:
s = struct.Struct("!B")
s.pack_into(opt_bytes, 0, option_num)
else:
s = struct.Struct("H")
s.pack_into(opt_bytes, 0, option_num)
critical = (opt_bytes[0] & 0x01) > 0
unsafe = (opt_bytes[0] & 0x02) > 0
nocache = ((opt_bytes[0] & 0x1e) == 0x1c)
return (critical, unsafe, nocache) | python | def get_option_flags(option_num):
"""
Get Critical, UnSafe, NoCacheKey flags from the option number
as per RFC 7252, section 5.4.6
:param option_num: option number
:return: option flags
:rtype: 3-tuple (critical, unsafe, no-cache)
"""
opt_bytes = array.array('B', '\0\0')
if option_num < 256:
s = struct.Struct("!B")
s.pack_into(opt_bytes, 0, option_num)
else:
s = struct.Struct("H")
s.pack_into(opt_bytes, 0, option_num)
critical = (opt_bytes[0] & 0x01) > 0
unsafe = (opt_bytes[0] & 0x02) > 0
nocache = ((opt_bytes[0] & 0x1e) == 0x1c)
return (critical, unsafe, nocache) | [
"def",
"get_option_flags",
"(",
"option_num",
")",
":",
"opt_bytes",
"=",
"array",
".",
"array",
"(",
"'B'",
",",
"'\\0\\0'",
")",
"if",
"option_num",
"<",
"256",
":",
"s",
"=",
"struct",
".",
"Struct",
"(",
"\"!B\"",
")",
"s",
".",
"pack_into",
"(",
... | Get Critical, UnSafe, NoCacheKey flags from the option number
as per RFC 7252, section 5.4.6
:param option_num: option number
:return: option flags
:rtype: 3-tuple (critical, unsafe, no-cache) | [
"Get",
"Critical",
"UnSafe",
"NoCacheKey",
"flags",
"from",
"the",
"option",
"number",
"as",
"per",
"RFC",
"7252",
"section",
"5",
".",
"4",
".",
"6"
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/defines.py#L159-L178 | train | 210,698 |
Tanganelli/CoAPthon3 | coapthon/serializer.py | Serializer.read_option_value_from_nibble | def read_option_value_from_nibble(nibble, pos, values):
"""
Calculates the value used in the extended option fields.
:param nibble: the 4-bit option header value.
:return: the value calculated from the nibble and the extended option value.
"""
if nibble <= 12:
return nibble, pos
elif nibble == 13:
tmp = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13
pos += 1
return tmp, pos
elif nibble == 14:
s = struct.Struct("!H")
tmp = s.unpack_from(values[pos:].to_bytes(2, "big"))[0] + 269
pos += 2
return tmp, pos
else:
raise AttributeError("Unsupported option nibble " + str(nibble)) | python | def read_option_value_from_nibble(nibble, pos, values):
"""
Calculates the value used in the extended option fields.
:param nibble: the 4-bit option header value.
:return: the value calculated from the nibble and the extended option value.
"""
if nibble <= 12:
return nibble, pos
elif nibble == 13:
tmp = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13
pos += 1
return tmp, pos
elif nibble == 14:
s = struct.Struct("!H")
tmp = s.unpack_from(values[pos:].to_bytes(2, "big"))[0] + 269
pos += 2
return tmp, pos
else:
raise AttributeError("Unsupported option nibble " + str(nibble)) | [
"def",
"read_option_value_from_nibble",
"(",
"nibble",
",",
"pos",
",",
"values",
")",
":",
"if",
"nibble",
"<=",
"12",
":",
"return",
"nibble",
",",
"pos",
"elif",
"nibble",
"==",
"13",
":",
"tmp",
"=",
"struct",
".",
"unpack",
"(",
"\"!B\"",
",",
"va... | Calculates the value used in the extended option fields.
:param nibble: the 4-bit option header value.
:return: the value calculated from the nibble and the extended option value. | [
"Calculates",
"the",
"value",
"used",
"in",
"the",
"extended",
"option",
"fields",
"."
] | 985763bfe2eb9e00f49ec100c5b8877c2ed7d531 | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/serializer.py#L269-L288 | train | 210,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.