repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
digidotcom/python-devicecloud | devicecloud/monitor_tcp.py | TCPClientManager._writer | def _writer(self):
"""
Indefinitely checks the writer queue for data to write
to socket.
"""
while not self.closed:
try:
sock, data = self._write_queue.get(timeout=0.1)
self._write_queue.task_done()
sock.send(data)
except Empty:
pass # nothing to write after timeout
except socket.error as err:
if err.errno == errno.EBADF:
self._clean_dead_sessions() | python | def _writer(self):
"""
Indefinitely checks the writer queue for data to write
to socket.
"""
while not self.closed:
try:
sock, data = self._write_queue.get(timeout=0.1)
self._write_queue.task_done()
sock.send(data)
except Empty:
pass # nothing to write after timeout
except socket.error as err:
if err.errno == errno.EBADF:
self._clean_dead_sessions() | [
"def",
"_writer",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"closed",
":",
"try",
":",
"sock",
",",
"data",
"=",
"self",
".",
"_write_queue",
".",
"get",
"(",
"timeout",
"=",
"0.1",
")",
"self",
".",
"_write_queue",
".",
"task_done",
"(",
... | Indefinitely checks the writer queue for data to write
to socket. | [
"Indefinitely",
"checks",
"the",
"writer",
"queue",
"for",
"data",
"to",
"write",
"to",
"socket",
"."
] | 32529684a348a7830a269c32601604c78036bcb8 | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/monitor_tcp.py#L418-L432 | train |
digidotcom/python-devicecloud | devicecloud/monitor_tcp.py | TCPClientManager._clean_dead_sessions | def _clean_dead_sessions(self):
"""
Traverses sessions to determine if any sockets
were removed (indicates a stopped session).
In these cases, remove the session.
"""
for sck in list(self.sessions.keys()):
session = self.sessions[sck]
if session.socket is None:
del self.sessions[sck] | python | def _clean_dead_sessions(self):
"""
Traverses sessions to determine if any sockets
were removed (indicates a stopped session).
In these cases, remove the session.
"""
for sck in list(self.sessions.keys()):
session = self.sessions[sck]
if session.socket is None:
del self.sessions[sck] | [
"def",
"_clean_dead_sessions",
"(",
"self",
")",
":",
"for",
"sck",
"in",
"list",
"(",
"self",
".",
"sessions",
".",
"keys",
"(",
")",
")",
":",
"session",
"=",
"self",
".",
"sessions",
"[",
"sck",
"]",
"if",
"session",
".",
"socket",
"is",
"None",
... | Traverses sessions to determine if any sockets
were removed (indicates a stopped session).
In these cases, remove the session. | [
"Traverses",
"sessions",
"to",
"determine",
"if",
"any",
"sockets",
"were",
"removed",
"(",
"indicates",
"a",
"stopped",
"session",
")",
".",
"In",
"these",
"cases",
"remove",
"the",
"session",
"."
] | 32529684a348a7830a269c32601604c78036bcb8 | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/monitor_tcp.py#L434-L443 | train |
digidotcom/python-devicecloud | devicecloud/monitor_tcp.py | TCPClientManager._select | def _select(self):
"""
While the client is not marked as closed, performs a socket select
on all PushSession sockets. If any data is received, parses and
forwards it on to the callback function. If the callback is
successful, a PublishMessageReceived message is sent.
"""
try:
while not self.closed:
try:
inputready = select.select(self.sessions.keys(), [], [], 0.1)[0]
for sock in inputready:
session = self.sessions[sock]
sck = session.socket
if sck is None:
# Socket has since been deleted, continue
continue
# If no defined message length, nothing has been
# consumed yet, parse the header.
if session.message_length == 0:
# Read header information before receiving rest of
# message.
response_type = _read_msg_header(session)
if response_type == NO_DATA:
# No data could be read, assume socket closed.
if session.socket is not None:
self.log.error("Socket closed for Monitor %s." % session.monitor_id)
self._restart_session(session)
continue
elif response_type == INCOMPLETE:
# More Data to be read. Continue.
continue
elif response_type != PUBLISH_MESSAGE:
self.log.warn("Response Type (%x) does not match PublishMessage (%x)"
% (response_type, PUBLISH_MESSAGE))
continue
try:
if not _read_msg(session):
# Data not completely read, continue.
continue
except PushException as err:
# If Socket is None, it was closed,
# otherwise it was closed when it shouldn't
# have been restart it.
session.data = six.b("")
session.message_length = 0
if session.socket is None:
del self.sessions[sck]
else:
self.log.exception(err)
self._restart_session(session)
continue
# We received full payload,
# clear session data and parse it.
data = session.data
session.data = six.b("")
session.message_length = 0
block_id = struct.unpack('!H', data[0:2])[0]
compression = struct.unpack('!B', data[4:5])[0]
payload = data[10:]
if compression == 0x01:
# Data is compressed, uncompress it.
payload = zlib.decompress(payload)
# Enqueue payload into a callback queue to be
# invoked
self._callback_pool.queue_callback(session, block_id, payload)
except select.error as err:
# Evaluate sessions if we get a bad file descriptor, if
# socket is gone, delete the session.
if err.args[0] == errno.EBADF:
self._clean_dead_sessions()
except Exception as err:
self.log.exception(err)
finally:
for session in self.sessions.values():
if session is not None:
session.stop() | python | def _select(self):
"""
While the client is not marked as closed, performs a socket select
on all PushSession sockets. If any data is received, parses and
forwards it on to the callback function. If the callback is
successful, a PublishMessageReceived message is sent.
"""
try:
while not self.closed:
try:
inputready = select.select(self.sessions.keys(), [], [], 0.1)[0]
for sock in inputready:
session = self.sessions[sock]
sck = session.socket
if sck is None:
# Socket has since been deleted, continue
continue
# If no defined message length, nothing has been
# consumed yet, parse the header.
if session.message_length == 0:
# Read header information before receiving rest of
# message.
response_type = _read_msg_header(session)
if response_type == NO_DATA:
# No data could be read, assume socket closed.
if session.socket is not None:
self.log.error("Socket closed for Monitor %s." % session.monitor_id)
self._restart_session(session)
continue
elif response_type == INCOMPLETE:
# More Data to be read. Continue.
continue
elif response_type != PUBLISH_MESSAGE:
self.log.warn("Response Type (%x) does not match PublishMessage (%x)"
% (response_type, PUBLISH_MESSAGE))
continue
try:
if not _read_msg(session):
# Data not completely read, continue.
continue
except PushException as err:
# If Socket is None, it was closed,
# otherwise it was closed when it shouldn't
# have been restart it.
session.data = six.b("")
session.message_length = 0
if session.socket is None:
del self.sessions[sck]
else:
self.log.exception(err)
self._restart_session(session)
continue
# We received full payload,
# clear session data and parse it.
data = session.data
session.data = six.b("")
session.message_length = 0
block_id = struct.unpack('!H', data[0:2])[0]
compression = struct.unpack('!B', data[4:5])[0]
payload = data[10:]
if compression == 0x01:
# Data is compressed, uncompress it.
payload = zlib.decompress(payload)
# Enqueue payload into a callback queue to be
# invoked
self._callback_pool.queue_callback(session, block_id, payload)
except select.error as err:
# Evaluate sessions if we get a bad file descriptor, if
# socket is gone, delete the session.
if err.args[0] == errno.EBADF:
self._clean_dead_sessions()
except Exception as err:
self.log.exception(err)
finally:
for session in self.sessions.values():
if session is not None:
session.stop() | [
"def",
"_select",
"(",
"self",
")",
":",
"try",
":",
"while",
"not",
"self",
".",
"closed",
":",
"try",
":",
"inputready",
"=",
"select",
".",
"select",
"(",
"self",
".",
"sessions",
".",
"keys",
"(",
")",
",",
"[",
"]",
",",
"[",
"]",
",",
"0.... | While the client is not marked as closed, performs a socket select
on all PushSession sockets. If any data is received, parses and
forwards it on to the callback function. If the callback is
successful, a PublishMessageReceived message is sent. | [
"While",
"the",
"client",
"is",
"not",
"marked",
"as",
"closed",
"performs",
"a",
"socket",
"select",
"on",
"all",
"PushSession",
"sockets",
".",
"If",
"any",
"data",
"is",
"received",
"parses",
"and",
"forwards",
"it",
"on",
"to",
"the",
"callback",
"func... | 32529684a348a7830a269c32601604c78036bcb8 | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/monitor_tcp.py#L445-L528 | train |
digidotcom/python-devicecloud | devicecloud/monitor_tcp.py | TCPClientManager._init_threads | def _init_threads(self):
"""Initializes the IO and Writer threads"""
if self._io_thread is None:
self._io_thread = Thread(target=self._select)
self._io_thread.start()
if self._writer_thread is None:
self._writer_thread = Thread(target=self._writer)
self._writer_thread.start() | python | def _init_threads(self):
"""Initializes the IO and Writer threads"""
if self._io_thread is None:
self._io_thread = Thread(target=self._select)
self._io_thread.start()
if self._writer_thread is None:
self._writer_thread = Thread(target=self._writer)
self._writer_thread.start() | [
"def",
"_init_threads",
"(",
"self",
")",
":",
"if",
"self",
".",
"_io_thread",
"is",
"None",
":",
"self",
".",
"_io_thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_select",
")",
"self",
".",
"_io_thread",
".",
"start",
"(",
")",
"if",
"se... | Initializes the IO and Writer threads | [
"Initializes",
"the",
"IO",
"and",
"Writer",
"threads"
] | 32529684a348a7830a269c32601604c78036bcb8 | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/monitor_tcp.py#L530-L538 | train |
digidotcom/python-devicecloud | devicecloud/monitor_tcp.py | TCPClientManager.create_session | def create_session(self, callback, monitor_id):
"""
Creates and Returns a PushSession instance based on the input monitor
and callback. When data is received, callback will be invoked.
If neither monitor or monitor_id are specified, throws an Exception.
:param callback: Callback function to call when PublishMessage
messages are received. Expects 1 argument which will contain the
payload of the pushed message. Additionally, expects
function to return True if callback was able to process
the message, False or None otherwise.
:param monitor_id: The id of the Monitor, will be queried
to understand parameters of the monitor.
"""
self.log.info("Creating Session for Monitor %s." % monitor_id)
session = SecurePushSession(callback, monitor_id, self, self._ca_certs) \
if self._secure else PushSession(callback, monitor_id, self)
session.start()
self.sessions[session.socket.fileno()] = session
self._init_threads()
return session | python | def create_session(self, callback, monitor_id):
"""
Creates and Returns a PushSession instance based on the input monitor
and callback. When data is received, callback will be invoked.
If neither monitor or monitor_id are specified, throws an Exception.
:param callback: Callback function to call when PublishMessage
messages are received. Expects 1 argument which will contain the
payload of the pushed message. Additionally, expects
function to return True if callback was able to process
the message, False or None otherwise.
:param monitor_id: The id of the Monitor, will be queried
to understand parameters of the monitor.
"""
self.log.info("Creating Session for Monitor %s." % monitor_id)
session = SecurePushSession(callback, monitor_id, self, self._ca_certs) \
if self._secure else PushSession(callback, monitor_id, self)
session.start()
self.sessions[session.socket.fileno()] = session
self._init_threads()
return session | [
"def",
"create_session",
"(",
"self",
",",
"callback",
",",
"monitor_id",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Creating Session for Monitor %s.\"",
"%",
"monitor_id",
")",
"session",
"=",
"SecurePushSession",
"(",
"callback",
",",
"monitor_id",
","... | Creates and Returns a PushSession instance based on the input monitor
and callback. When data is received, callback will be invoked.
If neither monitor or monitor_id are specified, throws an Exception.
:param callback: Callback function to call when PublishMessage
messages are received. Expects 1 argument which will contain the
payload of the pushed message. Additionally, expects
function to return True if callback was able to process
the message, False or None otherwise.
:param monitor_id: The id of the Monitor, will be queried
to understand parameters of the monitor. | [
"Creates",
"and",
"Returns",
"a",
"PushSession",
"instance",
"based",
"on",
"the",
"input",
"monitor",
"and",
"callback",
".",
"When",
"data",
"is",
"received",
"callback",
"will",
"be",
"invoked",
".",
"If",
"neither",
"monitor",
"or",
"monitor_id",
"are",
... | 32529684a348a7830a269c32601604c78036bcb8 | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/monitor_tcp.py#L540-L562 | train |
digidotcom/python-devicecloud | devicecloud/monitor_tcp.py | TCPClientManager.stop | def stop(self):
"""Stops all session activity.
Blocks until io and writer thread dies
"""
if self._io_thread is not None:
self.log.info("Waiting for I/O thread to stop...")
self.closed = True
self._io_thread.join()
if self._writer_thread is not None:
self.log.info("Waiting for Writer Thread to stop...")
self.closed = True
self._writer_thread.join()
self.log.info("All worker threads stopped.") | python | def stop(self):
"""Stops all session activity.
Blocks until io and writer thread dies
"""
if self._io_thread is not None:
self.log.info("Waiting for I/O thread to stop...")
self.closed = True
self._io_thread.join()
if self._writer_thread is not None:
self.log.info("Waiting for Writer Thread to stop...")
self.closed = True
self._writer_thread.join()
self.log.info("All worker threads stopped.") | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_io_thread",
"is",
"not",
"None",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Waiting for I/O thread to stop...\"",
")",
"self",
".",
"closed",
"=",
"True",
"self",
".",
"_io_thread",
".",
"join... | Stops all session activity.
Blocks until io and writer thread dies | [
"Stops",
"all",
"session",
"activity",
"."
] | 32529684a348a7830a269c32601604c78036bcb8 | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/monitor_tcp.py#L564-L579 | train |
timmahrt/ProMo | promo/morph_utils/plot_morphed_data.py | plotF0 | def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath):
'''
Plots the original data in a graph above the plot of the dtw'ed data
'''
_matplotlibCheck()
plt.hold(True)
fig, (ax0) = plt.subplots(nrows=1)
# Old data
plot1 = ax0.plot(fromTuple[0], fromTuple[1], color='red',
linewidth=2, label="From")
plot2 = ax0.plot(toTuple[0], toTuple[1], color='blue',
linewidth=2, label="To")
ax0.set_title("Plot of F0 Morph")
plt.ylabel('Pitch (hz)')
plt.xlabel('Time (s)')
# Merge data
colorValue = 0
colorStep = 255.0 / len(mergeTupleList)
for timeList, valueList in mergeTupleList:
colorValue += colorStep
hexValue = "#%02x0000" % int(255 - colorValue)
if int(colorValue) == 255:
ax0.plot(timeList, valueList, color=hexValue, linewidth=1,
label="Merged line, final iteration")
else:
ax0.plot(timeList, valueList, color=hexValue, linewidth=1)
plt.legend(loc=1, borderaxespad=0.)
# plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"])
plt.savefig(fnFullPath, dpi=300, bbox_inches='tight')
plt.close(fig) | python | def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath):
'''
Plots the original data in a graph above the plot of the dtw'ed data
'''
_matplotlibCheck()
plt.hold(True)
fig, (ax0) = plt.subplots(nrows=1)
# Old data
plot1 = ax0.plot(fromTuple[0], fromTuple[1], color='red',
linewidth=2, label="From")
plot2 = ax0.plot(toTuple[0], toTuple[1], color='blue',
linewidth=2, label="To")
ax0.set_title("Plot of F0 Morph")
plt.ylabel('Pitch (hz)')
plt.xlabel('Time (s)')
# Merge data
colorValue = 0
colorStep = 255.0 / len(mergeTupleList)
for timeList, valueList in mergeTupleList:
colorValue += colorStep
hexValue = "#%02x0000" % int(255 - colorValue)
if int(colorValue) == 255:
ax0.plot(timeList, valueList, color=hexValue, linewidth=1,
label="Merged line, final iteration")
else:
ax0.plot(timeList, valueList, color=hexValue, linewidth=1)
plt.legend(loc=1, borderaxespad=0.)
# plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"])
plt.savefig(fnFullPath, dpi=300, bbox_inches='tight')
plt.close(fig) | [
"def",
"plotF0",
"(",
"fromTuple",
",",
"toTuple",
",",
"mergeTupleList",
",",
"fnFullPath",
")",
":",
"_matplotlibCheck",
"(",
")",
"plt",
".",
"hold",
"(",
"True",
")",
"fig",
",",
"(",
"ax0",
")",
"=",
"plt",
".",
"subplots",
"(",
"nrows",
"=",
"1... | Plots the original data in a graph above the plot of the dtw'ed data | [
"Plots",
"the",
"original",
"data",
"in",
"a",
"graph",
"above",
"the",
"plot",
"of",
"the",
"dtw",
"ed",
"data"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/plot_morphed_data.py#L74-L109 | train |
timmahrt/ProMo | promo/f0_morph.py | getPitchForIntervals | def getPitchForIntervals(data, tgFN, tierName):
'''
Preps data for use in f0Morph
'''
tg = tgio.openTextgrid(tgFN)
data = tg.tierDict[tierName].getValuesInIntervals(data)
data = [dataList for _, dataList in data]
return data | python | def getPitchForIntervals(data, tgFN, tierName):
'''
Preps data for use in f0Morph
'''
tg = tgio.openTextgrid(tgFN)
data = tg.tierDict[tierName].getValuesInIntervals(data)
data = [dataList for _, dataList in data]
return data | [
"def",
"getPitchForIntervals",
"(",
"data",
",",
"tgFN",
",",
"tierName",
")",
":",
"tg",
"=",
"tgio",
".",
"openTextgrid",
"(",
"tgFN",
")",
"data",
"=",
"tg",
".",
"tierDict",
"[",
"tierName",
"]",
".",
"getValuesInIntervals",
"(",
"data",
")",
"data",... | Preps data for use in f0Morph | [
"Preps",
"data",
"for",
"use",
"in",
"f0Morph"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/f0_morph.py#L35-L43 | train |
timmahrt/ProMo | promo/f0_morph.py | f0Morph | def f0Morph(fromWavFN, pitchPath, stepList,
outputName, doPlotPitchSteps, fromPitchData, toPitchData,
outputMinPitch, outputMaxPitch, praatEXE, keepPitchRange=False,
keepAveragePitch=False, sourcePitchDataList=None,
minIntervalLength=0.3):
'''
Resynthesizes the pitch track from a source to a target wav file
fromPitchData and toPitchData should be segmented according to the
portions that you want to morph. The two lists must have the same
number of sublists.
Occurs over a three-step process.
This function can act as a template for how to use the function
morph_sequence.morphChunkedDataLists to morph pitch contours or
other data.
By default, everything is morphed, but it is possible to maintain elements
of the original speaker's pitch (average pitch and pitch range) by setting
the appropriate flag)
sourcePitchDataList: if passed in, any regions unspecified by
fromPitchData will be sampled from this list. In
essence, this allows one to leave segments of
the original pitch contour untouched by the
morph process.
'''
fromDuration = audio_scripts.getSoundFileDuration(fromWavFN)
# Find source pitch samples that will be mixed in with the target
# pitch samples later
nonMorphPitchData = []
if sourcePitchDataList is not None:
timeList = sorted(fromPitchData)
timeList = [(row[0][0], row[-1][0]) for row in timeList]
endTime = sourcePitchDataList[-1][0]
invertedTimeList = praatio_utils.invertIntervalList(timeList, endTime)
invertedTimeList = [(start, stop) for start, stop in invertedTimeList
if stop - start > minIntervalLength]
for start, stop in invertedTimeList:
pitchList = praatio_utils.getValuesInInterval(sourcePitchDataList,
start,
stop)
nonMorphPitchData.extend(pitchList)
# Iterative pitch tier data path
pitchTierPath = join(pitchPath, "pitchTiers")
resynthesizedPath = join(pitchPath, "f0_resynthesized_wavs")
for tmpPath in [pitchTierPath, resynthesizedPath]:
utils.makeDir(tmpPath)
# 1. Prepare the data for morphing - acquire the segments to merge
# (Done elsewhere, with the input fed into this function)
# 2. Morph the fromData to the toData
try:
finalOutputList = morph_sequence.morphChunkedDataLists(fromPitchData,
toPitchData,
stepList)
except IndexError:
raise MissingPitchDataException()
fromPitchData = [row for subList in fromPitchData for row in subList]
toPitchData = [row for subList in toPitchData for row in subList]
# 3. Save the pitch data and resynthesize the pitch
mergedDataList = []
for i in range(0, len(finalOutputList)):
outputDataList = finalOutputList[i]
if keepPitchRange is True:
outputDataList = morph_sequence.morphRange(outputDataList,
fromPitchData)
if keepAveragePitch is True:
outputDataList = morph_sequence.morphAveragePitch(outputDataList,
fromPitchData)
if sourcePitchDataList is not None:
outputDataList.extend(nonMorphPitchData)
outputDataList.sort()
stepOutputName = "%s_%0.3g" % (outputName, stepList[i])
pitchFNFullPath = join(pitchTierPath, "%s.PitchTier" % stepOutputName)
outputFN = join(resynthesizedPath, "%s.wav" % stepOutputName)
pointObj = dataio.PointObject2D(outputDataList, dataio.PITCH,
0, fromDuration)
pointObj.save(pitchFNFullPath)
outputTime, outputVals = zip(*outputDataList)
mergedDataList.append((outputTime, outputVals))
praat_scripts.resynthesizePitch(praatEXE, fromWavFN, pitchFNFullPath,
outputFN, outputMinPitch,
outputMaxPitch)
# 4. (Optional) Plot the generated contours
if doPlotPitchSteps:
fromTime, fromVals = zip(*fromPitchData)
toTime, toVals = zip(*toPitchData)
plot_morphed_data.plotF0((fromTime, fromVals),
(toTime, toVals),
mergedDataList,
join(pitchTierPath,
"%s.png" % outputName)) | python | def f0Morph(fromWavFN, pitchPath, stepList,
outputName, doPlotPitchSteps, fromPitchData, toPitchData,
outputMinPitch, outputMaxPitch, praatEXE, keepPitchRange=False,
keepAveragePitch=False, sourcePitchDataList=None,
minIntervalLength=0.3):
'''
Resynthesizes the pitch track from a source to a target wav file
fromPitchData and toPitchData should be segmented according to the
portions that you want to morph. The two lists must have the same
number of sublists.
Occurs over a three-step process.
This function can act as a template for how to use the function
morph_sequence.morphChunkedDataLists to morph pitch contours or
other data.
By default, everything is morphed, but it is possible to maintain elements
of the original speaker's pitch (average pitch and pitch range) by setting
the appropriate flag)
sourcePitchDataList: if passed in, any regions unspecified by
fromPitchData will be sampled from this list. In
essence, this allows one to leave segments of
the original pitch contour untouched by the
morph process.
'''
fromDuration = audio_scripts.getSoundFileDuration(fromWavFN)
# Find source pitch samples that will be mixed in with the target
# pitch samples later
nonMorphPitchData = []
if sourcePitchDataList is not None:
timeList = sorted(fromPitchData)
timeList = [(row[0][0], row[-1][0]) for row in timeList]
endTime = sourcePitchDataList[-1][0]
invertedTimeList = praatio_utils.invertIntervalList(timeList, endTime)
invertedTimeList = [(start, stop) for start, stop in invertedTimeList
if stop - start > minIntervalLength]
for start, stop in invertedTimeList:
pitchList = praatio_utils.getValuesInInterval(sourcePitchDataList,
start,
stop)
nonMorphPitchData.extend(pitchList)
# Iterative pitch tier data path
pitchTierPath = join(pitchPath, "pitchTiers")
resynthesizedPath = join(pitchPath, "f0_resynthesized_wavs")
for tmpPath in [pitchTierPath, resynthesizedPath]:
utils.makeDir(tmpPath)
# 1. Prepare the data for morphing - acquire the segments to merge
# (Done elsewhere, with the input fed into this function)
# 2. Morph the fromData to the toData
try:
finalOutputList = morph_sequence.morphChunkedDataLists(fromPitchData,
toPitchData,
stepList)
except IndexError:
raise MissingPitchDataException()
fromPitchData = [row for subList in fromPitchData for row in subList]
toPitchData = [row for subList in toPitchData for row in subList]
# 3. Save the pitch data and resynthesize the pitch
mergedDataList = []
for i in range(0, len(finalOutputList)):
outputDataList = finalOutputList[i]
if keepPitchRange is True:
outputDataList = morph_sequence.morphRange(outputDataList,
fromPitchData)
if keepAveragePitch is True:
outputDataList = morph_sequence.morphAveragePitch(outputDataList,
fromPitchData)
if sourcePitchDataList is not None:
outputDataList.extend(nonMorphPitchData)
outputDataList.sort()
stepOutputName = "%s_%0.3g" % (outputName, stepList[i])
pitchFNFullPath = join(pitchTierPath, "%s.PitchTier" % stepOutputName)
outputFN = join(resynthesizedPath, "%s.wav" % stepOutputName)
pointObj = dataio.PointObject2D(outputDataList, dataio.PITCH,
0, fromDuration)
pointObj.save(pitchFNFullPath)
outputTime, outputVals = zip(*outputDataList)
mergedDataList.append((outputTime, outputVals))
praat_scripts.resynthesizePitch(praatEXE, fromWavFN, pitchFNFullPath,
outputFN, outputMinPitch,
outputMaxPitch)
# 4. (Optional) Plot the generated contours
if doPlotPitchSteps:
fromTime, fromVals = zip(*fromPitchData)
toTime, toVals = zip(*toPitchData)
plot_morphed_data.plotF0((fromTime, fromVals),
(toTime, toVals),
mergedDataList,
join(pitchTierPath,
"%s.png" % outputName)) | [
"def",
"f0Morph",
"(",
"fromWavFN",
",",
"pitchPath",
",",
"stepList",
",",
"outputName",
",",
"doPlotPitchSteps",
",",
"fromPitchData",
",",
"toPitchData",
",",
"outputMinPitch",
",",
"outputMaxPitch",
",",
"praatEXE",
",",
"keepPitchRange",
"=",
"False",
",",
... | Resynthesizes the pitch track from a source to a target wav file
fromPitchData and toPitchData should be segmented according to the
portions that you want to morph. The two lists must have the same
number of sublists.
Occurs over a three-step process.
This function can act as a template for how to use the function
morph_sequence.morphChunkedDataLists to morph pitch contours or
other data.
By default, everything is morphed, but it is possible to maintain elements
of the original speaker's pitch (average pitch and pitch range) by setting
the appropriate flag)
sourcePitchDataList: if passed in, any regions unspecified by
fromPitchData will be sampled from this list. In
essence, this allows one to leave segments of
the original pitch contour untouched by the
morph process. | [
"Resynthesizes",
"the",
"pitch",
"track",
"from",
"a",
"source",
"to",
"a",
"target",
"wav",
"file"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/f0_morph.py#L46-L156 | train |
hermanschaaf/mafan | mafan/pinyin.py | decode | def decode(s):
"""
Converts text in the numbering format of pinyin ("ni3hao3") to text with the
appropriate tone marks ("nǐhǎo").
"""
s = s.lower()
r = ""
t = ""
for c in s:
if c >= 'a' and c <= 'z':
t += c
elif c == ':':
try:
if t[-1] == 'u':
t = t[:-1] + u"\u00fc"
except:
pass
else:
if c >= '0' and c <= '5':
tone = int(c) % 5
if tone != 0:
m = re.search(u"[aoeiuv\u00fc]+", t)
if m is None:
t += c
elif len(m.group(0)) == 1:
t = t[:m.start(0)] + PinyinToneMark[tone][PinyinToneMark[0].index(m.group(0))] + t[m.end(0):]
else:
if 'a' in t:
t = t.replace("a", PinyinToneMark[tone][0])
elif 'o' in t:
t = t.replace("o", PinyinToneMark[tone][1])
elif 'e' in t:
t = t.replace("e", PinyinToneMark[tone][2])
elif t.endswith("ui"):
t = t.replace("i", PinyinToneMark[tone][3])
elif t.endswith("iu"):
t = t.replace("u", PinyinToneMark[tone][4])
else:
t += "!"
r += t
t = ""
r += t
return r | python | def decode(s):
"""
Converts text in the numbering format of pinyin ("ni3hao3") to text with the
appropriate tone marks ("nǐhǎo").
"""
s = s.lower()
r = ""
t = ""
for c in s:
if c >= 'a' and c <= 'z':
t += c
elif c == ':':
try:
if t[-1] == 'u':
t = t[:-1] + u"\u00fc"
except:
pass
else:
if c >= '0' and c <= '5':
tone = int(c) % 5
if tone != 0:
m = re.search(u"[aoeiuv\u00fc]+", t)
if m is None:
t += c
elif len(m.group(0)) == 1:
t = t[:m.start(0)] + PinyinToneMark[tone][PinyinToneMark[0].index(m.group(0))] + t[m.end(0):]
else:
if 'a' in t:
t = t.replace("a", PinyinToneMark[tone][0])
elif 'o' in t:
t = t.replace("o", PinyinToneMark[tone][1])
elif 'e' in t:
t = t.replace("e", PinyinToneMark[tone][2])
elif t.endswith("ui"):
t = t.replace("i", PinyinToneMark[tone][3])
elif t.endswith("iu"):
t = t.replace("u", PinyinToneMark[tone][4])
else:
t += "!"
r += t
t = ""
r += t
return r | [
"def",
"decode",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"lower",
"(",
")",
"r",
"=",
"\"\"",
"t",
"=",
"\"\"",
"for",
"c",
"in",
"s",
":",
"if",
"c",
">=",
"'a'",
"and",
"c",
"<=",
"'z'",
":",
"t",
"+=",
"c",
"elif",
"c",
"==",
"':'",
... | Converts text in the numbering format of pinyin ("ni3hao3") to text with the
appropriate tone marks ("nǐhǎo"). | [
"Converts",
"text",
"in",
"the",
"numbering",
"format",
"of",
"pinyin",
"(",
"ni3hao3",
")",
"to",
"text",
"with",
"the",
"appropriate",
"tone",
"marks",
"(",
"nǐhǎo",
")",
"."
] | 373ddf299aeb2bd8413bf921c71768af7a8170ea | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/pinyin.py#L14-L57 | train |
timmahrt/ProMo | promo/morph_utils/modify_pitch_accent.py | PitchAccent.adjustPeakHeight | def adjustPeakHeight(self, heightAmount):
'''
Adjust peak height
The foot of the accent is left unchanged and intermediate
values are linearly scaled
'''
if heightAmount == 0:
return
pitchList = [f0V for _, f0V in self.pointList]
minV = min(pitchList)
maxV = max(pitchList)
scale = lambda x, y: x + y * (x - minV) / float(maxV - minV)
self.pointList = [(timeV, scale(f0V, heightAmount))
for timeV, f0V in self.pointList] | python | def adjustPeakHeight(self, heightAmount):
'''
Adjust peak height
The foot of the accent is left unchanged and intermediate
values are linearly scaled
'''
if heightAmount == 0:
return
pitchList = [f0V for _, f0V in self.pointList]
minV = min(pitchList)
maxV = max(pitchList)
scale = lambda x, y: x + y * (x - minV) / float(maxV - minV)
self.pointList = [(timeV, scale(f0V, heightAmount))
for timeV, f0V in self.pointList] | [
"def",
"adjustPeakHeight",
"(",
"self",
",",
"heightAmount",
")",
":",
"if",
"heightAmount",
"==",
"0",
":",
"return",
"pitchList",
"=",
"[",
"f0V",
"for",
"_",
",",
"f0V",
"in",
"self",
".",
"pointList",
"]",
"minV",
"=",
"min",
"(",
"pitchList",
")",... | Adjust peak height
The foot of the accent is left unchanged and intermediate
values are linearly scaled | [
"Adjust",
"peak",
"height",
"The",
"foot",
"of",
"the",
"accent",
"is",
"left",
"unchanged",
"and",
"intermediate",
"values",
"are",
"linearly",
"scaled"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/modify_pitch_accent.py#L47-L63 | train |
timmahrt/ProMo | promo/morph_utils/modify_pitch_accent.py | PitchAccent.addPlateau | def addPlateau(self, plateauAmount, pitchSampFreq=None):
'''
Add a plateau
A negative plateauAmount will move the peak backwards.
A positive plateauAmount will move the peak forwards.
All points on the side of the peak growth will also get moved.
i.e. the slope of the peak does not change. The accent gets
wider instead.
If pitchSampFreq=None, the plateau will only be specified by
the start and end points of the plateau
'''
if plateauAmount == 0:
return
maxPoint = self.pointList[self.peakI]
# Define the plateau
if pitchSampFreq is not None:
numSteps = abs(int(plateauAmount / pitchSampFreq))
timeChangeList = [stepV * pitchSampFreq
for stepV in
range(0, numSteps + 1)]
else:
timeChangeList = [plateauAmount, ]
# Shift the side being pushed by the plateau
if plateauAmount < 0: # Plateau moves left of the peak
leftSide = self.pointList[:self.peakI]
rightSide = self.pointList[self.peakI:]
plateauPoints = [(maxPoint[0] + timeChange, maxPoint[1])
for timeChange in timeChangeList]
leftSide = [(timeV + plateauAmount, f0V)
for timeV, f0V in leftSide]
self.netLeftShift += plateauAmount
elif plateauAmount > 0: # Plateau moves right of the peak
leftSide = self.pointList[:self.peakI + 1]
rightSide = self.pointList[self.peakI + 1:]
plateauPoints = [(maxPoint[0] + timeChange, maxPoint[1])
for timeChange in timeChangeList]
rightSide = [(timeV + plateauAmount, f0V)
for timeV, f0V in rightSide]
self.netRightShift += plateauAmount
self.pointList = leftSide + plateauPoints + rightSide | python | def addPlateau(self, plateauAmount, pitchSampFreq=None):
'''
Add a plateau
A negative plateauAmount will move the peak backwards.
A positive plateauAmount will move the peak forwards.
All points on the side of the peak growth will also get moved.
i.e. the slope of the peak does not change. The accent gets
wider instead.
If pitchSampFreq=None, the plateau will only be specified by
the start and end points of the plateau
'''
if plateauAmount == 0:
return
maxPoint = self.pointList[self.peakI]
# Define the plateau
if pitchSampFreq is not None:
numSteps = abs(int(plateauAmount / pitchSampFreq))
timeChangeList = [stepV * pitchSampFreq
for stepV in
range(0, numSteps + 1)]
else:
timeChangeList = [plateauAmount, ]
# Shift the side being pushed by the plateau
if plateauAmount < 0: # Plateau moves left of the peak
leftSide = self.pointList[:self.peakI]
rightSide = self.pointList[self.peakI:]
plateauPoints = [(maxPoint[0] + timeChange, maxPoint[1])
for timeChange in timeChangeList]
leftSide = [(timeV + plateauAmount, f0V)
for timeV, f0V in leftSide]
self.netLeftShift += plateauAmount
elif plateauAmount > 0: # Plateau moves right of the peak
leftSide = self.pointList[:self.peakI + 1]
rightSide = self.pointList[self.peakI + 1:]
plateauPoints = [(maxPoint[0] + timeChange, maxPoint[1])
for timeChange in timeChangeList]
rightSide = [(timeV + plateauAmount, f0V)
for timeV, f0V in rightSide]
self.netRightShift += plateauAmount
self.pointList = leftSide + plateauPoints + rightSide | [
"def",
"addPlateau",
"(",
"self",
",",
"plateauAmount",
",",
"pitchSampFreq",
"=",
"None",
")",
":",
"if",
"plateauAmount",
"==",
"0",
":",
"return",
"maxPoint",
"=",
"self",
".",
"pointList",
"[",
"self",
".",
"peakI",
"]",
"# Define the plateau",
"if",
"... | Add a plateau
A negative plateauAmount will move the peak backwards.
A positive plateauAmount will move the peak forwards.
All points on the side of the peak growth will also get moved.
i.e. the slope of the peak does not change. The accent gets
wider instead.
If pitchSampFreq=None, the plateau will only be specified by
the start and end points of the plateau | [
"Add",
"a",
"plateau",
"A",
"negative",
"plateauAmount",
"will",
"move",
"the",
"peak",
"backwards",
".",
"A",
"positive",
"plateauAmount",
"will",
"move",
"the",
"peak",
"forwards",
".",
"All",
"points",
"on",
"the",
"side",
"of",
"the",
"peak",
"growth",
... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/modify_pitch_accent.py#L65-L114 | train |
timmahrt/ProMo | promo/morph_utils/modify_pitch_accent.py | PitchAccent.shiftAccent | def shiftAccent(self, shiftAmount):
'''
Move the whole accent earlier or later
'''
if shiftAmount == 0:
return
self.pointList = [(time + shiftAmount, pitch)
for time, pitch in self.pointList]
# Update shift amounts
if shiftAmount < 0:
self.netLeftShift += shiftAmount
elif shiftAmount >= 0:
self.netRightShift += shiftAmount | python | def shiftAccent(self, shiftAmount):
'''
Move the whole accent earlier or later
'''
if shiftAmount == 0:
return
self.pointList = [(time + shiftAmount, pitch)
for time, pitch in self.pointList]
# Update shift amounts
if shiftAmount < 0:
self.netLeftShift += shiftAmount
elif shiftAmount >= 0:
self.netRightShift += shiftAmount | [
"def",
"shiftAccent",
"(",
"self",
",",
"shiftAmount",
")",
":",
"if",
"shiftAmount",
"==",
"0",
":",
"return",
"self",
".",
"pointList",
"=",
"[",
"(",
"time",
"+",
"shiftAmount",
",",
"pitch",
")",
"for",
"time",
",",
"pitch",
"in",
"self",
".",
"p... | Move the whole accent earlier or later | [
"Move",
"the",
"whole",
"accent",
"earlier",
"or",
"later"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/modify_pitch_accent.py#L116-L130 | train |
timmahrt/ProMo | promo/morph_utils/modify_pitch_accent.py | PitchAccent.deleteOverlapping | def deleteOverlapping(self, targetList):
'''
Erase points from another list that overlap with points in this list
'''
start = self.pointList[0][0]
stop = self.pointList[-1][0]
if self.netLeftShift < 0:
start += self.netLeftShift
if self.netRightShift > 0:
stop += self.netRightShift
targetList = _deletePoints(targetList, start, stop)
return targetList | python | def deleteOverlapping(self, targetList):
'''
Erase points from another list that overlap with points in this list
'''
start = self.pointList[0][0]
stop = self.pointList[-1][0]
if self.netLeftShift < 0:
start += self.netLeftShift
if self.netRightShift > 0:
stop += self.netRightShift
targetList = _deletePoints(targetList, start, stop)
return targetList | [
"def",
"deleteOverlapping",
"(",
"self",
",",
"targetList",
")",
":",
"start",
"=",
"self",
".",
"pointList",
"[",
"0",
"]",
"[",
"0",
"]",
"stop",
"=",
"self",
".",
"pointList",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"if",
"self",
".",
"netLeftShift",... | Erase points from another list that overlap with points in this list | [
"Erase",
"points",
"from",
"another",
"list",
"that",
"overlap",
"with",
"points",
"in",
"this",
"list"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/modify_pitch_accent.py#L132-L147 | train |
timmahrt/ProMo | promo/morph_utils/modify_pitch_accent.py | PitchAccent.reintegrate | def reintegrate(self, fullPointList):
'''
Integrates the pitch values of the accent into a larger pitch contour
'''
# Erase the original region of the accent
fullPointList = _deletePoints(fullPointList, self.minT, self.maxT)
# Erase the new region of the accent
fullPointList = self.deleteOverlapping(fullPointList)
# Add the accent into the full pitch list
outputPointList = fullPointList + self.pointList
outputPointList.sort()
return outputPointList | python | def reintegrate(self, fullPointList):
'''
Integrates the pitch values of the accent into a larger pitch contour
'''
# Erase the original region of the accent
fullPointList = _deletePoints(fullPointList, self.minT, self.maxT)
# Erase the new region of the accent
fullPointList = self.deleteOverlapping(fullPointList)
# Add the accent into the full pitch list
outputPointList = fullPointList + self.pointList
outputPointList.sort()
return outputPointList | [
"def",
"reintegrate",
"(",
"self",
",",
"fullPointList",
")",
":",
"# Erase the original region of the accent",
"fullPointList",
"=",
"_deletePoints",
"(",
"fullPointList",
",",
"self",
".",
"minT",
",",
"self",
".",
"maxT",
")",
"# Erase the new region of the accent",
... | Integrates the pitch values of the accent into a larger pitch contour | [
"Integrates",
"the",
"pitch",
"values",
"of",
"the",
"accent",
"into",
"a",
"larger",
"pitch",
"contour"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/modify_pitch_accent.py#L149-L163 | train |
hermanschaaf/mafan | mafan/encoding.py | convert | def convert(filename, new_filename=None, overwrite=False, to_encoding='utf-8', force=True):
""" Convert file with crappy encoding to a new proper encoding (or vice versa if you wish).
filename -- the name, partial path or full path of the file you want to encode to a new encoding
new_filename -- (optional) the name of the new file to be generated using the new encoding
overwrite -- if `new_filename` is omitted, set this to True to change the supplied file's
encoding and not bother creating a new file (be careful! loss of information is likely)
to_encoding -- the name of the encoding you wish to convert to (utf-8 by default)
force -- Encode even if the current file is already in the correct encoding.
"""
logging.info('Opening file %s' % filename)
f = open(filename)
detection = chardet.detect(f.read())
f.close()
encoding = detection.get('encoding')
confidence = detection.get('confidence')
logging.info('I think it is %s with %.1f%% confidence' % (encoding, confidence * 100.0))
delete_original = bool(new_filename) == False and overwrite
if not new_filename or new_filename == filename:
# use the current filename, but add the encoding to the name (while keeping extension intact)
base_name, ext = os.path.splitext(filename)
new_filename = base_name + '_%s' % to_encoding + ext
if not encoding.lower() == to_encoding.lower():
logging.info('Converting to %s with iconv...' % to_encoding)
else:
logging.info('Already in correct encoding.')
if force:
logging.info('Going ahead anyway, because force == True (the force is strong with this one)')
else:
logging.warning('Stopping. Use force = True if you want to force the encoding.')
return None
# command example: iconv -f gb18030 -t utf-8 chs.srt > chs-utf8.srt
# "iconv" does not support -o parameter now and use stdout to instead.
with open(new_filename, 'w') as output_file:
p = subprocess.Popen(['iconv', '-f', encoding, '-t', to_encoding + "//IGNORE", \
os.path.abspath(filename)], shell=False, \
stdout=output_file, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
retval = p.wait()
if delete_original and os.path.isfile(new_filename):
os.remove(filename)
os.rename(new_filename, filename)
new_filename = filename
return new_filename | python | def convert(filename, new_filename=None, overwrite=False, to_encoding='utf-8', force=True):
""" Convert file with crappy encoding to a new proper encoding (or vice versa if you wish).
filename -- the name, partial path or full path of the file you want to encode to a new encoding
new_filename -- (optional) the name of the new file to be generated using the new encoding
overwrite -- if `new_filename` is omitted, set this to True to change the supplied file's
encoding and not bother creating a new file (be careful! loss of information is likely)
to_encoding -- the name of the encoding you wish to convert to (utf-8 by default)
force -- Encode even if the current file is already in the correct encoding.
"""
logging.info('Opening file %s' % filename)
f = open(filename)
detection = chardet.detect(f.read())
f.close()
encoding = detection.get('encoding')
confidence = detection.get('confidence')
logging.info('I think it is %s with %.1f%% confidence' % (encoding, confidence * 100.0))
delete_original = bool(new_filename) == False and overwrite
if not new_filename or new_filename == filename:
# use the current filename, but add the encoding to the name (while keeping extension intact)
base_name, ext = os.path.splitext(filename)
new_filename = base_name + '_%s' % to_encoding + ext
if not encoding.lower() == to_encoding.lower():
logging.info('Converting to %s with iconv...' % to_encoding)
else:
logging.info('Already in correct encoding.')
if force:
logging.info('Going ahead anyway, because force == True (the force is strong with this one)')
else:
logging.warning('Stopping. Use force = True if you want to force the encoding.')
return None
# command example: iconv -f gb18030 -t utf-8 chs.srt > chs-utf8.srt
# "iconv" does not support -o parameter now and use stdout to instead.
with open(new_filename, 'w') as output_file:
p = subprocess.Popen(['iconv', '-f', encoding, '-t', to_encoding + "//IGNORE", \
os.path.abspath(filename)], shell=False, \
stdout=output_file, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
retval = p.wait()
if delete_original and os.path.isfile(new_filename):
os.remove(filename)
os.rename(new_filename, filename)
new_filename = filename
return new_filename | [
"def",
"convert",
"(",
"filename",
",",
"new_filename",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"to_encoding",
"=",
"'utf-8'",
",",
"force",
"=",
"True",
")",
":",
"logging",
".",
"info",
"(",
"'Opening file %s'",
"%",
"filename",
")",
"f",
"="... | Convert file with crappy encoding to a new proper encoding (or vice versa if you wish).
filename -- the name, partial path or full path of the file you want to encode to a new encoding
new_filename -- (optional) the name of the new file to be generated using the new encoding
overwrite -- if `new_filename` is omitted, set this to True to change the supplied file's
encoding and not bother creating a new file (be careful! loss of information is likely)
to_encoding -- the name of the encoding you wish to convert to (utf-8 by default)
force -- Encode even if the current file is already in the correct encoding. | [
"Convert",
"file",
"with",
"crappy",
"encoding",
"to",
"a",
"new",
"proper",
"encoding",
"(",
"or",
"vice",
"versa",
"if",
"you",
"wish",
")",
"."
] | 373ddf299aeb2bd8413bf921c71768af7a8170ea | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/encoding.py#L17-L64 | train |
hermanschaaf/mafan | mafan/encoding.py | detect | def detect(filename, include_confidence=False):
"""
Detect the encoding of a file.
Returns only the predicted current encoding as a string.
If `include_confidence` is True,
Returns tuple containing: (str encoding, float confidence)
"""
f = open(filename)
detection = chardet.detect(f.read())
f.close()
encoding = detection.get('encoding')
confidence = detection.get('confidence')
if include_confidence:
return (encoding, confidence)
return encoding | python | def detect(filename, include_confidence=False):
"""
Detect the encoding of a file.
Returns only the predicted current encoding as a string.
If `include_confidence` is True,
Returns tuple containing: (str encoding, float confidence)
"""
f = open(filename)
detection = chardet.detect(f.read())
f.close()
encoding = detection.get('encoding')
confidence = detection.get('confidence')
if include_confidence:
return (encoding, confidence)
return encoding | [
"def",
"detect",
"(",
"filename",
",",
"include_confidence",
"=",
"False",
")",
":",
"f",
"=",
"open",
"(",
"filename",
")",
"detection",
"=",
"chardet",
".",
"detect",
"(",
"f",
".",
"read",
"(",
")",
")",
"f",
".",
"close",
"(",
")",
"encoding",
... | Detect the encoding of a file.
Returns only the predicted current encoding as a string.
If `include_confidence` is True,
Returns tuple containing: (str encoding, float confidence) | [
"Detect",
"the",
"encoding",
"of",
"a",
"file",
"."
] | 373ddf299aeb2bd8413bf921c71768af7a8170ea | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/encoding.py#L67-L83 | train |
hermanschaaf/mafan | mafan/download_data.py | download | def download(url, localFileName=None, localDirName=None):
"""
Utility function for downloading files from the web
and retaining the same filename.
"""
localName = url2name(url)
req = Request(url)
r = urlopen(req)
if r.info().has_key('Content-Disposition'):
# If the response has Content-Disposition, we take file name from it
localName = r.info()['Content-Disposition'].split('filename=')
if len(localName) > 1:
localName = localName[1]
if localName[0] == '"' or localName[0] == "'":
localName = localName[1:-1]
else:
localName = url2name(r.url)
elif r.url != url:
# if we were redirected, the real file name we take from the final URL
localName = url2name(r.url)
if localFileName:
# we can force to save the file as specified name
localName = localFileName
if localDirName:
# we can also put it in some custom directory
if not os.path.exists(localDirName):
os.makedirs(localDirName)
localName = os.path.join(localDirName, localName)
f = open(localName, 'wb')
f.write(r.read())
f.close() | python | def download(url, localFileName=None, localDirName=None):
"""
Utility function for downloading files from the web
and retaining the same filename.
"""
localName = url2name(url)
req = Request(url)
r = urlopen(req)
if r.info().has_key('Content-Disposition'):
# If the response has Content-Disposition, we take file name from it
localName = r.info()['Content-Disposition'].split('filename=')
if len(localName) > 1:
localName = localName[1]
if localName[0] == '"' or localName[0] == "'":
localName = localName[1:-1]
else:
localName = url2name(r.url)
elif r.url != url:
# if we were redirected, the real file name we take from the final URL
localName = url2name(r.url)
if localFileName:
# we can force to save the file as specified name
localName = localFileName
if localDirName:
# we can also put it in some custom directory
if not os.path.exists(localDirName):
os.makedirs(localDirName)
localName = os.path.join(localDirName, localName)
f = open(localName, 'wb')
f.write(r.read())
f.close() | [
"def",
"download",
"(",
"url",
",",
"localFileName",
"=",
"None",
",",
"localDirName",
"=",
"None",
")",
":",
"localName",
"=",
"url2name",
"(",
"url",
")",
"req",
"=",
"Request",
"(",
"url",
")",
"r",
"=",
"urlopen",
"(",
"req",
")",
"if",
"r",
".... | Utility function for downloading files from the web
and retaining the same filename. | [
"Utility",
"function",
"for",
"downloading",
"files",
"from",
"the",
"web",
"and",
"retaining",
"the",
"same",
"filename",
"."
] | 373ddf299aeb2bd8413bf921c71768af7a8170ea | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/download_data.py#L22-L53 | train |
hermanschaaf/mafan | mafan/third_party/jianfan/__init__.py | _t | def _t(unistr, charset_from, charset_to):
"""
This is a unexposed function, is responsibility for translation internal.
"""
# if type(unistr) is str:
# try:
# unistr = unistr.decode('utf-8')
# # Python 3 returns AttributeError when .decode() is called on a str
# # This means it is already unicode.
# except AttributeError:
# pass
# try:
# if type(unistr) is not unicode:
# return unistr
# # Python 3 returns NameError because unicode is not a type.
# except NameError:
# pass
chars = []
for c in unistr:
idx = charset_from.find(c)
chars.append(charset_to[idx] if idx!=-1 else c)
return u''.join(chars) | python | def _t(unistr, charset_from, charset_to):
"""
This is a unexposed function, is responsibility for translation internal.
"""
# if type(unistr) is str:
# try:
# unistr = unistr.decode('utf-8')
# # Python 3 returns AttributeError when .decode() is called on a str
# # This means it is already unicode.
# except AttributeError:
# pass
# try:
# if type(unistr) is not unicode:
# return unistr
# # Python 3 returns NameError because unicode is not a type.
# except NameError:
# pass
chars = []
for c in unistr:
idx = charset_from.find(c)
chars.append(charset_to[idx] if idx!=-1 else c)
return u''.join(chars) | [
"def",
"_t",
"(",
"unistr",
",",
"charset_from",
",",
"charset_to",
")",
":",
"# if type(unistr) is str:",
"# try:",
"# unistr = unistr.decode('utf-8')",
"# # Python 3 returns AttributeError when .decode() is called on a str",
"# # This means it is already unicode.",
... | This is a unexposed function, is responsibility for translation internal. | [
"This",
"is",
"a",
"unexposed",
"function",
"is",
"responsibility",
"for",
"translation",
"internal",
"."
] | 373ddf299aeb2bd8413bf921c71768af7a8170ea | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/third_party/jianfan/__init__.py#L23-L45 | train |
hermanschaaf/mafan | mafan/hanzidentifier/hanzidentifier.py | identify | def identify(text):
"""Identify whether a string is simplified or traditional Chinese.
Returns:
None: if there are no recognizd Chinese characters.
EITHER: if the test is inconclusive.
TRAD: if the text is traditional.
SIMP: if the text is simplified.
BOTH: the text has characters recognized as being solely traditional
and other characters recognized as being solely simplified.
"""
filtered_text = set(list(text)).intersection(ALL_CHARS)
if len(filtered_text) is 0:
return None
if filtered_text.issubset(SHARED_CHARS):
return EITHER
if filtered_text.issubset(TRAD_CHARS):
return TRAD
if filtered_text.issubset(SIMP_CHARS):
return SIMP
if filtered_text.difference(TRAD_CHARS).issubset(SIMP_CHARS):
return BOTH | python | def identify(text):
"""Identify whether a string is simplified or traditional Chinese.
Returns:
None: if there are no recognizd Chinese characters.
EITHER: if the test is inconclusive.
TRAD: if the text is traditional.
SIMP: if the text is simplified.
BOTH: the text has characters recognized as being solely traditional
and other characters recognized as being solely simplified.
"""
filtered_text = set(list(text)).intersection(ALL_CHARS)
if len(filtered_text) is 0:
return None
if filtered_text.issubset(SHARED_CHARS):
return EITHER
if filtered_text.issubset(TRAD_CHARS):
return TRAD
if filtered_text.issubset(SIMP_CHARS):
return SIMP
if filtered_text.difference(TRAD_CHARS).issubset(SIMP_CHARS):
return BOTH | [
"def",
"identify",
"(",
"text",
")",
":",
"filtered_text",
"=",
"set",
"(",
"list",
"(",
"text",
")",
")",
".",
"intersection",
"(",
"ALL_CHARS",
")",
"if",
"len",
"(",
"filtered_text",
")",
"is",
"0",
":",
"return",
"None",
"if",
"filtered_text",
".",... | Identify whether a string is simplified or traditional Chinese.
Returns:
None: if there are no recognizd Chinese characters.
EITHER: if the test is inconclusive.
TRAD: if the text is traditional.
SIMP: if the text is simplified.
BOTH: the text has characters recognized as being solely traditional
and other characters recognized as being solely simplified. | [
"Identify",
"whether",
"a",
"string",
"is",
"simplified",
"or",
"traditional",
"Chinese",
"."
] | 373ddf299aeb2bd8413bf921c71768af7a8170ea | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/hanzidentifier/hanzidentifier.py#L38-L60 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | makeSequenceRelative | def makeSequenceRelative(absVSequence):
'''
Puts every value in a list on a continuum between 0 and 1
Also returns the min and max values (to reverse the process)
'''
if len(absVSequence) < 2 or len(set(absVSequence)) == 1:
raise RelativizeSequenceException(absVSequence)
minV = min(absVSequence)
maxV = max(absVSequence)
relativeSeq = [(value - minV) / (maxV - minV) for value in absVSequence]
return relativeSeq, minV, maxV | python | def makeSequenceRelative(absVSequence):
'''
Puts every value in a list on a continuum between 0 and 1
Also returns the min and max values (to reverse the process)
'''
if len(absVSequence) < 2 or len(set(absVSequence)) == 1:
raise RelativizeSequenceException(absVSequence)
minV = min(absVSequence)
maxV = max(absVSequence)
relativeSeq = [(value - minV) / (maxV - minV) for value in absVSequence]
return relativeSeq, minV, maxV | [
"def",
"makeSequenceRelative",
"(",
"absVSequence",
")",
":",
"if",
"len",
"(",
"absVSequence",
")",
"<",
"2",
"or",
"len",
"(",
"set",
"(",
"absVSequence",
")",
")",
"==",
"1",
":",
"raise",
"RelativizeSequenceException",
"(",
"absVSequence",
")",
"minV",
... | Puts every value in a list on a continuum between 0 and 1
Also returns the min and max values (to reverse the process) | [
"Puts",
"every",
"value",
"in",
"a",
"list",
"on",
"a",
"continuum",
"between",
"0",
"and",
"1"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L33-L47 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | makeSequenceAbsolute | def makeSequenceAbsolute(relVSequence, minV, maxV):
'''
Makes every value in a sequence absolute
'''
return [(value * (maxV - minV)) + minV for value in relVSequence] | python | def makeSequenceAbsolute(relVSequence, minV, maxV):
'''
Makes every value in a sequence absolute
'''
return [(value * (maxV - minV)) + minV for value in relVSequence] | [
"def",
"makeSequenceAbsolute",
"(",
"relVSequence",
",",
"minV",
",",
"maxV",
")",
":",
"return",
"[",
"(",
"value",
"*",
"(",
"maxV",
"-",
"minV",
")",
")",
"+",
"minV",
"for",
"value",
"in",
"relVSequence",
"]"
] | Makes every value in a sequence absolute | [
"Makes",
"every",
"value",
"in",
"a",
"sequence",
"absolute"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L50-L55 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | _makeTimingRelative | def _makeTimingRelative(absoluteDataList):
'''
Given normal pitch tier data, puts the times on a scale from 0 to 1
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
Also returns the start and end time so that the process can be reversed
'''
timingSeq = [row[0] for row in absoluteDataList]
valueSeq = [list(row[1:]) for row in absoluteDataList]
relTimingSeq, startTime, endTime = makeSequenceRelative(timingSeq)
relDataList = [tuple([time, ] + row) for time, row
in zip(relTimingSeq, valueSeq)]
return relDataList, startTime, endTime | python | def _makeTimingRelative(absoluteDataList):
'''
Given normal pitch tier data, puts the times on a scale from 0 to 1
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
Also returns the start and end time so that the process can be reversed
'''
timingSeq = [row[0] for row in absoluteDataList]
valueSeq = [list(row[1:]) for row in absoluteDataList]
relTimingSeq, startTime, endTime = makeSequenceRelative(timingSeq)
relDataList = [tuple([time, ] + row) for time, row
in zip(relTimingSeq, valueSeq)]
return relDataList, startTime, endTime | [
"def",
"_makeTimingRelative",
"(",
"absoluteDataList",
")",
":",
"timingSeq",
"=",
"[",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"absoluteDataList",
"]",
"valueSeq",
"=",
"[",
"list",
"(",
"row",
"[",
"1",
":",
"]",
")",
"for",
"row",
"in",
"absoluteD... | Given normal pitch tier data, puts the times on a scale from 0 to 1
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
Also returns the start and end time so that the process can be reversed | [
"Given",
"normal",
"pitch",
"tier",
"data",
"puts",
"the",
"times",
"on",
"a",
"scale",
"from",
"0",
"to",
"1"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L58-L76 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | _makeTimingAbsolute | def _makeTimingAbsolute(relativeDataList, startTime, endTime):
'''
Maps values from 0 to 1 to the provided start and end time
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
'''
timingSeq = [row[0] for row in relativeDataList]
valueSeq = [list(row[1:]) for row in relativeDataList]
absTimingSeq = makeSequenceAbsolute(timingSeq, startTime, endTime)
absDataList = [tuple([time, ] + row) for time, row
in zip(absTimingSeq, valueSeq)]
return absDataList | python | def _makeTimingAbsolute(relativeDataList, startTime, endTime):
'''
Maps values from 0 to 1 to the provided start and end time
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
'''
timingSeq = [row[0] for row in relativeDataList]
valueSeq = [list(row[1:]) for row in relativeDataList]
absTimingSeq = makeSequenceAbsolute(timingSeq, startTime, endTime)
absDataList = [tuple([time, ] + row) for time, row
in zip(absTimingSeq, valueSeq)]
return absDataList | [
"def",
"_makeTimingAbsolute",
"(",
"relativeDataList",
",",
"startTime",
",",
"endTime",
")",
":",
"timingSeq",
"=",
"[",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"relativeDataList",
"]",
"valueSeq",
"=",
"[",
"list",
"(",
"row",
"[",
"1",
":",
"]",
"... | Maps values from 0 to 1 to the provided start and end time
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...] | [
"Maps",
"values",
"from",
"0",
"to",
"1",
"to",
"the",
"provided",
"start",
"and",
"end",
"time"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L79-L95 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | _getSmallestDifference | def _getSmallestDifference(inputList, targetVal):
'''
Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast
'''
targetList = inputList[:]
retVal = None
while True:
# If we're down to one value, stop iterating
if len(targetList) == 1:
retVal = targetList[0]
break
halfPoint = int(len(targetList) / 2.0) - 1
a = targetList[halfPoint]
b = targetList[halfPoint + 1]
leftDiff = abs(targetVal - a)
rightDiff = abs(targetVal - b)
# If the distance is 0, stop iterating, the targetVal is present
# in the inputList
if leftDiff == 0 or rightDiff == 0:
retVal = targetVal
break
# Look at left half or right half
if leftDiff < rightDiff:
targetList = targetList[:halfPoint + 1]
else:
targetList = targetList[halfPoint + 1:]
return retVal | python | def _getSmallestDifference(inputList, targetVal):
'''
Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast
'''
targetList = inputList[:]
retVal = None
while True:
# If we're down to one value, stop iterating
if len(targetList) == 1:
retVal = targetList[0]
break
halfPoint = int(len(targetList) / 2.0) - 1
a = targetList[halfPoint]
b = targetList[halfPoint + 1]
leftDiff = abs(targetVal - a)
rightDiff = abs(targetVal - b)
# If the distance is 0, stop iterating, the targetVal is present
# in the inputList
if leftDiff == 0 or rightDiff == 0:
retVal = targetVal
break
# Look at left half or right half
if leftDiff < rightDiff:
targetList = targetList[:halfPoint + 1]
else:
targetList = targetList[halfPoint + 1:]
return retVal | [
"def",
"_getSmallestDifference",
"(",
"inputList",
",",
"targetVal",
")",
":",
"targetList",
"=",
"inputList",
"[",
":",
"]",
"retVal",
"=",
"None",
"while",
"True",
":",
"# If we're down to one value, stop iterating",
"if",
"len",
"(",
"targetList",
")",
"==",
... | Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast | [
"Returns",
"the",
"value",
"in",
"inputList",
"that",
"is",
"closest",
"to",
"targetVal",
"Iteratively",
"splits",
"the",
"dataset",
"in",
"two",
"so",
"it",
"should",
"be",
"pretty",
"fast"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L98-L130 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | _getNearestMappingIndexList | def _getNearestMappingIndexList(fromValList, toValList):
'''
Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2]
'''
indexList = []
for fromTimestamp in fromValList:
smallestDiff = _getSmallestDifference(toValList, fromTimestamp)
i = toValList.index(smallestDiff)
indexList.append(i)
return indexList | python | def _getNearestMappingIndexList(fromValList, toValList):
'''
Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2]
'''
indexList = []
for fromTimestamp in fromValList:
smallestDiff = _getSmallestDifference(toValList, fromTimestamp)
i = toValList.index(smallestDiff)
indexList.append(i)
return indexList | [
"def",
"_getNearestMappingIndexList",
"(",
"fromValList",
",",
"toValList",
")",
":",
"indexList",
"=",
"[",
"]",
"for",
"fromTimestamp",
"in",
"fromValList",
":",
"smallestDiff",
"=",
"_getSmallestDifference",
"(",
"toValList",
",",
"fromTimestamp",
")",
"i",
"="... | Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2] | [
"Finds",
"the",
"indicies",
"for",
"data",
"points",
"that",
"are",
"closest",
"to",
"each",
"other",
"."
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L133-L148 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | morphDataLists | def morphDataLists(fromList, toList, stepList):
'''
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
'''
# If there are more than 1 pitch value, then we align the data in
# relative time.
# Each data point comes with a timestamp. The earliest timestamp is 0
# and the latest timestamp is 1. Using this method, for each relative
# timestamp in the source list, we find the closest relative timestamp
# in the target list. Just because two pitch values have the same index
# in the source and target lists does not mean that they correspond to
# the same speech event.
fromListRel, fromStartTime, fromEndTime = _makeTimingRelative(fromList)
toListRel = _makeTimingRelative(toList)[0]
# If fromList has more points, we'll have flat areas
# If toList has more points, we'll might miss peaks or valleys
fromTimeList = [dataTuple[0] for dataTuple in fromListRel]
toTimeList = [dataTuple[0] for dataTuple in toListRel]
indexList = _getNearestMappingIndexList(fromTimeList, toTimeList)
alignedToPitchRel = [toListRel[i] for i in indexList]
for stepAmount in stepList:
newPitchList = []
# Perform the interpolation
for fromTuple, toTuple in zip(fromListRel, alignedToPitchRel):
fromTime, fromValue = fromTuple
toTime, toValue = toTuple
# i + 1 b/c i_0 = 0 = no change
newValue = fromValue + (stepAmount * (toValue - fromValue))
newTime = fromTime + (stepAmount * (toTime - fromTime))
newPitchList.append((newTime, newValue))
newPitchList = _makeTimingAbsolute(newPitchList, fromStartTime,
fromEndTime)
yield stepAmount, newPitchList | python | def morphDataLists(fromList, toList, stepList):
'''
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
'''
# If there are more than 1 pitch value, then we align the data in
# relative time.
# Each data point comes with a timestamp. The earliest timestamp is 0
# and the latest timestamp is 1. Using this method, for each relative
# timestamp in the source list, we find the closest relative timestamp
# in the target list. Just because two pitch values have the same index
# in the source and target lists does not mean that they correspond to
# the same speech event.
fromListRel, fromStartTime, fromEndTime = _makeTimingRelative(fromList)
toListRel = _makeTimingRelative(toList)[0]
# If fromList has more points, we'll have flat areas
# If toList has more points, we'll might miss peaks or valleys
fromTimeList = [dataTuple[0] for dataTuple in fromListRel]
toTimeList = [dataTuple[0] for dataTuple in toListRel]
indexList = _getNearestMappingIndexList(fromTimeList, toTimeList)
alignedToPitchRel = [toListRel[i] for i in indexList]
for stepAmount in stepList:
newPitchList = []
# Perform the interpolation
for fromTuple, toTuple in zip(fromListRel, alignedToPitchRel):
fromTime, fromValue = fromTuple
toTime, toValue = toTuple
# i + 1 b/c i_0 = 0 = no change
newValue = fromValue + (stepAmount * (toValue - fromValue))
newTime = fromTime + (stepAmount * (toTime - fromTime))
newPitchList.append((newTime, newValue))
newPitchList = _makeTimingAbsolute(newPitchList, fromStartTime,
fromEndTime)
yield stepAmount, newPitchList | [
"def",
"morphDataLists",
"(",
"fromList",
",",
"toList",
",",
"stepList",
")",
":",
"# If there are more than 1 pitch value, then we align the data in",
"# relative time.",
"# Each data point comes with a timestamp. The earliest timestamp is 0",
"# and the latest timestamp is 1. Using th... | Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value | [
"Iteratively",
"morph",
"fromList",
"into",
"toList",
"using",
"the",
"values",
"0",
"to",
"1",
"in",
"stepList",
"stepList",
":",
"a",
"value",
"of",
"0",
"means",
"no",
"change",
"and",
"a",
"value",
"of",
"1",
"means",
"a",
"complete",
"change",
"to",... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L151-L194 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | morphChunkedDataLists | def morphChunkedDataLists(fromDataList, toDataList, stepList):
'''
Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together.
'''
assert(len(fromDataList) == len(toDataList))
# Morph the fromDataList into the toDataList
outputList = []
for x, y in zip(fromDataList, toDataList):
# We cannot morph a region if there is no data or only
# a single data point for either side
if (len(x) < 2) or (len(y) < 2):
continue
tmpList = [outputPitchList for _, outputPitchList
in morphDataLists(x, y, stepList)]
outputList.append(tmpList)
# Transpose list
finalOutputList = outputList.pop(0)
for subList in outputList:
for i, subsubList in enumerate(subList):
finalOutputList[i].extend(subsubList)
return finalOutputList | python | def morphChunkedDataLists(fromDataList, toDataList, stepList):
'''
Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together.
'''
assert(len(fromDataList) == len(toDataList))
# Morph the fromDataList into the toDataList
outputList = []
for x, y in zip(fromDataList, toDataList):
# We cannot morph a region if there is no data or only
# a single data point for either side
if (len(x) < 2) or (len(y) < 2):
continue
tmpList = [outputPitchList for _, outputPitchList
in morphDataLists(x, y, stepList)]
outputList.append(tmpList)
# Transpose list
finalOutputList = outputList.pop(0)
for subList in outputList:
for i, subsubList in enumerate(subList):
finalOutputList[i].extend(subsubList)
return finalOutputList | [
"def",
"morphChunkedDataLists",
"(",
"fromDataList",
",",
"toDataList",
",",
"stepList",
")",
":",
"assert",
"(",
"len",
"(",
"fromDataList",
")",
"==",
"len",
"(",
"toDataList",
")",
")",
"# Morph the fromDataList into the toDataList",
"outputList",
"=",
"[",
"]"... | Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together. | [
"Morph",
"one",
"set",
"of",
"data",
"into",
"another",
"in",
"a",
"stepwise",
"fashion"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L197-L228 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | morphAveragePitch | def morphAveragePitch(fromDataList, toDataList):
'''
Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code removes any values below zero, thus the
final average might not match the target average.
'''
timeList, fromPitchList = zip(*fromDataList)
toPitchList = [pitchVal for _, pitchVal in toDataList]
# Zero pitch values aren't meaningful, so filter them out if they are
# in the dataset
fromListNoZeroes = [val for val in fromPitchList if val > 0]
fromAverage = sum(fromListNoZeroes) / float(len(fromListNoZeroes))
toListNoZeroes = [val for val in toPitchList if val > 0]
toAverage = sum(toListNoZeroes) / float(len(toListNoZeroes))
newPitchList = [val - fromAverage + toAverage for val in fromPitchList]
# finalAverage = sum(newPitchList) / float(len(newPitchList))
# Removing zeroes and negative pitch values
retDataList = [(time, pitchVal) for time, pitchVal
in zip(timeList, newPitchList)
if pitchVal > 0]
return retDataList | python | def morphAveragePitch(fromDataList, toDataList):
'''
Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code removes any values below zero, thus the
final average might not match the target average.
'''
timeList, fromPitchList = zip(*fromDataList)
toPitchList = [pitchVal for _, pitchVal in toDataList]
# Zero pitch values aren't meaningful, so filter them out if they are
# in the dataset
fromListNoZeroes = [val for val in fromPitchList if val > 0]
fromAverage = sum(fromListNoZeroes) / float(len(fromListNoZeroes))
toListNoZeroes = [val for val in toPitchList if val > 0]
toAverage = sum(toListNoZeroes) / float(len(toListNoZeroes))
newPitchList = [val - fromAverage + toAverage for val in fromPitchList]
# finalAverage = sum(newPitchList) / float(len(newPitchList))
# Removing zeroes and negative pitch values
retDataList = [(time, pitchVal) for time, pitchVal
in zip(timeList, newPitchList)
if pitchVal > 0]
return retDataList | [
"def",
"morphAveragePitch",
"(",
"fromDataList",
",",
"toDataList",
")",
":",
"timeList",
",",
"fromPitchList",
"=",
"zip",
"(",
"*",
"fromDataList",
")",
"toPitchList",
"=",
"[",
"pitchVal",
"for",
"_",
",",
"pitchVal",
"in",
"toDataList",
"]",
"# Zero pitch ... | Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code removes any values below zero, thus the
final average might not match the target average. | [
"Adjusts",
"the",
"values",
"in",
"fromPitchList",
"to",
"have",
"the",
"same",
"average",
"as",
"toPitchList",
"Because",
"other",
"manipulations",
"can",
"alter",
"the",
"average",
"pitch",
"morphing",
"the",
"pitch",
"is",
"the",
"last",
"pitch",
"manipulatio... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L231-L262 | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | morphRange | def morphRange(fromDataList, toDataList):
'''
Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList. The 75% largest value in fromDataList will be set to the
75% largest value in toDataList, etc.
Small sample sizes will yield results that are not very meaningful
'''
# Isolate and sort pitch values
fromPitchList = [dataTuple[1] for dataTuple in fromDataList]
toPitchList = [dataTuple[1] for dataTuple in toDataList]
fromPitchListSorted = sorted(fromPitchList)
toPitchListSorted = sorted(toPitchList)
# Bin pitch values between 0 and 1
fromListRel = makeSequenceRelative(fromPitchListSorted)[0]
toListRel = makeSequenceRelative(toPitchListSorted)[0]
# Find each values closest equivalent in the other list
indexList = _getNearestMappingIndexList(fromListRel, toListRel)
# Map the source pitch to the target pitch value
# Pitch value -> get sorted position -> get corresponding position in
# target list -> get corresponding pitch value = the new pitch value
retList = []
for time, pitch in fromDataList:
fromI = fromPitchListSorted.index(pitch)
toI = indexList[fromI]
newPitch = toPitchListSorted[toI]
retList.append((time, newPitch))
return retList | python | def morphRange(fromDataList, toDataList):
'''
Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList. The 75% largest value in fromDataList will be set to the
75% largest value in toDataList, etc.
Small sample sizes will yield results that are not very meaningful
'''
# Isolate and sort pitch values
fromPitchList = [dataTuple[1] for dataTuple in fromDataList]
toPitchList = [dataTuple[1] for dataTuple in toDataList]
fromPitchListSorted = sorted(fromPitchList)
toPitchListSorted = sorted(toPitchList)
# Bin pitch values between 0 and 1
fromListRel = makeSequenceRelative(fromPitchListSorted)[0]
toListRel = makeSequenceRelative(toPitchListSorted)[0]
# Find each values closest equivalent in the other list
indexList = _getNearestMappingIndexList(fromListRel, toListRel)
# Map the source pitch to the target pitch value
# Pitch value -> get sorted position -> get corresponding position in
# target list -> get corresponding pitch value = the new pitch value
retList = []
for time, pitch in fromDataList:
fromI = fromPitchListSorted.index(pitch)
toI = indexList[fromI]
newPitch = toPitchListSorted[toI]
retList.append((time, newPitch))
return retList | [
"def",
"morphRange",
"(",
"fromDataList",
",",
"toDataList",
")",
":",
"# Isolate and sort pitch values",
"fromPitchList",
"=",
"[",
"dataTuple",
"[",
"1",
"]",
"for",
"dataTuple",
"in",
"fromDataList",
"]",
"toPitchList",
"=",
"[",
"dataTuple",
"[",
"1",
"]",
... | Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList. The 75% largest value in fromDataList will be set to the
75% largest value in toDataList, etc.
Small sample sizes will yield results that are not very meaningful | [
"Changes",
"the",
"scale",
"of",
"values",
"in",
"one",
"distribution",
"to",
"that",
"of",
"another",
"ie",
"The",
"maximum",
"value",
"in",
"fromDataList",
"will",
"be",
"set",
"to",
"the",
"maximum",
"value",
"in",
"toDataList",
".",
"The",
"75%",
"larg... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L265-L301 | train |
timmahrt/ProMo | promo/morph_utils/interpolation.py | quadraticInterpolation | def quadraticInterpolation(valueList2d, numDegrees, n,
startTime=None, endTime=None):
'''
Generates a series of points on a smooth curve that cross the given points
numDegrees - the degrees of the fitted polynomial
- the curve gets weird if this value is too high for the input
n - number of points to output
startTime/endTime/n - n points will be generated at evenly spaced
intervals between startTime and endTime
'''
_numpyCheck()
x, y = zip(*valueList2d)
if startTime is None:
startTime = x[0]
if endTime is None:
endTime = x[-1]
polyFunc = np.poly1d(np.polyfit(x, y, numDegrees))
newX = np.linspace(startTime, endTime, n)
retList = [(n, polyFunc(n)) for n in newX]
return retList | python | def quadraticInterpolation(valueList2d, numDegrees, n,
startTime=None, endTime=None):
'''
Generates a series of points on a smooth curve that cross the given points
numDegrees - the degrees of the fitted polynomial
- the curve gets weird if this value is too high for the input
n - number of points to output
startTime/endTime/n - n points will be generated at evenly spaced
intervals between startTime and endTime
'''
_numpyCheck()
x, y = zip(*valueList2d)
if startTime is None:
startTime = x[0]
if endTime is None:
endTime = x[-1]
polyFunc = np.poly1d(np.polyfit(x, y, numDegrees))
newX = np.linspace(startTime, endTime, n)
retList = [(n, polyFunc(n)) for n in newX]
return retList | [
"def",
"quadraticInterpolation",
"(",
"valueList2d",
",",
"numDegrees",
",",
"n",
",",
"startTime",
"=",
"None",
",",
"endTime",
"=",
"None",
")",
":",
"_numpyCheck",
"(",
")",
"x",
",",
"y",
"=",
"zip",
"(",
"*",
"valueList2d",
")",
"if",
"startTime",
... | Generates a series of points on a smooth curve that cross the given points
numDegrees - the degrees of the fitted polynomial
- the curve gets weird if this value is too high for the input
n - number of points to output
startTime/endTime/n - n points will be generated at evenly spaced
intervals between startTime and endTime | [
"Generates",
"a",
"series",
"of",
"points",
"on",
"a",
"smooth",
"curve",
"that",
"cross",
"the",
"given",
"points",
"numDegrees",
"-",
"the",
"degrees",
"of",
"the",
"fitted",
"polynomial",
"-",
"the",
"curve",
"gets",
"weird",
"if",
"this",
"value",
"is"... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/interpolation.py#L21-L47 | train |
timmahrt/ProMo | promo/morph_utils/utils.py | getIntervals | def getIntervals(fn, tierName, filterFunc=None,
includeUnlabeledRegions=False):
'''
Get information about the 'extract' tier, used by several merge scripts
'''
tg = tgio.openTextgrid(fn)
tier = tg.tierDict[tierName]
if includeUnlabeledRegions is True:
tier = tgio._fillInBlanks(tier)
entryList = tier.entryList
if filterFunc is not None:
entryList = [entry for entry in entryList if filterFunc(entry)]
return entryList | python | def getIntervals(fn, tierName, filterFunc=None,
includeUnlabeledRegions=False):
'''
Get information about the 'extract' tier, used by several merge scripts
'''
tg = tgio.openTextgrid(fn)
tier = tg.tierDict[tierName]
if includeUnlabeledRegions is True:
tier = tgio._fillInBlanks(tier)
entryList = tier.entryList
if filterFunc is not None:
entryList = [entry for entry in entryList if filterFunc(entry)]
return entryList | [
"def",
"getIntervals",
"(",
"fn",
",",
"tierName",
",",
"filterFunc",
"=",
"None",
",",
"includeUnlabeledRegions",
"=",
"False",
")",
":",
"tg",
"=",
"tgio",
".",
"openTextgrid",
"(",
"fn",
")",
"tier",
"=",
"tg",
".",
"tierDict",
"[",
"tierName",
"]",
... | Get information about the 'extract' tier, used by several merge scripts | [
"Get",
"information",
"about",
"the",
"extract",
"tier",
"used",
"by",
"several",
"merge",
"scripts"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/utils.py#L12-L28 | train |
timmahrt/ProMo | promo/duration_morph.py | changeDuration | def changeDuration(fromWavFN, durationParameters, stepList, outputName,
outputMinPitch, outputMaxPitch, praatEXE):
'''
Uses praat to morph duration in one file to duration in another
Praat uses the PSOLA algorithm
'''
rootPath = os.path.split(fromWavFN)[0]
# Prep output directories
outputPath = join(rootPath, "duration_resynthesized_wavs")
utils.makeDir(outputPath)
durationTierPath = join(rootPath, "duration_tiers")
utils.makeDir(durationTierPath)
fromWavDuration = audio_scripts.getSoundFileDuration(fromWavFN)
durationParameters = copy.deepcopy(durationParameters)
# Pad any gaps with values of 1 (no change in duration)
# No need to stretch out any pauses at the beginning
if durationParameters[0][0] != 0:
tmpVar = (0, durationParameters[0][0] - PRAAT_TIME_DIFF, 1)
durationParameters.insert(0, tmpVar)
# Or the end
if durationParameters[-1][1] < fromWavDuration:
durationParameters.append((durationParameters[-1][1] + PRAAT_TIME_DIFF,
fromWavDuration, 1))
# Create the praat script for doing duration manipulation
for stepAmount in stepList:
durationPointList = []
for start, end, ratio in durationParameters:
percentChange = 1 + (ratio - 1) * stepAmount
durationPointList.append((start, percentChange))
durationPointList.append((end, percentChange))
outputPrefix = "%s_%0.3g" % (outputName, stepAmount)
durationTierFN = join(durationTierPath,
"%s.DurationTier" % outputPrefix)
outputWavFN = join(outputPath, "%s.wav" % outputPrefix)
durationTier = dataio.PointObject2D(durationPointList, dataio.DURATION,
0, fromWavDuration)
durationTier.save(durationTierFN)
praat_scripts.resynthesizeDuration(praatEXE,
fromWavFN,
durationTierFN,
outputWavFN,
outputMinPitch, outputMaxPitch) | python | def changeDuration(fromWavFN, durationParameters, stepList, outputName,
outputMinPitch, outputMaxPitch, praatEXE):
'''
Uses praat to morph duration in one file to duration in another
Praat uses the PSOLA algorithm
'''
rootPath = os.path.split(fromWavFN)[0]
# Prep output directories
outputPath = join(rootPath, "duration_resynthesized_wavs")
utils.makeDir(outputPath)
durationTierPath = join(rootPath, "duration_tiers")
utils.makeDir(durationTierPath)
fromWavDuration = audio_scripts.getSoundFileDuration(fromWavFN)
durationParameters = copy.deepcopy(durationParameters)
# Pad any gaps with values of 1 (no change in duration)
# No need to stretch out any pauses at the beginning
if durationParameters[0][0] != 0:
tmpVar = (0, durationParameters[0][0] - PRAAT_TIME_DIFF, 1)
durationParameters.insert(0, tmpVar)
# Or the end
if durationParameters[-1][1] < fromWavDuration:
durationParameters.append((durationParameters[-1][1] + PRAAT_TIME_DIFF,
fromWavDuration, 1))
# Create the praat script for doing duration manipulation
for stepAmount in stepList:
durationPointList = []
for start, end, ratio in durationParameters:
percentChange = 1 + (ratio - 1) * stepAmount
durationPointList.append((start, percentChange))
durationPointList.append((end, percentChange))
outputPrefix = "%s_%0.3g" % (outputName, stepAmount)
durationTierFN = join(durationTierPath,
"%s.DurationTier" % outputPrefix)
outputWavFN = join(outputPath, "%s.wav" % outputPrefix)
durationTier = dataio.PointObject2D(durationPointList, dataio.DURATION,
0, fromWavDuration)
durationTier.save(durationTierFN)
praat_scripts.resynthesizeDuration(praatEXE,
fromWavFN,
durationTierFN,
outputWavFN,
outputMinPitch, outputMaxPitch) | [
"def",
"changeDuration",
"(",
"fromWavFN",
",",
"durationParameters",
",",
"stepList",
",",
"outputName",
",",
"outputMinPitch",
",",
"outputMaxPitch",
",",
"praatEXE",
")",
":",
"rootPath",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fromWavFN",
")",
"[",
"... | Uses praat to morph duration in one file to duration in another
Praat uses the PSOLA algorithm | [
"Uses",
"praat",
"to",
"morph",
"duration",
"in",
"one",
"file",
"to",
"duration",
"in",
"another"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L35-L87 | train |
timmahrt/ProMo | promo/duration_morph.py | getMorphParameters | def getMorphParameters(fromTGFN, toTGFN, tierName,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of toTGFN.
'''
if filterFunc is None:
filterFunc = lambda entry: True # Everything is accepted
fromEntryList = utils.getIntervals(fromTGFN, tierName,
includeUnlabeledRegions=useBlanks)
toEntryList = utils.getIntervals(toTGFN, tierName,
includeUnlabeledRegions=useBlanks)
fromEntryList = [entry for entry in fromEntryList if filterFunc(entry)]
toEntryList = [entry for entry in toEntryList if filterFunc(entry)]
assert(len(fromEntryList) == len(toEntryList))
durationParameters = []
for fromEntry, toEntry in zip(fromEntryList, toEntryList):
fromStart, fromEnd = fromEntry[:2]
toStart, toEnd = toEntry[:2]
# Praat will ignore a second value appearing at the same time as
# another so we give each start a tiny offset to distinguish intervals
# that start and end at the same point
toStart += PRAAT_TIME_DIFF
fromStart += PRAAT_TIME_DIFF
ratio = (toEnd - toStart) / float((fromEnd - fromStart))
durationParameters.append((fromStart, fromEnd, ratio))
return durationParameters | python | def getMorphParameters(fromTGFN, toTGFN, tierName,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of toTGFN.
'''
if filterFunc is None:
filterFunc = lambda entry: True # Everything is accepted
fromEntryList = utils.getIntervals(fromTGFN, tierName,
includeUnlabeledRegions=useBlanks)
toEntryList = utils.getIntervals(toTGFN, tierName,
includeUnlabeledRegions=useBlanks)
fromEntryList = [entry for entry in fromEntryList if filterFunc(entry)]
toEntryList = [entry for entry in toEntryList if filterFunc(entry)]
assert(len(fromEntryList) == len(toEntryList))
durationParameters = []
for fromEntry, toEntry in zip(fromEntryList, toEntryList):
fromStart, fromEnd = fromEntry[:2]
toStart, toEnd = toEntry[:2]
# Praat will ignore a second value appearing at the same time as
# another so we give each start a tiny offset to distinguish intervals
# that start and end at the same point
toStart += PRAAT_TIME_DIFF
fromStart += PRAAT_TIME_DIFF
ratio = (toEnd - toStart) / float((fromEnd - fromStart))
durationParameters.append((fromStart, fromEnd, ratio))
return durationParameters | [
"def",
"getMorphParameters",
"(",
"fromTGFN",
",",
"toTGFN",
",",
"tierName",
",",
"filterFunc",
"=",
"None",
",",
"useBlanks",
"=",
"False",
")",
":",
"if",
"filterFunc",
"is",
"None",
":",
"filterFunc",
"=",
"lambda",
"entry",
":",
"True",
"# Everything is... | Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of toTGFN. | [
"Get",
"intervals",
"for",
"source",
"and",
"target",
"audio",
"files",
"Use",
"this",
"information",
"to",
"find",
"out",
"how",
"much",
"to",
"stretch",
"/",
"shrink",
"each",
"source",
"interval",
".",
"The",
"target",
"values",
"are",
"based",
"on",
"t... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L95-L133 | train |
timmahrt/ProMo | promo/duration_morph.py | getManipulatedParamaters | def getManipulatedParamaters(tgFN, tierName, modFunc,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on modfunc.
'''
fromExtractInfo = utils.getIntervals(tgFN, tierName, filterFunc,
useBlanks)
durationParameters = []
for fromInfoTuple in fromExtractInfo:
fromStart, fromEnd = fromInfoTuple[:2]
toStart, toEnd = modFunc(fromStart), modFunc(fromEnd)
# Praat will ignore a second value appearing at the same time as
# another so we give each start a tiny offset to distinguish intervals
# that start and end at the same point
toStart += PRAAT_TIME_DIFF
fromStart += PRAAT_TIME_DIFF
ratio = (toEnd - toStart) / float((fromEnd - fromStart))
ratioTuple = (fromStart, fromEnd, ratio)
durationParameters.append(ratioTuple)
return durationParameters | python | def getManipulatedParamaters(tgFN, tierName, modFunc,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on modfunc.
'''
fromExtractInfo = utils.getIntervals(tgFN, tierName, filterFunc,
useBlanks)
durationParameters = []
for fromInfoTuple in fromExtractInfo:
fromStart, fromEnd = fromInfoTuple[:2]
toStart, toEnd = modFunc(fromStart), modFunc(fromEnd)
# Praat will ignore a second value appearing at the same time as
# another so we give each start a tiny offset to distinguish intervals
# that start and end at the same point
toStart += PRAAT_TIME_DIFF
fromStart += PRAAT_TIME_DIFF
ratio = (toEnd - toStart) / float((fromEnd - fromStart))
ratioTuple = (fromStart, fromEnd, ratio)
durationParameters.append(ratioTuple)
return durationParameters | [
"def",
"getManipulatedParamaters",
"(",
"tgFN",
",",
"tierName",
",",
"modFunc",
",",
"filterFunc",
"=",
"None",
",",
"useBlanks",
"=",
"False",
")",
":",
"fromExtractInfo",
"=",
"utils",
".",
"getIntervals",
"(",
"tgFN",
",",
"tierName",
",",
"filterFunc",
... | Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on modfunc. | [
"Get",
"intervals",
"for",
"source",
"and",
"target",
"audio",
"files",
"Use",
"this",
"information",
"to",
"find",
"out",
"how",
"much",
"to",
"stretch",
"/",
"shrink",
"each",
"source",
"interval",
".",
"The",
"target",
"values",
"are",
"based",
"on",
"m... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L136-L166 | train |
timmahrt/ProMo | promo/duration_morph.py | textgridMorphDuration | def textgridMorphDuration(fromTGFN, toTGFN):
'''
A convenience function. Morphs interval durations of one tg to another.
This assumes the two textgrids have the same number of segments.
'''
fromTG = tgio.openTextgrid(fromTGFN)
toTG = tgio.openTextgrid(toTGFN)
adjustedTG = tgio.Textgrid()
for tierName in fromTG.tierNameList:
fromTier = fromTG.tierDict[tierName]
toTier = toTG.tierDict[tierName]
adjustedTier = fromTier.morph(toTier)
adjustedTG.addTier(adjustedTier)
return adjustedTG | python | def textgridMorphDuration(fromTGFN, toTGFN):
'''
A convenience function. Morphs interval durations of one tg to another.
This assumes the two textgrids have the same number of segments.
'''
fromTG = tgio.openTextgrid(fromTGFN)
toTG = tgio.openTextgrid(toTGFN)
adjustedTG = tgio.Textgrid()
for tierName in fromTG.tierNameList:
fromTier = fromTG.tierDict[tierName]
toTier = toTG.tierDict[tierName]
adjustedTier = fromTier.morph(toTier)
adjustedTG.addTier(adjustedTier)
return adjustedTG | [
"def",
"textgridMorphDuration",
"(",
"fromTGFN",
",",
"toTGFN",
")",
":",
"fromTG",
"=",
"tgio",
".",
"openTextgrid",
"(",
"fromTGFN",
")",
"toTG",
"=",
"tgio",
".",
"openTextgrid",
"(",
"toTGFN",
")",
"adjustedTG",
"=",
"tgio",
".",
"Textgrid",
"(",
")",
... | A convenience function. Morphs interval durations of one tg to another.
This assumes the two textgrids have the same number of segments. | [
"A",
"convenience",
"function",
".",
"Morphs",
"interval",
"durations",
"of",
"one",
"tg",
"to",
"another",
".",
"This",
"assumes",
"the",
"two",
"textgrids",
"have",
"the",
"same",
"number",
"of",
"segments",
"."
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L244-L260 | train |
timmahrt/ProMo | promo/morph_utils/audio_scripts.py | getSoundFileDuration | def getSoundFileDuration(fn):
'''
Returns the duration of a wav file (in seconds)
'''
audiofile = wave.open(fn, "r")
params = audiofile.getparams()
framerate = params[2]
nframes = params[3]
duration = float(nframes) / framerate
return duration | python | def getSoundFileDuration(fn):
'''
Returns the duration of a wav file (in seconds)
'''
audiofile = wave.open(fn, "r")
params = audiofile.getparams()
framerate = params[2]
nframes = params[3]
duration = float(nframes) / framerate
return duration | [
"def",
"getSoundFileDuration",
"(",
"fn",
")",
":",
"audiofile",
"=",
"wave",
".",
"open",
"(",
"fn",
",",
"\"r\"",
")",
"params",
"=",
"audiofile",
".",
"getparams",
"(",
")",
"framerate",
"=",
"params",
"[",
"2",
"]",
"nframes",
"=",
"params",
"[",
... | Returns the duration of a wav file (in seconds) | [
"Returns",
"the",
"duration",
"of",
"a",
"wav",
"file",
"(",
"in",
"seconds",
")"
] | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/audio_scripts.py#L10-L21 | train |
hermanschaaf/mafan | mafan/text.py | split_text | def split_text(text, include_part_of_speech=False, strip_english=False, strip_numbers=False):
u"""
Split Chinese text at word boundaries.
include_pos: also returns the Part Of Speech for each of the words.
Some of the different parts of speech are:
r: pronoun
v: verb
ns: proper noun
etc...
This all gets returned as a tuple:
index 0: the split word
index 1: the word's part of speech
strip_english: remove all entries that have English or numbers in them (useful sometimes)
"""
if not include_part_of_speech:
seg_list = pseg.cut(text)
if strip_english:
seg_list = filter(lambda x: not contains_english(x), seg_list)
if strip_numbers:
seg_list = filter(lambda x: not _is_number(x), seg_list)
return list(map(lambda i: i.word, seg_list))
else:
seg_list = pseg.cut(text)
objs = map(lambda w: (w.word, w.flag), seg_list)
if strip_english:
objs = filter(lambda x: not contains_english(x[0]), objs)
if strip_english:
objs = filter(lambda x: not _is_number(x[0]), objs)
return objs
# if was_traditional:
# seg_list = map(tradify, seg_list)
return list(seg_list) | python | def split_text(text, include_part_of_speech=False, strip_english=False, strip_numbers=False):
u"""
Split Chinese text at word boundaries.
include_pos: also returns the Part Of Speech for each of the words.
Some of the different parts of speech are:
r: pronoun
v: verb
ns: proper noun
etc...
This all gets returned as a tuple:
index 0: the split word
index 1: the word's part of speech
strip_english: remove all entries that have English or numbers in them (useful sometimes)
"""
if not include_part_of_speech:
seg_list = pseg.cut(text)
if strip_english:
seg_list = filter(lambda x: not contains_english(x), seg_list)
if strip_numbers:
seg_list = filter(lambda x: not _is_number(x), seg_list)
return list(map(lambda i: i.word, seg_list))
else:
seg_list = pseg.cut(text)
objs = map(lambda w: (w.word, w.flag), seg_list)
if strip_english:
objs = filter(lambda x: not contains_english(x[0]), objs)
if strip_english:
objs = filter(lambda x: not _is_number(x[0]), objs)
return objs
# if was_traditional:
# seg_list = map(tradify, seg_list)
return list(seg_list) | [
"def",
"split_text",
"(",
"text",
",",
"include_part_of_speech",
"=",
"False",
",",
"strip_english",
"=",
"False",
",",
"strip_numbers",
"=",
"False",
")",
":",
"if",
"not",
"include_part_of_speech",
":",
"seg_list",
"=",
"pseg",
".",
"cut",
"(",
"text",
")"... | u"""
Split Chinese text at word boundaries.
include_pos: also returns the Part Of Speech for each of the words.
Some of the different parts of speech are:
r: pronoun
v: verb
ns: proper noun
etc...
This all gets returned as a tuple:
index 0: the split word
index 1: the word's part of speech
strip_english: remove all entries that have English or numbers in them (useful sometimes) | [
"u",
"Split",
"Chinese",
"text",
"at",
"word",
"boundaries",
"."
] | 373ddf299aeb2bd8413bf921c71768af7a8170ea | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/text.py#L209-L246 | train |
ericpruitt/cronex | cronex/__init__.py | is_special_atom | def is_special_atom(cron_atom, span):
"""
Returns a boolean indicating whether or not the string can be parsed by
parse_atom to produce a static set. In the process of examining the
string, the syntax of any special character uses is also checked.
"""
for special_char in ('%', '#', 'L', 'W'):
if special_char not in cron_atom:
continue
if special_char == '#':
if span != DAYS_OF_WEEK:
raise ValueError("\"#\" invalid where used.")
elif not VALIDATE_POUND.match(cron_atom):
raise ValueError("\"#\" syntax incorrect.")
elif special_char == "W":
if span != DAYS_OF_MONTH:
raise ValueError("\"W\" syntax incorrect.")
elif not(VALIDATE_W.match(cron_atom) and int(cron_atom[:-1]) > 0):
raise ValueError("Invalid use of \"W\".")
elif special_char == "L":
if span not in L_FIELDS:
raise ValueError("\"L\" invalid where used.")
elif span == DAYS_OF_MONTH:
if cron_atom != "L":
raise ValueError("\"L\" must be alone in days of month.")
elif span == DAYS_OF_WEEK:
if not VALIDATE_L_IN_DOW.match(cron_atom):
raise ValueError("\"L\" syntax incorrect.")
elif special_char == "%":
if not(cron_atom[1:].isdigit() and int(cron_atom[1:]) > 1):
raise ValueError("\"%\" syntax incorrect.")
return True
else:
return False | python | def is_special_atom(cron_atom, span):
"""
Returns a boolean indicating whether or not the string can be parsed by
parse_atom to produce a static set. In the process of examining the
string, the syntax of any special character uses is also checked.
"""
for special_char in ('%', '#', 'L', 'W'):
if special_char not in cron_atom:
continue
if special_char == '#':
if span != DAYS_OF_WEEK:
raise ValueError("\"#\" invalid where used.")
elif not VALIDATE_POUND.match(cron_atom):
raise ValueError("\"#\" syntax incorrect.")
elif special_char == "W":
if span != DAYS_OF_MONTH:
raise ValueError("\"W\" syntax incorrect.")
elif not(VALIDATE_W.match(cron_atom) and int(cron_atom[:-1]) > 0):
raise ValueError("Invalid use of \"W\".")
elif special_char == "L":
if span not in L_FIELDS:
raise ValueError("\"L\" invalid where used.")
elif span == DAYS_OF_MONTH:
if cron_atom != "L":
raise ValueError("\"L\" must be alone in days of month.")
elif span == DAYS_OF_WEEK:
if not VALIDATE_L_IN_DOW.match(cron_atom):
raise ValueError("\"L\" syntax incorrect.")
elif special_char == "%":
if not(cron_atom[1:].isdigit() and int(cron_atom[1:]) > 1):
raise ValueError("\"%\" syntax incorrect.")
return True
else:
return False | [
"def",
"is_special_atom",
"(",
"cron_atom",
",",
"span",
")",
":",
"for",
"special_char",
"in",
"(",
"'%'",
",",
"'#'",
",",
"'L'",
",",
"'W'",
")",
":",
"if",
"special_char",
"not",
"in",
"cron_atom",
":",
"continue",
"if",
"special_char",
"==",
"'#'",
... | Returns a boolean indicating whether or not the string can be parsed by
parse_atom to produce a static set. In the process of examining the
string, the syntax of any special character uses is also checked. | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"string",
"can",
"be",
"parsed",
"by",
"parse_atom",
"to",
"produce",
"a",
"static",
"set",
".",
"In",
"the",
"process",
"of",
"examining",
"the",
"string",
"the",
"syntax",
"of",
"any... | ff48a3a71bbcdf01cff46c0bf9376e69492c9224 | https://github.com/ericpruitt/cronex/blob/ff48a3a71bbcdf01cff46c0bf9376e69492c9224/cronex/__init__.py#L264-L298 | train |
ericpruitt/cronex | cronex/__init__.py | parse_atom | def parse_atom(parse, minmax):
"""
Returns a set containing valid values for a given cron-style range of
numbers. The 'minmax' arguments is a two element iterable containing the
inclusive upper and lower limits of the expression.
Examples:
>>> parse_atom("1-5",(0,6))
set([1, 2, 3, 4, 5])
>>> parse_atom("*/6",(0,23))
set([0, 6, 12, 18])
>>> parse_atom("18-6/4",(0,23))
set([18, 22, 0, 4])
>>> parse_atom("*/9",(0,23))
set([0, 9, 18])
"""
parse = parse.strip()
increment = 1
if parse == '*':
return set(xrange(minmax[0], minmax[1] + 1))
elif parse.isdigit():
# A single number still needs to be returned as a set
value = int(parse)
if value >= minmax[0] and value <= minmax[1]:
return set((value,))
else:
raise ValueError("\"%s\" is not within valid range." % parse)
elif '-' in parse or '/' in parse:
divide = parse.split('/')
subrange = divide[0]
if len(divide) == 2:
# Example: 1-3/5 or */7 increment should be 5 and 7 respectively
increment = int(divide[1])
if '-' in subrange:
# Example: a-b
prefix, suffix = [int(n) for n in subrange.split('-')]
if prefix < minmax[0] or suffix > minmax[1]:
raise ValueError("\"%s\" is not within valid range." % parse)
elif subrange.isdigit():
# Handle offset increments e.g. 5/15 to run at :05, :20, :35, and :50
return set(xrange(int(subrange), minmax[1] + 1, increment))
elif subrange == '*':
# Include all values with the given range
prefix, suffix = minmax
else:
raise ValueError("Unrecognized symbol \"%s\"" % subrange)
if prefix < suffix:
# Example: 7-10
return set(xrange(prefix, suffix + 1, increment))
else:
# Example: 12-4/2; (12, 12 + n, ..., 12 + m*n) U (n_0, ..., 4)
noskips = list(xrange(prefix, minmax[1] + 1))
noskips += list(xrange(minmax[0], suffix + 1))
return set(noskips[::increment])
else:
raise ValueError("Atom \"%s\" not in a recognized format." % parse) | python | def parse_atom(parse, minmax):
"""
Returns a set containing valid values for a given cron-style range of
numbers. The 'minmax' arguments is a two element iterable containing the
inclusive upper and lower limits of the expression.
Examples:
>>> parse_atom("1-5",(0,6))
set([1, 2, 3, 4, 5])
>>> parse_atom("*/6",(0,23))
set([0, 6, 12, 18])
>>> parse_atom("18-6/4",(0,23))
set([18, 22, 0, 4])
>>> parse_atom("*/9",(0,23))
set([0, 9, 18])
"""
parse = parse.strip()
increment = 1
if parse == '*':
return set(xrange(minmax[0], minmax[1] + 1))
elif parse.isdigit():
# A single number still needs to be returned as a set
value = int(parse)
if value >= minmax[0] and value <= minmax[1]:
return set((value,))
else:
raise ValueError("\"%s\" is not within valid range." % parse)
elif '-' in parse or '/' in parse:
divide = parse.split('/')
subrange = divide[0]
if len(divide) == 2:
# Example: 1-3/5 or */7 increment should be 5 and 7 respectively
increment = int(divide[1])
if '-' in subrange:
# Example: a-b
prefix, suffix = [int(n) for n in subrange.split('-')]
if prefix < minmax[0] or suffix > minmax[1]:
raise ValueError("\"%s\" is not within valid range." % parse)
elif subrange.isdigit():
# Handle offset increments e.g. 5/15 to run at :05, :20, :35, and :50
return set(xrange(int(subrange), minmax[1] + 1, increment))
elif subrange == '*':
# Include all values with the given range
prefix, suffix = minmax
else:
raise ValueError("Unrecognized symbol \"%s\"" % subrange)
if prefix < suffix:
# Example: 7-10
return set(xrange(prefix, suffix + 1, increment))
else:
# Example: 12-4/2; (12, 12 + n, ..., 12 + m*n) U (n_0, ..., 4)
noskips = list(xrange(prefix, minmax[1] + 1))
noskips += list(xrange(minmax[0], suffix + 1))
return set(noskips[::increment])
else:
raise ValueError("Atom \"%s\" not in a recognized format." % parse) | [
"def",
"parse_atom",
"(",
"parse",
",",
"minmax",
")",
":",
"parse",
"=",
"parse",
".",
"strip",
"(",
")",
"increment",
"=",
"1",
"if",
"parse",
"==",
"'*'",
":",
"return",
"set",
"(",
"xrange",
"(",
"minmax",
"[",
"0",
"]",
",",
"minmax",
"[",
"... | Returns a set containing valid values for a given cron-style range of
numbers. The 'minmax' arguments is a two element iterable containing the
inclusive upper and lower limits of the expression.
Examples:
>>> parse_atom("1-5",(0,6))
set([1, 2, 3, 4, 5])
>>> parse_atom("*/6",(0,23))
set([0, 6, 12, 18])
>>> parse_atom("18-6/4",(0,23))
set([18, 22, 0, 4])
>>> parse_atom("*/9",(0,23))
set([0, 9, 18]) | [
"Returns",
"a",
"set",
"containing",
"valid",
"values",
"for",
"a",
"given",
"cron",
"-",
"style",
"range",
"of",
"numbers",
".",
"The",
"minmax",
"arguments",
"is",
"a",
"two",
"element",
"iterable",
"containing",
"the",
"inclusive",
"upper",
"and",
"lower"... | ff48a3a71bbcdf01cff46c0bf9376e69492c9224 | https://github.com/ericpruitt/cronex/blob/ff48a3a71bbcdf01cff46c0bf9376e69492c9224/cronex/__init__.py#L302-L362 | train |
ericpruitt/cronex | cronex/__init__.py | CronExpression.compute_numtab | def compute_numtab(self):
"""
Recomputes the sets for the static ranges of the trigger time.
This method should only be called by the user if the string_tab
member is modified.
"""
self.numerical_tab = []
for field_str, span in zip(self.string_tab, FIELD_RANGES):
split_field_str = field_str.split(',')
if len(split_field_str) > 1 and "*" in split_field_str:
raise ValueError("\"*\" must be alone in a field.")
unified = set()
for cron_atom in split_field_str:
# parse_atom only handles static cases
if not(is_special_atom(cron_atom, span)):
unified.update(parse_atom(cron_atom, span))
self.numerical_tab.append(unified)
if self.string_tab[2] == "*" and self.string_tab[4] != "*":
self.numerical_tab[2] = set()
elif self.string_tab[4] == "*" and self.string_tab[2] != "*":
self.numerical_tab[4] = set() | python | def compute_numtab(self):
"""
Recomputes the sets for the static ranges of the trigger time.
This method should only be called by the user if the string_tab
member is modified.
"""
self.numerical_tab = []
for field_str, span in zip(self.string_tab, FIELD_RANGES):
split_field_str = field_str.split(',')
if len(split_field_str) > 1 and "*" in split_field_str:
raise ValueError("\"*\" must be alone in a field.")
unified = set()
for cron_atom in split_field_str:
# parse_atom only handles static cases
if not(is_special_atom(cron_atom, span)):
unified.update(parse_atom(cron_atom, span))
self.numerical_tab.append(unified)
if self.string_tab[2] == "*" and self.string_tab[4] != "*":
self.numerical_tab[2] = set()
elif self.string_tab[4] == "*" and self.string_tab[2] != "*":
self.numerical_tab[4] = set() | [
"def",
"compute_numtab",
"(",
"self",
")",
":",
"self",
".",
"numerical_tab",
"=",
"[",
"]",
"for",
"field_str",
",",
"span",
"in",
"zip",
"(",
"self",
".",
"string_tab",
",",
"FIELD_RANGES",
")",
":",
"split_field_str",
"=",
"field_str",
".",
"split",
"... | Recomputes the sets for the static ranges of the trigger time.
This method should only be called by the user if the string_tab
member is modified. | [
"Recomputes",
"the",
"sets",
"for",
"the",
"static",
"ranges",
"of",
"the",
"trigger",
"time",
"."
] | ff48a3a71bbcdf01cff46c0bf9376e69492c9224 | https://github.com/ericpruitt/cronex/blob/ff48a3a71bbcdf01cff46c0bf9376e69492c9224/cronex/__init__.py#L129-L154 | train |
ericpruitt/cronex | cronex/__init__.py | CronExpression.check_trigger | def check_trigger(self, date_tuple, utc_offset=0):
"""
Returns boolean indicating if the trigger is active at the given time.
The date tuple should be in the local time. Unless periodicities are
used, utc_offset does not need to be specified. If periodicities are
used, specifically in the hour and minutes fields, it is crucial that
the utc_offset is specified.
"""
year, month, day, hour, mins = date_tuple
given_date = datetime.date(year, month, day)
zeroday = datetime.date(*self.epoch[:3])
last_dom = calendar.monthrange(year, month)[-1]
dom_matched = True
# In calendar and datetime.date.weekday, Monday = 0
given_dow = (datetime.date.weekday(given_date) + 1) % 7
first_dow = (given_dow + 1 - day) % 7
# Figure out how much time has passed from the epoch to the given date
utc_diff = utc_offset - self.epoch[5]
mod_delta_yrs = year - self.epoch[0]
mod_delta_mon = month - self.epoch[1] + mod_delta_yrs * 12
mod_delta_day = (given_date - zeroday).days
mod_delta_hrs = hour - self.epoch[3] + mod_delta_day * 24 + utc_diff
mod_delta_min = mins - self.epoch[4] + mod_delta_hrs * 60
# Makes iterating through like components easier.
quintuple = zip(
(mins, hour, day, month, given_dow),
self.numerical_tab,
self.string_tab,
(mod_delta_min, mod_delta_hrs, mod_delta_day, mod_delta_mon,
mod_delta_day),
FIELD_RANGES)
for value, valid_values, field_str, delta_t, field_type in quintuple:
# All valid, static values for the fields are stored in sets
if value in valid_values:
continue
# The following for loop implements the logic for context
# sensitive and epoch sensitive constraints. break statements,
# which are executed when a match is found, lead to a continue
# in the outer loop. If there are no matches found, the given date
# does not match expression constraints, so the function returns
# False as seen at the end of this for...else... construct.
for cron_atom in field_str.split(','):
if cron_atom[0] == '%':
if not(delta_t % int(cron_atom[1:])):
break
elif '#' in cron_atom:
D, N = int(cron_atom[0]), int(cron_atom[2])
# Computes Nth occurence of D day of the week
if (((D - first_dow) % 7) + 1 + 7 * (N - 1)) == day:
break
elif cron_atom[-1] == 'W':
target = min(int(cron_atom[:-1]), last_dom)
lands_on = (first_dow + target - 1) % 7
if lands_on == 0:
# Shift from Sun. to Mon. unless Mon. is next month
if target < last_dom:
target += 1
else:
target -= 2
elif lands_on == 6:
# Shift from Sat. to Fri. unless Fri. in prior month
if target > 1:
target -= 1
else:
target += 2
# Break if the day is correct, and target is a weekday
if target == day and (first_dow + target) % 7 > 1:
break
elif cron_atom[-1] == 'L':
# In dom field, L means the last day of the month
target = last_dom
if field_type == DAYS_OF_WEEK:
# Calculates the last occurence of given day of week
desired_dow = int(cron_atom[:-1])
target = (((desired_dow - first_dow) % 7) + 29)
if target > last_dom:
target -= 7
if target == day:
break
else:
# See 2010.11.15 of CHANGELOG
if field_type == DAYS_OF_MONTH and self.string_tab[4] != '*':
dom_matched = False
continue
elif field_type == DAYS_OF_WEEK and self.string_tab[2] != '*':
# If we got here, then days of months validated so it does
# not matter that days of the week failed.
return dom_matched
# None of the expressions matched which means this field fails
return False
# Arriving at this point means the date landed within the constraints
# of all fields; the associated trigger should be fired.
return True | python | def check_trigger(self, date_tuple, utc_offset=0):
"""
Returns boolean indicating if the trigger is active at the given time.
The date tuple should be in the local time. Unless periodicities are
used, utc_offset does not need to be specified. If periodicities are
used, specifically in the hour and minutes fields, it is crucial that
the utc_offset is specified.
"""
year, month, day, hour, mins = date_tuple
given_date = datetime.date(year, month, day)
zeroday = datetime.date(*self.epoch[:3])
last_dom = calendar.monthrange(year, month)[-1]
dom_matched = True
# In calendar and datetime.date.weekday, Monday = 0
given_dow = (datetime.date.weekday(given_date) + 1) % 7
first_dow = (given_dow + 1 - day) % 7
# Figure out how much time has passed from the epoch to the given date
utc_diff = utc_offset - self.epoch[5]
mod_delta_yrs = year - self.epoch[0]
mod_delta_mon = month - self.epoch[1] + mod_delta_yrs * 12
mod_delta_day = (given_date - zeroday).days
mod_delta_hrs = hour - self.epoch[3] + mod_delta_day * 24 + utc_diff
mod_delta_min = mins - self.epoch[4] + mod_delta_hrs * 60
# Makes iterating through like components easier.
quintuple = zip(
(mins, hour, day, month, given_dow),
self.numerical_tab,
self.string_tab,
(mod_delta_min, mod_delta_hrs, mod_delta_day, mod_delta_mon,
mod_delta_day),
FIELD_RANGES)
for value, valid_values, field_str, delta_t, field_type in quintuple:
# All valid, static values for the fields are stored in sets
if value in valid_values:
continue
# The following for loop implements the logic for context
# sensitive and epoch sensitive constraints. break statements,
# which are executed when a match is found, lead to a continue
# in the outer loop. If there are no matches found, the given date
# does not match expression constraints, so the function returns
# False as seen at the end of this for...else... construct.
for cron_atom in field_str.split(','):
if cron_atom[0] == '%':
if not(delta_t % int(cron_atom[1:])):
break
elif '#' in cron_atom:
D, N = int(cron_atom[0]), int(cron_atom[2])
# Computes Nth occurence of D day of the week
if (((D - first_dow) % 7) + 1 + 7 * (N - 1)) == day:
break
elif cron_atom[-1] == 'W':
target = min(int(cron_atom[:-1]), last_dom)
lands_on = (first_dow + target - 1) % 7
if lands_on == 0:
# Shift from Sun. to Mon. unless Mon. is next month
if target < last_dom:
target += 1
else:
target -= 2
elif lands_on == 6:
# Shift from Sat. to Fri. unless Fri. in prior month
if target > 1:
target -= 1
else:
target += 2
# Break if the day is correct, and target is a weekday
if target == day and (first_dow + target) % 7 > 1:
break
elif cron_atom[-1] == 'L':
# In dom field, L means the last day of the month
target = last_dom
if field_type == DAYS_OF_WEEK:
# Calculates the last occurence of given day of week
desired_dow = int(cron_atom[:-1])
target = (((desired_dow - first_dow) % 7) + 29)
if target > last_dom:
target -= 7
if target == day:
break
else:
# See 2010.11.15 of CHANGELOG
if field_type == DAYS_OF_MONTH and self.string_tab[4] != '*':
dom_matched = False
continue
elif field_type == DAYS_OF_WEEK and self.string_tab[2] != '*':
# If we got here, then days of months validated so it does
# not matter that days of the week failed.
return dom_matched
# None of the expressions matched which means this field fails
return False
# Arriving at this point means the date landed within the constraints
# of all fields; the associated trigger should be fired.
return True | [
"def",
"check_trigger",
"(",
"self",
",",
"date_tuple",
",",
"utc_offset",
"=",
"0",
")",
":",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"mins",
"=",
"date_tuple",
"given_date",
"=",
"datetime",
".",
"date",
"(",
"year",
",",
"month",
",",
... | Returns boolean indicating if the trigger is active at the given time.
The date tuple should be in the local time. Unless periodicities are
used, utc_offset does not need to be specified. If periodicities are
used, specifically in the hour and minutes fields, it is crucial that
the utc_offset is specified. | [
"Returns",
"boolean",
"indicating",
"if",
"the",
"trigger",
"is",
"active",
"at",
"the",
"given",
"time",
".",
"The",
"date",
"tuple",
"should",
"be",
"in",
"the",
"local",
"time",
".",
"Unless",
"periodicities",
"are",
"used",
"utc_offset",
"does",
"not",
... | ff48a3a71bbcdf01cff46c0bf9376e69492c9224 | https://github.com/ericpruitt/cronex/blob/ff48a3a71bbcdf01cff46c0bf9376e69492c9224/cronex/__init__.py#L156-L261 | train |
hustlzp/permission | permission/permission.py | Rule.show | def show(self):
"""Show the structure of self.rules_list, only for debug."""
for rule in self.rules_list:
result = ", ".join([str(check) for check, deny in rule])
print(result) | python | def show(self):
"""Show the structure of self.rules_list, only for debug."""
for rule in self.rules_list:
result = ", ".join([str(check) for check, deny in rule])
print(result) | [
"def",
"show",
"(",
"self",
")",
":",
"for",
"rule",
"in",
"self",
".",
"rules_list",
":",
"result",
"=",
"\", \"",
".",
"join",
"(",
"[",
"str",
"(",
"check",
")",
"for",
"check",
",",
"deny",
"in",
"rule",
"]",
")",
"print",
"(",
"result",
")"
... | Show the structure of self.rules_list, only for debug. | [
"Show",
"the",
"structure",
"of",
"self",
".",
"rules_list",
"only",
"for",
"debug",
"."
] | 302a02a775c4cd53f7588ff9c4ce1ca49a0d40bf | https://github.com/hustlzp/permission/blob/302a02a775c4cd53f7588ff9c4ce1ca49a0d40bf/permission/permission.py#L88-L92 | train |
hustlzp/permission | permission/permission.py | Rule.run | def run(self):
"""Run self.rules_list.
Return True if one rule channel has been passed.
Otherwise return False and the deny() method of the last failed rule.
"""
failed_result = None
for rule in self.rules_list:
for check, deny in rule:
if not check():
failed_result = (False, deny)
break
else:
return (True, None)
return failed_result | python | def run(self):
"""Run self.rules_list.
Return True if one rule channel has been passed.
Otherwise return False and the deny() method of the last failed rule.
"""
failed_result = None
for rule in self.rules_list:
for check, deny in rule:
if not check():
failed_result = (False, deny)
break
else:
return (True, None)
return failed_result | [
"def",
"run",
"(",
"self",
")",
":",
"failed_result",
"=",
"None",
"for",
"rule",
"in",
"self",
".",
"rules_list",
":",
"for",
"check",
",",
"deny",
"in",
"rule",
":",
"if",
"not",
"check",
"(",
")",
":",
"failed_result",
"=",
"(",
"False",
",",
"d... | Run self.rules_list.
Return True if one rule channel has been passed.
Otherwise return False and the deny() method of the last failed rule. | [
"Run",
"self",
".",
"rules_list",
"."
] | 302a02a775c4cd53f7588ff9c4ce1ca49a0d40bf | https://github.com/hustlzp/permission/blob/302a02a775c4cd53f7588ff9c4ce1ca49a0d40bf/permission/permission.py#L98-L112 | train |
kbr/fritzconnection | fritzconnection/fritzmonitor.py | MeterRectangle.set_fraction | def set_fraction(self, value):
"""Set the meter indicator. Value should be between 0 and 1."""
if value < 0:
value *= -1
value = min(value, 1)
if self.horizontal:
width = int(self.width * value)
height = self.height
else:
width = self.width
height = int(self.height * value)
self.canvas.coords(self.meter, self.xpos, self.ypos,
self.xpos + width, self.ypos + height) | python | def set_fraction(self, value):
"""Set the meter indicator. Value should be between 0 and 1."""
if value < 0:
value *= -1
value = min(value, 1)
if self.horizontal:
width = int(self.width * value)
height = self.height
else:
width = self.width
height = int(self.height * value)
self.canvas.coords(self.meter, self.xpos, self.ypos,
self.xpos + width, self.ypos + height) | [
"def",
"set_fraction",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"value",
"*=",
"-",
"1",
"value",
"=",
"min",
"(",
"value",
",",
"1",
")",
"if",
"self",
".",
"horizontal",
":",
"width",
"=",
"int",
"(",
"self",
".",
"w... | Set the meter indicator. Value should be between 0 and 1. | [
"Set",
"the",
"meter",
"indicator",
".",
"Value",
"should",
"be",
"between",
"0",
"and",
"1",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzmonitor.py#L58-L70 | train |
kbr/fritzconnection | fritzconnection/fritzmonitor.py | FritzMonitor.update_status | def update_status(self):
"""Update status informations in tkinter window."""
try:
# all this may fail if the connection to the fritzbox is down
self.update_connection_status()
self.max_stream_rate.set(self.get_stream_rate_str())
self.ip.set(self.status.external_ip)
self.uptime.set(self.status.str_uptime)
upstream, downstream = self.status.transmission_rate
except IOError:
# here we inform the user about being unable to
# update the status informations
pass
else:
# max_downstream and max_upstream may be zero if the
# fritzbox is configured as ip-client.
if self.max_downstream > 0:
self.in_meter.set_fraction(
1.0 * downstream / self.max_downstream)
if self.max_upstream > 0:
self.out_meter.set_fraction(1.0 * upstream / self.max_upstream)
self.update_traffic_info()
self.after(1000, self.update_status) | python | def update_status(self):
"""Update status informations in tkinter window."""
try:
# all this may fail if the connection to the fritzbox is down
self.update_connection_status()
self.max_stream_rate.set(self.get_stream_rate_str())
self.ip.set(self.status.external_ip)
self.uptime.set(self.status.str_uptime)
upstream, downstream = self.status.transmission_rate
except IOError:
# here we inform the user about being unable to
# update the status informations
pass
else:
# max_downstream and max_upstream may be zero if the
# fritzbox is configured as ip-client.
if self.max_downstream > 0:
self.in_meter.set_fraction(
1.0 * downstream / self.max_downstream)
if self.max_upstream > 0:
self.out_meter.set_fraction(1.0 * upstream / self.max_upstream)
self.update_traffic_info()
self.after(1000, self.update_status) | [
"def",
"update_status",
"(",
"self",
")",
":",
"try",
":",
"# all this may fail if the connection to the fritzbox is down",
"self",
".",
"update_connection_status",
"(",
")",
"self",
".",
"max_stream_rate",
".",
"set",
"(",
"self",
".",
"get_stream_rate_str",
"(",
")"... | Update status informations in tkinter window. | [
"Update",
"status",
"informations",
"in",
"tkinter",
"window",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzmonitor.py#L112-L134 | train |
kbr/fritzconnection | fritzconnection/fritztools.py | format_num | def format_num(num, unit='bytes'):
"""
Returns a human readable string of a byte-value.
If 'num' is bits, set unit='bits'.
"""
if unit == 'bytes':
extension = 'B'
else:
# if it's not bytes, it's bits
extension = 'Bit'
for dimension in (unit, 'K', 'M', 'G', 'T'):
if num < 1024:
if dimension == unit:
return '%3.1f %s' % (num, dimension)
return '%3.1f %s%s' % (num, dimension, extension)
num /= 1024
return '%3.1f P%s' % (num, extension) | python | def format_num(num, unit='bytes'):
"""
Returns a human readable string of a byte-value.
If 'num' is bits, set unit='bits'.
"""
if unit == 'bytes':
extension = 'B'
else:
# if it's not bytes, it's bits
extension = 'Bit'
for dimension in (unit, 'K', 'M', 'G', 'T'):
if num < 1024:
if dimension == unit:
return '%3.1f %s' % (num, dimension)
return '%3.1f %s%s' % (num, dimension, extension)
num /= 1024
return '%3.1f P%s' % (num, extension) | [
"def",
"format_num",
"(",
"num",
",",
"unit",
"=",
"'bytes'",
")",
":",
"if",
"unit",
"==",
"'bytes'",
":",
"extension",
"=",
"'B'",
"else",
":",
"# if it's not bytes, it's bits",
"extension",
"=",
"'Bit'",
"for",
"dimension",
"in",
"(",
"unit",
",",
"'K'"... | Returns a human readable string of a byte-value.
If 'num' is bits, set unit='bits'. | [
"Returns",
"a",
"human",
"readable",
"string",
"of",
"a",
"byte",
"-",
"value",
".",
"If",
"num",
"is",
"bits",
"set",
"unit",
"=",
"bits",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritztools.py#L9-L25 | train |
g2p/rfc6266 | rfc6266.py | parse_headers | def parse_headers(content_disposition, location=None, relaxed=False):
"""Build a ContentDisposition from header values.
"""
LOGGER.debug(
'Content-Disposition %r, Location %r', content_disposition, location)
if content_disposition is None:
return ContentDisposition(location=location)
# Both alternatives seem valid.
if False:
# Require content_disposition to be ascii bytes (0-127),
# or characters in the ascii range
content_disposition = ensure_charset(content_disposition, 'ascii')
else:
# We allow non-ascii here (it will only be parsed inside of
# qdtext, and rejected by the grammar if it appears in
# other places), although parsing it can be ambiguous.
# Parsing it ensures that a non-ambiguous filename* value
# won't get dismissed because of an unrelated ambiguity
# in the filename parameter. But it does mean we occasionally
# give less-than-certain values for some legacy senders.
content_disposition = ensure_charset(content_disposition, 'iso-8859-1')
# Check the caller already did LWS-folding (normally done
# when separating header names and values; RFC 2616 section 2.2
# says it should be done before interpretation at any rate).
# Hopefully space still means what it should in iso-8859-1.
# This check is a bit stronger that LWS folding, it will
# remove CR and LF even if they aren't part of a CRLF.
# However http doesn't allow isolated CR and LF in headers outside
# of LWS.
if relaxed:
# Relaxed has two effects (so far):
# the grammar allows a final ';' in the header;
# we do LWS-folding, and possibly normalise other broken
# whitespace, instead of rejecting non-lws-safe text.
# XXX Would prefer to accept only the quoted whitespace
# case, rather than normalising everything.
content_disposition = normalize_ws(content_disposition)
parser = content_disposition_value_relaxed
else:
# Turns out this is occasionally broken: two spaces inside
# a quoted_string's qdtext. Firefox and Chrome save the two spaces.
if not is_lws_safe(content_disposition):
raise ValueError(
content_disposition, 'Contains nonstandard whitespace')
parser = content_disposition_value
try:
parsed = parser.parse(content_disposition)
except FullFirstMatchException:
return ContentDisposition(location=location)
return ContentDisposition(
disposition=parsed[0], assocs=parsed[1:], location=location) | python | def parse_headers(content_disposition, location=None, relaxed=False):
"""Build a ContentDisposition from header values.
"""
LOGGER.debug(
'Content-Disposition %r, Location %r', content_disposition, location)
if content_disposition is None:
return ContentDisposition(location=location)
# Both alternatives seem valid.
if False:
# Require content_disposition to be ascii bytes (0-127),
# or characters in the ascii range
content_disposition = ensure_charset(content_disposition, 'ascii')
else:
# We allow non-ascii here (it will only be parsed inside of
# qdtext, and rejected by the grammar if it appears in
# other places), although parsing it can be ambiguous.
# Parsing it ensures that a non-ambiguous filename* value
# won't get dismissed because of an unrelated ambiguity
# in the filename parameter. But it does mean we occasionally
# give less-than-certain values for some legacy senders.
content_disposition = ensure_charset(content_disposition, 'iso-8859-1')
# Check the caller already did LWS-folding (normally done
# when separating header names and values; RFC 2616 section 2.2
# says it should be done before interpretation at any rate).
# Hopefully space still means what it should in iso-8859-1.
# This check is a bit stronger that LWS folding, it will
# remove CR and LF even if they aren't part of a CRLF.
# However http doesn't allow isolated CR and LF in headers outside
# of LWS.
if relaxed:
# Relaxed has two effects (so far):
# the grammar allows a final ';' in the header;
# we do LWS-folding, and possibly normalise other broken
# whitespace, instead of rejecting non-lws-safe text.
# XXX Would prefer to accept only the quoted whitespace
# case, rather than normalising everything.
content_disposition = normalize_ws(content_disposition)
parser = content_disposition_value_relaxed
else:
# Turns out this is occasionally broken: two spaces inside
# a quoted_string's qdtext. Firefox and Chrome save the two spaces.
if not is_lws_safe(content_disposition):
raise ValueError(
content_disposition, 'Contains nonstandard whitespace')
parser = content_disposition_value
try:
parsed = parser.parse(content_disposition)
except FullFirstMatchException:
return ContentDisposition(location=location)
return ContentDisposition(
disposition=parsed[0], assocs=parsed[1:], location=location) | [
"def",
"parse_headers",
"(",
"content_disposition",
",",
"location",
"=",
"None",
",",
"relaxed",
"=",
"False",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Content-Disposition %r, Location %r'",
",",
"content_disposition",
",",
"location",
")",
"if",
"content_dispositi... | Build a ContentDisposition from header values. | [
"Build",
"a",
"ContentDisposition",
"from",
"header",
"values",
"."
] | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L175-L232 | train |
g2p/rfc6266 | rfc6266.py | parse_requests_response | def parse_requests_response(response, **kwargs):
"""Build a ContentDisposition from a requests (PyPI) response.
"""
return parse_headers(
response.headers.get('content-disposition'), response.url, **kwargs) | python | def parse_requests_response(response, **kwargs):
"""Build a ContentDisposition from a requests (PyPI) response.
"""
return parse_headers(
response.headers.get('content-disposition'), response.url, **kwargs) | [
"def",
"parse_requests_response",
"(",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"parse_headers",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'content-disposition'",
")",
",",
"response",
".",
"url",
",",
"*",
"*",
"kwargs",
")"
] | Build a ContentDisposition from a requests (PyPI) response. | [
"Build",
"a",
"ContentDisposition",
"from",
"a",
"requests",
"(",
"PyPI",
")",
"response",
"."
] | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L244-L249 | train |
g2p/rfc6266 | rfc6266.py | build_header | def build_header(
filename, disposition='attachment', filename_compat=None
):
"""Generate a Content-Disposition header for a given filename.
For legacy clients that don't understand the filename* parameter,
a filename_compat value may be given.
It should either be ascii-only (recommended) or iso-8859-1 only.
In the later case it should be a character string
(unicode in Python 2).
Options for generating filename_compat (only useful for legacy clients):
- ignore (will only send filename*);
- strip accents using unicode's decomposing normalisations,
which can be done from unicode data (stdlib), and keep only ascii;
- use the ascii transliteration tables from Unidecode (PyPI);
- use iso-8859-1
Ignore is the safest, and can be used to trigger a fallback
to the document location (which can be percent-encoded utf-8
if you control the URLs).
See https://tools.ietf.org/html/rfc6266#appendix-D
"""
# While this method exists, it could also sanitize the filename
# by rejecting slashes or other weirdness that might upset a receiver.
if disposition != 'attachment':
assert is_token(disposition)
rv = disposition
if is_token(filename):
rv += '; filename=%s' % (filename, )
return rv
elif is_ascii(filename) and is_lws_safe(filename):
qd_filename = qd_quote(filename)
rv += '; filename="%s"' % (qd_filename, )
if qd_filename == filename:
# RFC 6266 claims some implementations are iffy on qdtext's
# backslash-escaping, we'll include filename* in that case.
return rv
elif filename_compat:
if is_token(filename_compat):
rv += '; filename=%s' % (filename_compat, )
else:
assert is_lws_safe(filename_compat)
rv += '; filename="%s"' % (qd_quote(filename_compat), )
# alnum are already considered always-safe, but the rest isn't.
# Python encodes ~ when it shouldn't, for example.
rv += "; filename*=utf-8''%s" % (percent_encode(
filename, safe=attr_chars_nonalnum, encoding='utf-8'), )
# This will only encode filename_compat, if it used non-ascii iso-8859-1.
return rv.encode('iso-8859-1') | python | def build_header(
filename, disposition='attachment', filename_compat=None
):
"""Generate a Content-Disposition header for a given filename.
For legacy clients that don't understand the filename* parameter,
a filename_compat value may be given.
It should either be ascii-only (recommended) or iso-8859-1 only.
In the later case it should be a character string
(unicode in Python 2).
Options for generating filename_compat (only useful for legacy clients):
- ignore (will only send filename*);
- strip accents using unicode's decomposing normalisations,
which can be done from unicode data (stdlib), and keep only ascii;
- use the ascii transliteration tables from Unidecode (PyPI);
- use iso-8859-1
Ignore is the safest, and can be used to trigger a fallback
to the document location (which can be percent-encoded utf-8
if you control the URLs).
See https://tools.ietf.org/html/rfc6266#appendix-D
"""
# While this method exists, it could also sanitize the filename
# by rejecting slashes or other weirdness that might upset a receiver.
if disposition != 'attachment':
assert is_token(disposition)
rv = disposition
if is_token(filename):
rv += '; filename=%s' % (filename, )
return rv
elif is_ascii(filename) and is_lws_safe(filename):
qd_filename = qd_quote(filename)
rv += '; filename="%s"' % (qd_filename, )
if qd_filename == filename:
# RFC 6266 claims some implementations are iffy on qdtext's
# backslash-escaping, we'll include filename* in that case.
return rv
elif filename_compat:
if is_token(filename_compat):
rv += '; filename=%s' % (filename_compat, )
else:
assert is_lws_safe(filename_compat)
rv += '; filename="%s"' % (qd_quote(filename_compat), )
# alnum are already considered always-safe, but the rest isn't.
# Python encodes ~ when it shouldn't, for example.
rv += "; filename*=utf-8''%s" % (percent_encode(
filename, safe=attr_chars_nonalnum, encoding='utf-8'), )
# This will only encode filename_compat, if it used non-ascii iso-8859-1.
return rv.encode('iso-8859-1') | [
"def",
"build_header",
"(",
"filename",
",",
"disposition",
"=",
"'attachment'",
",",
"filename_compat",
"=",
"None",
")",
":",
"# While this method exists, it could also sanitize the filename",
"# by rejecting slashes or other weirdness that might upset a receiver.",
"if",
"dispos... | Generate a Content-Disposition header for a given filename.
For legacy clients that don't understand the filename* parameter,
a filename_compat value may be given.
It should either be ascii-only (recommended) or iso-8859-1 only.
In the later case it should be a character string
(unicode in Python 2).
Options for generating filename_compat (only useful for legacy clients):
- ignore (will only send filename*);
- strip accents using unicode's decomposing normalisations,
which can be done from unicode data (stdlib), and keep only ascii;
- use the ascii transliteration tables from Unidecode (PyPI);
- use iso-8859-1
Ignore is the safest, and can be used to trigger a fallback
to the document location (which can be percent-encoded utf-8
if you control the URLs).
See https://tools.ietf.org/html/rfc6266#appendix-D | [
"Generate",
"a",
"Content",
"-",
"Disposition",
"header",
"for",
"a",
"given",
"filename",
"."
] | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L398-L453 | train |
g2p/rfc6266 | rfc6266.py | ContentDisposition.filename_unsafe | def filename_unsafe(self):
"""The filename from the Content-Disposition header.
If a location was passed at instanciation, the basename
from that may be used as a fallback. Otherwise, this may
be the None value.
On safety:
This property records the intent of the sender.
You shouldn't use this sender-controlled value as a filesystem
path, it can be insecure. Serving files with this filename can be
dangerous as well, due to a certain browser using the part after the
dot for mime-sniffing.
Saving it to a database is fine by itself though.
"""
if 'filename*' in self.assocs:
return self.assocs['filename*'].string
elif 'filename' in self.assocs:
# XXX Reject non-ascii (parsed via qdtext) here?
return self.assocs['filename']
elif self.location is not None:
return posixpath.basename(self.location_path.rstrip('/')) | python | def filename_unsafe(self):
"""The filename from the Content-Disposition header.
If a location was passed at instanciation, the basename
from that may be used as a fallback. Otherwise, this may
be the None value.
On safety:
This property records the intent of the sender.
You shouldn't use this sender-controlled value as a filesystem
path, it can be insecure. Serving files with this filename can be
dangerous as well, due to a certain browser using the part after the
dot for mime-sniffing.
Saving it to a database is fine by itself though.
"""
if 'filename*' in self.assocs:
return self.assocs['filename*'].string
elif 'filename' in self.assocs:
# XXX Reject non-ascii (parsed via qdtext) here?
return self.assocs['filename']
elif self.location is not None:
return posixpath.basename(self.location_path.rstrip('/')) | [
"def",
"filename_unsafe",
"(",
"self",
")",
":",
"if",
"'filename*'",
"in",
"self",
".",
"assocs",
":",
"return",
"self",
".",
"assocs",
"[",
"'filename*'",
"]",
".",
"string",
"elif",
"'filename'",
"in",
"self",
".",
"assocs",
":",
"# XXX Reject non-ascii (... | The filename from the Content-Disposition header.
If a location was passed at instanciation, the basename
from that may be used as a fallback. Otherwise, this may
be the None value.
On safety:
This property records the intent of the sender.
You shouldn't use this sender-controlled value as a filesystem
path, it can be insecure. Serving files with this filename can be
dangerous as well, due to a certain browser using the part after the
dot for mime-sniffing.
Saving it to a database is fine by itself though. | [
"The",
"filename",
"from",
"the",
"Content",
"-",
"Disposition",
"header",
"."
] | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L89-L112 | train |
g2p/rfc6266 | rfc6266.py | ContentDisposition.filename_sanitized | def filename_sanitized(self, extension, default_filename='file'):
"""Returns a filename that is safer to use on the filesystem.
The filename will not contain a slash (nor the path separator
for the current platform, if different), it will not
start with a dot, and it will have the expected extension.
No guarantees that makes it "safe enough".
No effort is made to remove special characters;
using this value blindly might overwrite existing files, etc.
"""
assert extension
assert extension[0] != '.'
assert default_filename
assert '.' not in default_filename
extension = '.' + extension
fname = self.filename_unsafe
if fname is None:
fname = default_filename
fname = posixpath.basename(fname)
fname = os.path.basename(fname)
fname = fname.lstrip('.')
if not fname:
fname = default_filename
if not fname.endswith(extension):
fname = fname + extension
return fname | python | def filename_sanitized(self, extension, default_filename='file'):
"""Returns a filename that is safer to use on the filesystem.
The filename will not contain a slash (nor the path separator
for the current platform, if different), it will not
start with a dot, and it will have the expected extension.
No guarantees that makes it "safe enough".
No effort is made to remove special characters;
using this value blindly might overwrite existing files, etc.
"""
assert extension
assert extension[0] != '.'
assert default_filename
assert '.' not in default_filename
extension = '.' + extension
fname = self.filename_unsafe
if fname is None:
fname = default_filename
fname = posixpath.basename(fname)
fname = os.path.basename(fname)
fname = fname.lstrip('.')
if not fname:
fname = default_filename
if not fname.endswith(extension):
fname = fname + extension
return fname | [
"def",
"filename_sanitized",
"(",
"self",
",",
"extension",
",",
"default_filename",
"=",
"'file'",
")",
":",
"assert",
"extension",
"assert",
"extension",
"[",
"0",
"]",
"!=",
"'.'",
"assert",
"default_filename",
"assert",
"'.'",
"not",
"in",
"default_filename"... | Returns a filename that is safer to use on the filesystem.
The filename will not contain a slash (nor the path separator
for the current platform, if different), it will not
start with a dot, and it will have the expected extension.
No guarantees that makes it "safe enough".
No effort is made to remove special characters;
using this value blindly might overwrite existing files, etc. | [
"Returns",
"a",
"filename",
"that",
"is",
"safer",
"to",
"use",
"on",
"the",
"filesystem",
"."
] | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L121-L149 | train |
kbr/fritzconnection | fritzconnection/fritzstatus.py | FritzStatus.str_uptime | def str_uptime(self):
"""uptime in human readable format."""
mins, secs = divmod(self.uptime, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d' % (hours, mins, secs) | python | def str_uptime(self):
"""uptime in human readable format."""
mins, secs = divmod(self.uptime, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d' % (hours, mins, secs) | [
"def",
"str_uptime",
"(",
"self",
")",
":",
"mins",
",",
"secs",
"=",
"divmod",
"(",
"self",
".",
"uptime",
",",
"60",
")",
"hours",
",",
"mins",
"=",
"divmod",
"(",
"mins",
",",
"60",
")",
"return",
"'%02d:%02d:%02d'",
"%",
"(",
"hours",
",",
"min... | uptime in human readable format. | [
"uptime",
"in",
"human",
"readable",
"format",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L82-L86 | train |
kbr/fritzconnection | fritzconnection/fritzstatus.py | FritzStatus.transmission_rate | def transmission_rate(self):
"""
Returns the upstream, downstream values as a tuple in bytes per
second. Use this for periodical calling.
"""
sent = self.bytes_sent
received = self.bytes_received
traffic_call = time.time()
time_delta = traffic_call - self.last_traffic_call
upstream = int(1.0 * (sent - self.last_bytes_sent)/time_delta)
downstream = int(1.0 * (received - self.last_bytes_received)/time_delta)
self.last_bytes_sent = sent
self.last_bytes_received = received
self.last_traffic_call = traffic_call
return upstream, downstream | python | def transmission_rate(self):
"""
Returns the upstream, downstream values as a tuple in bytes per
second. Use this for periodical calling.
"""
sent = self.bytes_sent
received = self.bytes_received
traffic_call = time.time()
time_delta = traffic_call - self.last_traffic_call
upstream = int(1.0 * (sent - self.last_bytes_sent)/time_delta)
downstream = int(1.0 * (received - self.last_bytes_received)/time_delta)
self.last_bytes_sent = sent
self.last_bytes_received = received
self.last_traffic_call = traffic_call
return upstream, downstream | [
"def",
"transmission_rate",
"(",
"self",
")",
":",
"sent",
"=",
"self",
".",
"bytes_sent",
"received",
"=",
"self",
".",
"bytes_received",
"traffic_call",
"=",
"time",
".",
"time",
"(",
")",
"time_delta",
"=",
"traffic_call",
"-",
"self",
".",
"last_traffic_... | Returns the upstream, downstream values as a tuple in bytes per
second. Use this for periodical calling. | [
"Returns",
"the",
"upstream",
"downstream",
"values",
"as",
"a",
"tuple",
"in",
"bytes",
"per",
"second",
".",
"Use",
"this",
"for",
"periodical",
"calling",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L101-L115 | train |
kbr/fritzconnection | fritzconnection/fritzstatus.py | FritzStatus.str_transmission_rate | def str_transmission_rate(self):
"""Returns a tuple of human readable transmission rates in bytes."""
upstream, downstream = self.transmission_rate
return (
fritztools.format_num(upstream),
fritztools.format_num(downstream)
) | python | def str_transmission_rate(self):
"""Returns a tuple of human readable transmission rates in bytes."""
upstream, downstream = self.transmission_rate
return (
fritztools.format_num(upstream),
fritztools.format_num(downstream)
) | [
"def",
"str_transmission_rate",
"(",
"self",
")",
":",
"upstream",
",",
"downstream",
"=",
"self",
".",
"transmission_rate",
"return",
"(",
"fritztools",
".",
"format_num",
"(",
"upstream",
")",
",",
"fritztools",
".",
"format_num",
"(",
"downstream",
")",
")"... | Returns a tuple of human readable transmission rates in bytes. | [
"Returns",
"a",
"tuple",
"of",
"human",
"readable",
"transmission",
"rates",
"in",
"bytes",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L118-L124 | train |
kbr/fritzconnection | fritzconnection/fritzstatus.py | FritzStatus.max_bit_rate | def max_bit_rate(self):
"""
Returns a tuple with the maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
status = self.fc.call_action('WANCommonInterfaceConfig',
'GetCommonLinkProperties')
downstream = status['NewLayer1DownstreamMaxBitRate']
upstream = status['NewLayer1UpstreamMaxBitRate']
return upstream, downstream | python | def max_bit_rate(self):
"""
Returns a tuple with the maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
status = self.fc.call_action('WANCommonInterfaceConfig',
'GetCommonLinkProperties')
downstream = status['NewLayer1DownstreamMaxBitRate']
upstream = status['NewLayer1UpstreamMaxBitRate']
return upstream, downstream | [
"def",
"max_bit_rate",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"fc",
".",
"call_action",
"(",
"'WANCommonInterfaceConfig'",
",",
"'GetCommonLinkProperties'",
")",
"downstream",
"=",
"status",
"[",
"'NewLayer1DownstreamMaxBitRate'",
"]",
"upstream",
"=",
... | Returns a tuple with the maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec. | [
"Returns",
"a",
"tuple",
"with",
"the",
"maximun",
"upstream",
"-",
"and",
"downstream",
"-",
"rate",
"of",
"the",
"given",
"connection",
".",
"The",
"rate",
"is",
"given",
"in",
"bits",
"/",
"sec",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L127-L136 | train |
kbr/fritzconnection | fritzconnection/fritzstatus.py | FritzStatus.str_max_bit_rate | def str_max_bit_rate(self):
"""
Returns a human readable maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
upstream, downstream = self.max_bit_rate
return (
fritztools.format_rate(upstream, unit='bits'),
fritztools.format_rate(downstream, unit ='bits')
) | python | def str_max_bit_rate(self):
"""
Returns a human readable maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
upstream, downstream = self.max_bit_rate
return (
fritztools.format_rate(upstream, unit='bits'),
fritztools.format_rate(downstream, unit ='bits')
) | [
"def",
"str_max_bit_rate",
"(",
"self",
")",
":",
"upstream",
",",
"downstream",
"=",
"self",
".",
"max_bit_rate",
"return",
"(",
"fritztools",
".",
"format_rate",
"(",
"upstream",
",",
"unit",
"=",
"'bits'",
")",
",",
"fritztools",
".",
"format_rate",
"(",
... | Returns a human readable maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec. | [
"Returns",
"a",
"human",
"readable",
"maximun",
"upstream",
"-",
"and",
"downstream",
"-",
"rate",
"of",
"the",
"given",
"connection",
".",
"The",
"rate",
"is",
"given",
"in",
"bits",
"/",
"sec",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L147-L156 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzAction._body_builder | def _body_builder(self, kwargs):
"""
Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service.
"""
p = {
'action_name': self.name,
'service_type': self.service_type,
'arguments': '',
}
if kwargs:
arguments = [
self.argument_template % {'name': k, 'value': v}
for k, v in kwargs.items()
]
p['arguments'] = ''.join(arguments)
body = self.body_template.strip() % p
return body | python | def _body_builder(self, kwargs):
"""
Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service.
"""
p = {
'action_name': self.name,
'service_type': self.service_type,
'arguments': '',
}
if kwargs:
arguments = [
self.argument_template % {'name': k, 'value': v}
for k, v in kwargs.items()
]
p['arguments'] = ''.join(arguments)
body = self.body_template.strip() % p
return body | [
"def",
"_body_builder",
"(",
"self",
",",
"kwargs",
")",
":",
"p",
"=",
"{",
"'action_name'",
":",
"self",
".",
"name",
",",
"'service_type'",
":",
"self",
".",
"service_type",
",",
"'arguments'",
":",
"''",
",",
"}",
"if",
"kwargs",
":",
"arguments",
... | Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service. | [
"Helper",
"method",
"to",
"construct",
"the",
"appropriate",
"SOAP",
"-",
"body",
"to",
"call",
"a",
"FritzBox",
"-",
"Service",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L94-L111 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzAction.execute | def execute(self, **kwargs):
"""
Calls the FritzBox action and returns a dictionary with the arguments.
"""
headers = self.header.copy()
headers['soapaction'] = '%s#%s' % (self.service_type, self.name)
data = self.envelope.strip() % self._body_builder(kwargs)
url = 'http://%s:%s%s' % (self.address, self.port, self.control_url)
auth = None
if self.password:
auth=HTTPDigestAuth(self.user, self.password)
response = requests.post(url, data=data, headers=headers, auth=auth)
# lxml needs bytes, therefore response.content (not response.text)
result = self.parse_response(response.content)
return result | python | def execute(self, **kwargs):
"""
Calls the FritzBox action and returns a dictionary with the arguments.
"""
headers = self.header.copy()
headers['soapaction'] = '%s#%s' % (self.service_type, self.name)
data = self.envelope.strip() % self._body_builder(kwargs)
url = 'http://%s:%s%s' % (self.address, self.port, self.control_url)
auth = None
if self.password:
auth=HTTPDigestAuth(self.user, self.password)
response = requests.post(url, data=data, headers=headers, auth=auth)
# lxml needs bytes, therefore response.content (not response.text)
result = self.parse_response(response.content)
return result | [
"def",
"execute",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"self",
".",
"header",
".",
"copy",
"(",
")",
"headers",
"[",
"'soapaction'",
"]",
"=",
"'%s#%s'",
"%",
"(",
"self",
".",
"service_type",
",",
"self",
".",
"name",
")... | Calls the FritzBox action and returns a dictionary with the arguments. | [
"Calls",
"the",
"FritzBox",
"action",
"and",
"returns",
"a",
"dictionary",
"with",
"the",
"arguments",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L113-L127 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzAction.parse_response | def parse_response(self, response):
"""
Evaluates the action-call response from a FritzBox.
The response is a xml byte-string.
Returns a dictionary with the received arguments-value pairs.
The values are converted according to the given data_types.
TODO: boolean and signed integers data-types from tr64 responses
"""
result = {}
root = etree.fromstring(response)
for argument in self.arguments.values():
try:
value = root.find('.//%s' % argument.name).text
except AttributeError:
# will happen by searching for in-parameters and by
# parsing responses with status_code != 200
continue
if argument.data_type.startswith('ui'):
try:
value = int(value)
except ValueError:
# should not happen
value = None
result[argument.name] = value
return result | python | def parse_response(self, response):
"""
Evaluates the action-call response from a FritzBox.
The response is a xml byte-string.
Returns a dictionary with the received arguments-value pairs.
The values are converted according to the given data_types.
TODO: boolean and signed integers data-types from tr64 responses
"""
result = {}
root = etree.fromstring(response)
for argument in self.arguments.values():
try:
value = root.find('.//%s' % argument.name).text
except AttributeError:
# will happen by searching for in-parameters and by
# parsing responses with status_code != 200
continue
if argument.data_type.startswith('ui'):
try:
value = int(value)
except ValueError:
# should not happen
value = None
result[argument.name] = value
return result | [
"def",
"parse_response",
"(",
"self",
",",
"response",
")",
":",
"result",
"=",
"{",
"}",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"response",
")",
"for",
"argument",
"in",
"self",
".",
"arguments",
".",
"values",
"(",
")",
":",
"try",
":",
"val... | Evaluates the action-call response from a FritzBox.
The response is a xml byte-string.
Returns a dictionary with the received arguments-value pairs.
The values are converted according to the given data_types.
TODO: boolean and signed integers data-types from tr64 responses | [
"Evaluates",
"the",
"action",
"-",
"call",
"response",
"from",
"a",
"FritzBox",
".",
"The",
"response",
"is",
"a",
"xml",
"byte",
"-",
"string",
".",
"Returns",
"a",
"dictionary",
"with",
"the",
"received",
"arguments",
"-",
"value",
"pairs",
".",
"The",
... | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L129-L153 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzDescParser.get_modelname | def get_modelname(self):
"""Returns the FritzBox model name."""
xpath = '%s/%s' % (self.nodename('device'), self.nodename('modelName'))
return self.root.find(xpath).text | python | def get_modelname(self):
"""Returns the FritzBox model name."""
xpath = '%s/%s' % (self.nodename('device'), self.nodename('modelName'))
return self.root.find(xpath).text | [
"def",
"get_modelname",
"(",
"self",
")",
":",
"xpath",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"nodename",
"(",
"'device'",
")",
",",
"self",
".",
"nodename",
"(",
"'modelName'",
")",
")",
"return",
"self",
".",
"root",
".",
"find",
"(",
"xpath",
")"... | Returns the FritzBox model name. | [
"Returns",
"the",
"FritzBox",
"model",
"name",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L202-L205 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzDescParser.get_services | def get_services(self):
"""Returns a list of FritzService-objects."""
result = []
nodes = self.root.iterfind(
'.//ns:service', namespaces={'ns': self.namespace})
for node in nodes:
result.append(FritzService(
node.find(self.nodename('serviceType')).text,
node.find(self.nodename('controlURL')).text,
node.find(self.nodename('SCPDURL')).text))
return result | python | def get_services(self):
"""Returns a list of FritzService-objects."""
result = []
nodes = self.root.iterfind(
'.//ns:service', namespaces={'ns': self.namespace})
for node in nodes:
result.append(FritzService(
node.find(self.nodename('serviceType')).text,
node.find(self.nodename('controlURL')).text,
node.find(self.nodename('SCPDURL')).text))
return result | [
"def",
"get_services",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"nodes",
"=",
"self",
".",
"root",
".",
"iterfind",
"(",
"'.//ns:service'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"namespace",
"}",
")",
"for",
"node",
"in",
"nod... | Returns a list of FritzService-objects. | [
"Returns",
"a",
"list",
"of",
"FritzService",
"-",
"objects",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L207-L217 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzSCDPParser._read_state_variables | def _read_state_variables(self):
"""
Reads the stateVariable information from the xml-file.
The information we like to extract are name and dataType so we
can assign them later on to FritzActionArgument-instances.
Returns a dictionary: key:value = name:dataType
"""
nodes = self.root.iterfind(
'.//ns:stateVariable', namespaces={'ns': self.namespace})
for node in nodes:
key = node.find(self.nodename('name')).text
value = node.find(self.nodename('dataType')).text
self.state_variables[key] = value | python | def _read_state_variables(self):
"""
Reads the stateVariable information from the xml-file.
The information we like to extract are name and dataType so we
can assign them later on to FritzActionArgument-instances.
Returns a dictionary: key:value = name:dataType
"""
nodes = self.root.iterfind(
'.//ns:stateVariable', namespaces={'ns': self.namespace})
for node in nodes:
key = node.find(self.nodename('name')).text
value = node.find(self.nodename('dataType')).text
self.state_variables[key] = value | [
"def",
"_read_state_variables",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"root",
".",
"iterfind",
"(",
"'.//ns:stateVariable'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"namespace",
"}",
")",
"for",
"node",
"in",
"nodes",
":",
"key... | Reads the stateVariable information from the xml-file.
The information we like to extract are name and dataType so we
can assign them later on to FritzActionArgument-instances.
Returns a dictionary: key:value = name:dataType | [
"Reads",
"the",
"stateVariable",
"information",
"from",
"the",
"xml",
"-",
"file",
".",
"The",
"information",
"we",
"like",
"to",
"extract",
"are",
"name",
"and",
"dataType",
"so",
"we",
"can",
"assign",
"them",
"later",
"on",
"to",
"FritzActionArgument",
"-... | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L240-L252 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzSCDPParser.get_actions | def get_actions(self):
"""Returns a list of FritzAction instances."""
self._read_state_variables()
actions = []
nodes = self.root.iterfind(
'.//ns:action', namespaces={'ns': self.namespace})
for node in nodes:
action = FritzAction(self.service.service_type,
self.service.control_url)
action.name = node.find(self.nodename('name')).text
action.arguments = self._get_arguments(node)
actions.append(action)
return actions | python | def get_actions(self):
"""Returns a list of FritzAction instances."""
self._read_state_variables()
actions = []
nodes = self.root.iterfind(
'.//ns:action', namespaces={'ns': self.namespace})
for node in nodes:
action = FritzAction(self.service.service_type,
self.service.control_url)
action.name = node.find(self.nodename('name')).text
action.arguments = self._get_arguments(node)
actions.append(action)
return actions | [
"def",
"get_actions",
"(",
"self",
")",
":",
"self",
".",
"_read_state_variables",
"(",
")",
"actions",
"=",
"[",
"]",
"nodes",
"=",
"self",
".",
"root",
".",
"iterfind",
"(",
"'.//ns:action'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"na... | Returns a list of FritzAction instances. | [
"Returns",
"a",
"list",
"of",
"FritzAction",
"instances",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L254-L266 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzSCDPParser._get_arguments | def _get_arguments(self, action_node):
"""
Returns a dictionary of arguments for the given action_node.
"""
arguments = {}
argument_nodes = action_node.iterfind(
r'./ns:argumentList/ns:argument', namespaces={'ns': self.namespace})
for argument_node in argument_nodes:
argument = self._get_argument(argument_node)
arguments[argument.name] = argument
return arguments | python | def _get_arguments(self, action_node):
"""
Returns a dictionary of arguments for the given action_node.
"""
arguments = {}
argument_nodes = action_node.iterfind(
r'./ns:argumentList/ns:argument', namespaces={'ns': self.namespace})
for argument_node in argument_nodes:
argument = self._get_argument(argument_node)
arguments[argument.name] = argument
return arguments | [
"def",
"_get_arguments",
"(",
"self",
",",
"action_node",
")",
":",
"arguments",
"=",
"{",
"}",
"argument_nodes",
"=",
"action_node",
".",
"iterfind",
"(",
"r'./ns:argumentList/ns:argument'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"namespace",
... | Returns a dictionary of arguments for the given action_node. | [
"Returns",
"a",
"dictionary",
"of",
"arguments",
"for",
"the",
"given",
"action_node",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L268-L278 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzSCDPParser._get_argument | def _get_argument(self, argument_node):
"""
Returns a FritzActionArgument instance for the given argument_node.
"""
argument = FritzActionArgument()
argument.name = argument_node.find(self.nodename('name')).text
argument.direction = argument_node.find(self.nodename('direction')).text
rsv = argument_node.find(self.nodename('relatedStateVariable')).text
# TODO: track malformed xml-nodes (i.e. misspelled)
argument.data_type = self.state_variables.get(rsv, None)
return argument | python | def _get_argument(self, argument_node):
"""
Returns a FritzActionArgument instance for the given argument_node.
"""
argument = FritzActionArgument()
argument.name = argument_node.find(self.nodename('name')).text
argument.direction = argument_node.find(self.nodename('direction')).text
rsv = argument_node.find(self.nodename('relatedStateVariable')).text
# TODO: track malformed xml-nodes (i.e. misspelled)
argument.data_type = self.state_variables.get(rsv, None)
return argument | [
"def",
"_get_argument",
"(",
"self",
",",
"argument_node",
")",
":",
"argument",
"=",
"FritzActionArgument",
"(",
")",
"argument",
".",
"name",
"=",
"argument_node",
".",
"find",
"(",
"self",
".",
"nodename",
"(",
"'name'",
")",
")",
".",
"text",
"argument... | Returns a FritzActionArgument instance for the given argument_node. | [
"Returns",
"a",
"FritzActionArgument",
"instance",
"for",
"the",
"given",
"argument_node",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L280-L290 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzConnection._read_descriptions | def _read_descriptions(self, password):
"""
Read and evaluate the igddesc.xml file
and the tr64desc.xml file if a password is given.
"""
descfiles = [FRITZ_IGD_DESC_FILE]
if password:
descfiles.append(FRITZ_TR64_DESC_FILE)
for descfile in descfiles:
parser = FritzDescParser(self.address, self.port, descfile)
if not self.modelname:
self.modelname = parser.get_modelname()
services = parser.get_services()
self._read_services(services) | python | def _read_descriptions(self, password):
"""
Read and evaluate the igddesc.xml file
and the tr64desc.xml file if a password is given.
"""
descfiles = [FRITZ_IGD_DESC_FILE]
if password:
descfiles.append(FRITZ_TR64_DESC_FILE)
for descfile in descfiles:
parser = FritzDescParser(self.address, self.port, descfile)
if not self.modelname:
self.modelname = parser.get_modelname()
services = parser.get_services()
self._read_services(services) | [
"def",
"_read_descriptions",
"(",
"self",
",",
"password",
")",
":",
"descfiles",
"=",
"[",
"FRITZ_IGD_DESC_FILE",
"]",
"if",
"password",
":",
"descfiles",
".",
"append",
"(",
"FRITZ_TR64_DESC_FILE",
")",
"for",
"descfile",
"in",
"descfiles",
":",
"parser",
"=... | Read and evaluate the igddesc.xml file
and the tr64desc.xml file if a password is given. | [
"Read",
"and",
"evaluate",
"the",
"igddesc",
".",
"xml",
"file",
"and",
"the",
"tr64desc",
".",
"xml",
"file",
"if",
"a",
"password",
"is",
"given",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L315-L328 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzConnection._read_services | def _read_services(self, services):
"""Get actions from services."""
for service in services:
parser = FritzSCDPParser(self.address, self.port, service)
actions = parser.get_actions()
service.actions = {action.name: action for action in actions}
self.services[service.name] = service | python | def _read_services(self, services):
"""Get actions from services."""
for service in services:
parser = FritzSCDPParser(self.address, self.port, service)
actions = parser.get_actions()
service.actions = {action.name: action for action in actions}
self.services[service.name] = service | [
"def",
"_read_services",
"(",
"self",
",",
"services",
")",
":",
"for",
"service",
"in",
"services",
":",
"parser",
"=",
"FritzSCDPParser",
"(",
"self",
".",
"address",
",",
"self",
".",
"port",
",",
"service",
")",
"actions",
"=",
"parser",
".",
"get_ac... | Get actions from services. | [
"Get",
"actions",
"from",
"services",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L330-L336 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzConnection.actionnames | def actionnames(self):
"""
Returns a alphabetical sorted list of tuples with all known
service- and action-names.
"""
actions = []
for service_name in sorted(self.services.keys()):
action_names = self.services[service_name].actions.keys()
for action_name in sorted(action_names):
actions.append((service_name, action_name))
return actions | python | def actionnames(self):
"""
Returns a alphabetical sorted list of tuples with all known
service- and action-names.
"""
actions = []
for service_name in sorted(self.services.keys()):
action_names = self.services[service_name].actions.keys()
for action_name in sorted(action_names):
actions.append((service_name, action_name))
return actions | [
"def",
"actionnames",
"(",
"self",
")",
":",
"actions",
"=",
"[",
"]",
"for",
"service_name",
"in",
"sorted",
"(",
"self",
".",
"services",
".",
"keys",
"(",
")",
")",
":",
"action_names",
"=",
"self",
".",
"services",
"[",
"service_name",
"]",
".",
... | Returns a alphabetical sorted list of tuples with all known
service- and action-names. | [
"Returns",
"a",
"alphabetical",
"sorted",
"list",
"of",
"tuples",
"with",
"all",
"known",
"service",
"-",
"and",
"action",
"-",
"names",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L339-L349 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzConnection.get_action_arguments | def get_action_arguments(self, service_name, action_name):
"""
Returns a list of tuples with all known arguments for the given
service- and action-name combination. The tuples contain the
argument-name, direction and data_type.
"""
return self.services[service_name].actions[action_name].info | python | def get_action_arguments(self, service_name, action_name):
"""
Returns a list of tuples with all known arguments for the given
service- and action-name combination. The tuples contain the
argument-name, direction and data_type.
"""
return self.services[service_name].actions[action_name].info | [
"def",
"get_action_arguments",
"(",
"self",
",",
"service_name",
",",
"action_name",
")",
":",
"return",
"self",
".",
"services",
"[",
"service_name",
"]",
".",
"actions",
"[",
"action_name",
"]",
".",
"info"
] | Returns a list of tuples with all known arguments for the given
service- and action-name combination. The tuples contain the
argument-name, direction and data_type. | [
"Returns",
"a",
"list",
"of",
"tuples",
"with",
"all",
"known",
"arguments",
"for",
"the",
"given",
"service",
"-",
"and",
"action",
"-",
"name",
"combination",
".",
"The",
"tuples",
"contain",
"the",
"argument",
"-",
"name",
"direction",
"and",
"data_type",... | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L351-L357 | train |
kbr/fritzconnection | fritzconnection/fritzconnection.py | FritzConnection.call_action | def call_action(self, service_name, action_name, **kwargs):
"""Executes the given action. Raise a KeyError on unkown actions."""
action = self.services[service_name].actions[action_name]
return action.execute(**kwargs) | python | def call_action(self, service_name, action_name, **kwargs):
"""Executes the given action. Raise a KeyError on unkown actions."""
action = self.services[service_name].actions[action_name]
return action.execute(**kwargs) | [
"def",
"call_action",
"(",
"self",
",",
"service_name",
",",
"action_name",
",",
"*",
"*",
"kwargs",
")",
":",
"action",
"=",
"self",
".",
"services",
"[",
"service_name",
"]",
".",
"actions",
"[",
"action_name",
"]",
"return",
"action",
".",
"execute",
... | Executes the given action. Raise a KeyError on unkown actions. | [
"Executes",
"the",
"given",
"action",
".",
"Raise",
"a",
"KeyError",
"on",
"unkown",
"actions",
"."
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L359-L362 | train |
kbr/fritzconnection | fritzconnection/fritzhosts.py | FritzHosts.get_hosts_info | def get_hosts_info(self):
"""
Returns a list of dicts with information about the known hosts.
The dict-keys are: 'ip', 'name', 'mac', 'status'
"""
result = []
index = 0
while index < self.host_numbers:
host = self.get_generic_host_entry(index)
result.append({
'ip': host['NewIPAddress'],
'name': host['NewHostName'],
'mac': host['NewMACAddress'],
'status': host['NewActive']})
index += 1
return result | python | def get_hosts_info(self):
"""
Returns a list of dicts with information about the known hosts.
The dict-keys are: 'ip', 'name', 'mac', 'status'
"""
result = []
index = 0
while index < self.host_numbers:
host = self.get_generic_host_entry(index)
result.append({
'ip': host['NewIPAddress'],
'name': host['NewHostName'],
'mac': host['NewMACAddress'],
'status': host['NewActive']})
index += 1
return result | [
"def",
"get_hosts_info",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"self",
".",
"host_numbers",
":",
"host",
"=",
"self",
".",
"get_generic_host_entry",
"(",
"index",
")",
"result",
".",
"append",
"(",
"{... | Returns a list of dicts with information about the known hosts.
The dict-keys are: 'ip', 'name', 'mac', 'status' | [
"Returns",
"a",
"list",
"of",
"dicts",
"with",
"information",
"about",
"the",
"known",
"hosts",
".",
"The",
"dict",
"-",
"keys",
"are",
":",
"ip",
"name",
"mac",
"status"
] | b183f759ef19dd1652371e912d36cfe34f6639ac | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzhosts.py#L50-L65 | train |
grigi/talkey | talkey/utils.py | find_executable | def find_executable(executable):
'''
Finds executable in PATH
Returns:
string or None
'''
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
executable_path = _find_executable(executable)
found = executable_path is not None
if found:
logger.debug("Executable '%s' found: '%s'", executable, executable_path)
else:
logger.debug("Executable '%s' not found", executable)
return executable_path | python | def find_executable(executable):
'''
Finds executable in PATH
Returns:
string or None
'''
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
executable_path = _find_executable(executable)
found = executable_path is not None
if found:
logger.debug("Executable '%s' found: '%s'", executable, executable_path)
else:
logger.debug("Executable '%s' not found", executable)
return executable_path | [
"def",
"find_executable",
"(",
"executable",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Checking executable '%s'...\"",
",",
"executable",
")",
"executable_path",
"=",
"_find_executable",
"(",
"execu... | Finds executable in PATH
Returns:
string or None | [
"Finds",
"executable",
"in",
"PATH"
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/utils.py#L12-L27 | train |
grigi/talkey | talkey/utils.py | check_network_connection | def check_network_connection(server, port):
'''
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug("Checking network connection to server '%s'...", server)
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(server)
# connect to the host -- tells us if the host is actually
# reachable
sock = socket.create_connection((host, port), 2)
sock.close()
except Exception: # pragma: no cover
logger.debug("Network connection not working")
return False
logger.debug("Network connection working")
return True | python | def check_network_connection(server, port):
'''
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug("Checking network connection to server '%s'...", server)
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(server)
# connect to the host -- tells us if the host is actually
# reachable
sock = socket.create_connection((host, port), 2)
sock.close()
except Exception: # pragma: no cover
logger.debug("Network connection not working")
return False
logger.debug("Network connection working")
return True | [
"def",
"check_network_connection",
"(",
"server",
",",
"port",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Checking network connection to server '%s'...\"",
",",
"server",
")",
"try",
":",
"# see if w... | Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False | [
"Checks",
"if",
"jasper",
"can",
"connect",
"a",
"network",
"server",
".",
"Arguments",
":",
"server",
"--",
"(",
"optional",
")",
"the",
"server",
"to",
"connect",
"with",
"(",
"Default",
":",
"www",
".",
"google",
".",
"com",
")",
"Returns",
":",
"Tr... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/utils.py#L40-L63 | train |
grigi/talkey | talkey/utils.py | check_python_import | def check_python_import(package_or_module):
'''
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug("Checking python import '%s'...", package_or_module)
loader = pkgutil.get_loader(package_or_module)
found = loader is not None
if found:
logger.debug("Python %s '%s' found",
"package" if loader.is_package(package_or_module)
else "module", package_or_module)
else: # pragma: no cover
logger.debug("Python import '%s' not found", package_or_module)
return found | python | def check_python_import(package_or_module):
'''
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug("Checking python import '%s'...", package_or_module)
loader = pkgutil.get_loader(package_or_module)
found = loader is not None
if found:
logger.debug("Python %s '%s' found",
"package" if loader.is_package(package_or_module)
else "module", package_or_module)
else: # pragma: no cover
logger.debug("Python import '%s' not found", package_or_module)
return found | [
"def",
"check_python_import",
"(",
"package_or_module",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Checking python import '%s'...\"",
",",
"package_or_module",
")",
"loader",
"=",
"pkgutil",
".",
"ge... | Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False | [
"Checks",
"if",
"a",
"python",
"package",
"or",
"module",
"is",
"importable",
".",
"Arguments",
":",
"package_or_module",
"--",
"the",
"package",
"or",
"module",
"name",
"to",
"check",
"Returns",
":",
"True",
"or",
"False"
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/utils.py#L66-L84 | train |
mozilla-services/axe-selenium-python | axe_selenium_python/axe.py | Axe.inject | def inject(self):
"""
Recursively inject aXe into all iframes and the top level document.
:param script_url: location of the axe-core script.
:type script_url: string
"""
with open(self.script_url, "r", encoding="utf8") as f:
self.selenium.execute_script(f.read()) | python | def inject(self):
"""
Recursively inject aXe into all iframes and the top level document.
:param script_url: location of the axe-core script.
:type script_url: string
"""
with open(self.script_url, "r", encoding="utf8") as f:
self.selenium.execute_script(f.read()) | [
"def",
"inject",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"script_url",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf8\"",
")",
"as",
"f",
":",
"self",
".",
"selenium",
".",
"execute_script",
"(",
"f",
".",
"read",
"(",
")",
")"
] | Recursively inject aXe into all iframes and the top level document.
:param script_url: location of the axe-core script.
:type script_url: string | [
"Recursively",
"inject",
"aXe",
"into",
"all",
"iframes",
"and",
"the",
"top",
"level",
"document",
"."
] | 475c9f4eb771587aea73897bee356284d0361d77 | https://github.com/mozilla-services/axe-selenium-python/blob/475c9f4eb771587aea73897bee356284d0361d77/axe_selenium_python/axe.py#L19-L27 | train |
mozilla-services/axe-selenium-python | axe_selenium_python/axe.py | Axe.run | def run(self, context=None, options=None):
"""
Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options.
"""
template = (
"var callback = arguments[arguments.length - 1];"
+ "axe.run(%s).then(results => callback(results))"
)
args = ""
# If context parameter is passed, add to args
if context is not None:
args += "%r" % context
# Add comma delimiter only if both parameters are passed
if context is not None and options is not None:
args += ","
# If options parameter is passed, add to args
if options is not None:
args += "%s" % options
command = template % args
response = self.selenium.execute_async_script(command)
return response | python | def run(self, context=None, options=None):
"""
Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options.
"""
template = (
"var callback = arguments[arguments.length - 1];"
+ "axe.run(%s).then(results => callback(results))"
)
args = ""
# If context parameter is passed, add to args
if context is not None:
args += "%r" % context
# Add comma delimiter only if both parameters are passed
if context is not None and options is not None:
args += ","
# If options parameter is passed, add to args
if options is not None:
args += "%s" % options
command = template % args
response = self.selenium.execute_async_script(command)
return response | [
"def",
"run",
"(",
"self",
",",
"context",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"template",
"=",
"(",
"\"var callback = arguments[arguments.length - 1];\"",
"+",
"\"axe.run(%s).then(results => callback(results))\"",
")",
"args",
"=",
"\"\"",
"# If conte... | Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options. | [
"Run",
"axe",
"against",
"the",
"current",
"page",
"."
] | 475c9f4eb771587aea73897bee356284d0361d77 | https://github.com/mozilla-services/axe-selenium-python/blob/475c9f4eb771587aea73897bee356284d0361d77/axe_selenium_python/axe.py#L29-L54 | train |
mozilla-services/axe-selenium-python | axe_selenium_python/axe.py | Axe.report | def report(self, violations):
"""
Return readable report of accessibility violations found.
:param violations: Dictionary of violations.
:type violations: dict
:return report: Readable report of violations.
:rtype: string
"""
string = ""
string += "Found " + str(len(violations)) + " accessibility violations:"
for violation in violations:
string += (
"\n\n\nRule Violated:\n"
+ violation["id"]
+ " - "
+ violation["description"]
+ "\n\tURL: "
+ violation["helpUrl"]
+ "\n\tImpact Level: "
+ violation["impact"]
+ "\n\tTags:"
)
for tag in violation["tags"]:
string += " " + tag
string += "\n\tElements Affected:"
i = 1
for node in violation["nodes"]:
for target in node["target"]:
string += "\n\t" + str(i) + ") Target: " + target
i += 1
for item in node["all"]:
string += "\n\t\t" + item["message"]
for item in node["any"]:
string += "\n\t\t" + item["message"]
for item in node["none"]:
string += "\n\t\t" + item["message"]
string += "\n\n\n"
return string | python | def report(self, violations):
"""
Return readable report of accessibility violations found.
:param violations: Dictionary of violations.
:type violations: dict
:return report: Readable report of violations.
:rtype: string
"""
string = ""
string += "Found " + str(len(violations)) + " accessibility violations:"
for violation in violations:
string += (
"\n\n\nRule Violated:\n"
+ violation["id"]
+ " - "
+ violation["description"]
+ "\n\tURL: "
+ violation["helpUrl"]
+ "\n\tImpact Level: "
+ violation["impact"]
+ "\n\tTags:"
)
for tag in violation["tags"]:
string += " " + tag
string += "\n\tElements Affected:"
i = 1
for node in violation["nodes"]:
for target in node["target"]:
string += "\n\t" + str(i) + ") Target: " + target
i += 1
for item in node["all"]:
string += "\n\t\t" + item["message"]
for item in node["any"]:
string += "\n\t\t" + item["message"]
for item in node["none"]:
string += "\n\t\t" + item["message"]
string += "\n\n\n"
return string | [
"def",
"report",
"(",
"self",
",",
"violations",
")",
":",
"string",
"=",
"\"\"",
"string",
"+=",
"\"Found \"",
"+",
"str",
"(",
"len",
"(",
"violations",
")",
")",
"+",
"\" accessibility violations:\"",
"for",
"violation",
"in",
"violations",
":",
"string",... | Return readable report of accessibility violations found.
:param violations: Dictionary of violations.
:type violations: dict
:return report: Readable report of violations.
:rtype: string | [
"Return",
"readable",
"report",
"of",
"accessibility",
"violations",
"found",
"."
] | 475c9f4eb771587aea73897bee356284d0361d77 | https://github.com/mozilla-services/axe-selenium-python/blob/475c9f4eb771587aea73897bee356284d0361d77/axe_selenium_python/axe.py#L56-L94 | train |
mozilla-services/axe-selenium-python | axe_selenium_python/axe.py | Axe.write_results | def write_results(self, data, name=None):
"""
Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:param output: JSON object.
"""
if name:
filepath = os.path.abspath(name)
else:
filepath = os.path.join(os.path.getcwd(), "results.json")
with open(filepath, "w", encoding="utf8") as f:
try:
f.write(unicode(json.dumps(data, indent=4)))
except NameError:
f.write(json.dumps(data, indent=4)) | python | def write_results(self, data, name=None):
"""
Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:param output: JSON object.
"""
if name:
filepath = os.path.abspath(name)
else:
filepath = os.path.join(os.path.getcwd(), "results.json")
with open(filepath, "w", encoding="utf8") as f:
try:
f.write(unicode(json.dumps(data, indent=4)))
except NameError:
f.write(json.dumps(data, indent=4)) | [
"def",
"write_results",
"(",
"self",
",",
"data",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"name",
")",
"else",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os"... | Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:param output: JSON object. | [
"Write",
"JSON",
"to",
"file",
"with",
"the",
"specified",
"name",
"."
] | 475c9f4eb771587aea73897bee356284d0361d77 | https://github.com/mozilla-services/axe-selenium-python/blob/475c9f4eb771587aea73897bee356284d0361d77/axe_selenium_python/axe.py#L96-L115 | train |
grigi/talkey | talkey/tts.py | create_engine | def create_engine(engine, options=None, defaults=None):
'''
Creates an instance of an engine.
There is a two-stage instantiation process with engines.
1. ``options``:
The keyword options to instantiate the engine class
2. ``defaults``:
The default configuration for the engine (options often depends on instantiated TTS engine)
'''
if engine not in _ENGINE_MAP.keys():
raise TTSError('Unknown engine %s' % engine)
options = options or {}
defaults = defaults or {}
einst = _ENGINE_MAP[engine](**options)
einst.configure_default(**defaults)
return einst | python | def create_engine(engine, options=None, defaults=None):
'''
Creates an instance of an engine.
There is a two-stage instantiation process with engines.
1. ``options``:
The keyword options to instantiate the engine class
2. ``defaults``:
The default configuration for the engine (options often depends on instantiated TTS engine)
'''
if engine not in _ENGINE_MAP.keys():
raise TTSError('Unknown engine %s' % engine)
options = options or {}
defaults = defaults or {}
einst = _ENGINE_MAP[engine](**options)
einst.configure_default(**defaults)
return einst | [
"def",
"create_engine",
"(",
"engine",
",",
"options",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"engine",
"not",
"in",
"_ENGINE_MAP",
".",
"keys",
"(",
")",
":",
"raise",
"TTSError",
"(",
"'Unknown engine %s'",
"%",
"engine",
")",
"opti... | Creates an instance of an engine.
There is a two-stage instantiation process with engines.
1. ``options``:
The keyword options to instantiate the engine class
2. ``defaults``:
The default configuration for the engine (options often depends on instantiated TTS engine) | [
"Creates",
"an",
"instance",
"of",
"an",
"engine",
".",
"There",
"is",
"a",
"two",
"-",
"stage",
"instantiation",
"process",
"with",
"engines",
"."
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/tts.py#L14-L31 | train |
grigi/talkey | talkey/tts.py | Talkey.classify | def classify(self, txt):
'''
Classifies text by language. Uses preferred_languages weighting.
'''
ranks = []
for lang, score in langid.rank(txt):
if lang in self.preferred_languages:
score += self.preferred_factor
ranks.append((lang, score))
ranks.sort(key=lambda x: x[1], reverse=True)
return ranks[0][0] | python | def classify(self, txt):
'''
Classifies text by language. Uses preferred_languages weighting.
'''
ranks = []
for lang, score in langid.rank(txt):
if lang in self.preferred_languages:
score += self.preferred_factor
ranks.append((lang, score))
ranks.sort(key=lambda x: x[1], reverse=True)
return ranks[0][0] | [
"def",
"classify",
"(",
"self",
",",
"txt",
")",
":",
"ranks",
"=",
"[",
"]",
"for",
"lang",
",",
"score",
"in",
"langid",
".",
"rank",
"(",
"txt",
")",
":",
"if",
"lang",
"in",
"self",
".",
"preferred_languages",
":",
"score",
"+=",
"self",
".",
... | Classifies text by language. Uses preferred_languages weighting. | [
"Classifies",
"text",
"by",
"language",
".",
"Uses",
"preferred_languages",
"weighting",
"."
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/tts.py#L105-L115 | train |
grigi/talkey | talkey/tts.py | Talkey.get_engine_for_lang | def get_engine_for_lang(self, lang):
'''
Determines the preferred engine/voice for a language.
'''
for eng in self.engines:
if lang in eng.languages.keys():
return eng
raise TTSError('Could not match language') | python | def get_engine_for_lang(self, lang):
'''
Determines the preferred engine/voice for a language.
'''
for eng in self.engines:
if lang in eng.languages.keys():
return eng
raise TTSError('Could not match language') | [
"def",
"get_engine_for_lang",
"(",
"self",
",",
"lang",
")",
":",
"for",
"eng",
"in",
"self",
".",
"engines",
":",
"if",
"lang",
"in",
"eng",
".",
"languages",
".",
"keys",
"(",
")",
":",
"return",
"eng",
"raise",
"TTSError",
"(",
"'Could not match langu... | Determines the preferred engine/voice for a language. | [
"Determines",
"the",
"preferred",
"engine",
"/",
"voice",
"for",
"a",
"language",
"."
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/tts.py#L117-L124 | train |
grigi/talkey | talkey/tts.py | Talkey.say | def say(self, txt, lang=None):
'''
Says the text.
if ``lang`` is ``None``, then uses ``classify()`` to detect language.
'''
lang = lang or self.classify(txt)
self.get_engine_for_lang(lang).say(txt, language=lang) | python | def say(self, txt, lang=None):
'''
Says the text.
if ``lang`` is ``None``, then uses ``classify()`` to detect language.
'''
lang = lang or self.classify(txt)
self.get_engine_for_lang(lang).say(txt, language=lang) | [
"def",
"say",
"(",
"self",
",",
"txt",
",",
"lang",
"=",
"None",
")",
":",
"lang",
"=",
"lang",
"or",
"self",
".",
"classify",
"(",
"txt",
")",
"self",
".",
"get_engine_for_lang",
"(",
"lang",
")",
".",
"say",
"(",
"txt",
",",
"language",
"=",
"l... | Says the text.
if ``lang`` is ``None``, then uses ``classify()`` to detect language. | [
"Says",
"the",
"text",
"."
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/tts.py#L126-L133 | train |
grigi/talkey | talkey/base.py | AbstractTTSEngine.configure_default | def configure_default(self, **_options):
'''
Sets default configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options)
self.default_language = language
self.default_options = options | python | def configure_default(self, **_options):
'''
Sets default configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options)
self.default_language = language
self.default_options = options | [
"def",
"configure_default",
"(",
"self",
",",
"*",
"*",
"_options",
")",
":",
"language",
",",
"voice",
",",
"voiceinfo",
",",
"options",
"=",
"self",
".",
"_configure",
"(",
"*",
"*",
"_options",
")",
"self",
".",
"languages_options",
"[",
"language",
"... | Sets default configuration.
Raises TTSError on error. | [
"Sets",
"default",
"configuration",
"."
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/base.py#L206-L215 | train |
grigi/talkey | talkey/base.py | AbstractTTSEngine.configure | def configure(self, **_options):
'''
Sets language-specific configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options) | python | def configure(self, **_options):
'''
Sets language-specific configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options) | [
"def",
"configure",
"(",
"self",
",",
"*",
"*",
"_options",
")",
":",
"language",
",",
"voice",
",",
"voiceinfo",
",",
"options",
"=",
"self",
".",
"_configure",
"(",
"*",
"*",
"_options",
")",
"self",
".",
"languages_options",
"[",
"language",
"]",
"=... | Sets language-specific configuration.
Raises TTSError on error. | [
"Sets",
"language",
"-",
"specific",
"configuration",
"."
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/base.py#L217-L224 | train |
grigi/talkey | talkey/base.py | AbstractTTSEngine.say | def say(self, phrase, **_options):
'''
Says the phrase, optionally allows to select/override any voice options.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self._logger.debug("Saying '%s' with '%s'", phrase, self.SLUG)
self._say(phrase, language, voice, voiceinfo, options) | python | def say(self, phrase, **_options):
'''
Says the phrase, optionally allows to select/override any voice options.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self._logger.debug("Saying '%s' with '%s'", phrase, self.SLUG)
self._say(phrase, language, voice, voiceinfo, options) | [
"def",
"say",
"(",
"self",
",",
"phrase",
",",
"*",
"*",
"_options",
")",
":",
"language",
",",
"voice",
",",
"voiceinfo",
",",
"options",
"=",
"self",
".",
"_configure",
"(",
"*",
"*",
"_options",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\... | Says the phrase, optionally allows to select/override any voice options. | [
"Says",
"the",
"phrase",
"optionally",
"allows",
"to",
"select",
"/",
"override",
"any",
"voice",
"options",
"."
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/base.py#L226-L232 | train |
grigi/talkey | talkey/base.py | AbstractTTSEngine.play | def play(self, filename, translate=False): # pragma: no cover
'''
Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV.
'''
# FIXME: Use platform-independent and async audio-output here
# PyAudio looks most promising, too bad about:
# --allow-external PyAudio --allow-unverified PyAudio
if translate:
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
fname = f.name
with audioread.audio_open(filename) as f:
with contextlib.closing(wave.open(fname, 'w')) as of:
of.setnchannels(f.channels)
of.setframerate(f.samplerate)
of.setsampwidth(2)
for buf in f:
of.writeframes(buf)
filename = fname
if winsound:
winsound.PlaySound(str(filename), winsound.SND_FILENAME)
else:
cmd = ['aplay', str(filename)]
self._logger.debug('Executing %s', ' '.join([pipes.quote(arg) for arg in cmd]))
subprocess.call(cmd)
if translate:
os.remove(fname) | python | def play(self, filename, translate=False): # pragma: no cover
'''
Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV.
'''
# FIXME: Use platform-independent and async audio-output here
# PyAudio looks most promising, too bad about:
# --allow-external PyAudio --allow-unverified PyAudio
if translate:
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
fname = f.name
with audioread.audio_open(filename) as f:
with contextlib.closing(wave.open(fname, 'w')) as of:
of.setnchannels(f.channels)
of.setframerate(f.samplerate)
of.setsampwidth(2)
for buf in f:
of.writeframes(buf)
filename = fname
if winsound:
winsound.PlaySound(str(filename), winsound.SND_FILENAME)
else:
cmd = ['aplay', str(filename)]
self._logger.debug('Executing %s', ' '.join([pipes.quote(arg) for arg in cmd]))
subprocess.call(cmd)
if translate:
os.remove(fname) | [
"def",
"play",
"(",
"self",
",",
"filename",
",",
"translate",
"=",
"False",
")",
":",
"# pragma: no cover",
"# FIXME: Use platform-independent and async audio-output here",
"# PyAudio looks most promising, too bad about:",
"# --allow-external PyAudio --allow-unverified PyAudio",
"i... | Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV. | [
"Plays",
"the",
"sounds",
"."
] | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/base.py#L234-L264 | train |
trbs/bucky | bucky/collectd.py | getCollectDServer | def getCollectDServer(queue, cfg):
"""Get the appropriate collectd server (multi processed or not)"""
server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer
return server(queue, cfg) | python | def getCollectDServer(queue, cfg):
"""Get the appropriate collectd server (multi processed or not)"""
server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer
return server(queue, cfg) | [
"def",
"getCollectDServer",
"(",
"queue",
",",
"cfg",
")",
":",
"server",
"=",
"CollectDServerMP",
"if",
"cfg",
".",
"collectd_workers",
">",
"1",
"else",
"CollectDServer",
"return",
"server",
"(",
"queue",
",",
"cfg",
")"
] | Get the appropriate collectd server (multi processed or not) | [
"Get",
"the",
"appropriate",
"collectd",
"server",
"(",
"multi",
"processed",
"or",
"not",
")"
] | ae4c696be46cda977cb5f27c31420985ef1cc0ba | https://github.com/trbs/bucky/blob/ae4c696be46cda977cb5f27c31420985ef1cc0ba/bucky/collectd.py#L652-L655 | train |
trbs/bucky | bucky/collectd.py | CollectDCrypto._hashes_match | def _hashes_match(self, a, b):
"""Constant time comparison of bytes for py3, strings for py2"""
if len(a) != len(b):
return False
diff = 0
if six.PY2:
a = bytearray(a)
b = bytearray(b)
for x, y in zip(a, b):
diff |= x ^ y
return not diff | python | def _hashes_match(self, a, b):
"""Constant time comparison of bytes for py3, strings for py2"""
if len(a) != len(b):
return False
diff = 0
if six.PY2:
a = bytearray(a)
b = bytearray(b)
for x, y in zip(a, b):
diff |= x ^ y
return not diff | [
"def",
"_hashes_match",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"return",
"False",
"diff",
"=",
"0",
"if",
"six",
".",
"PY2",
":",
"a",
"=",
"bytearray",
"(",
"a",
")",
"b",
"=... | Constant time comparison of bytes for py3, strings for py2 | [
"Constant",
"time",
"comparison",
"of",
"bytes",
"for",
"py3",
"strings",
"for",
"py2"
] | ae4c696be46cda977cb5f27c31420985ef1cc0ba | https://github.com/trbs/bucky/blob/ae4c696be46cda977cb5f27c31420985ef1cc0ba/bucky/collectd.py#L369-L379 | train |
heigeo/climata | climata/bin/acis_sites.py | load_sites | def load_sites(*basin_ids):
"""
Load metadata for all sites in given basin codes.
"""
# Resolve basin ids to HUC8s if needed
basins = []
for basin in basin_ids:
if basin.isdigit() and len(basin) == 8:
basins.append(basin)
else:
from climata.huc8 import get_huc8
basins.extend(get_huc8(basin))
# Load sites with data since 1900
sites = StationMetaIO(
basin=basins,
parameter=list(elems.keys()),
start_date='1900-01-01',
end_date=date.today(),
meta=ALL_META_FIELDS,
)
# Load all sites (to get sites without data)
seen_sites = [site.uid for site in sites]
nodata_sites = [
site for site in StationMetaIO(basin=basins)
if site.uid not in seen_sites
]
# Determine the following from the site lists:
seen_auths = set() # Which authority codes are actually used by any site
seen_elems = set() # Which elems actually have data in any site
ranges = {} # The overall period of record for each site
for site in sites:
for auth in site.sids.keys():
seen_auths.add(auth)
start, end = None, None
for elem in site.valid_daterange:
s, e = site.valid_daterange[elem]
seen_elems.add(elem)
if s is None or e is None:
continue
if start is None or s < start:
start = s
if end is None or e > end:
end = e
ranges[site.uid] = [start, end]
# Check for authority codes that might not be in sites with data
for site in nodata_sites:
for auth in site.sids.keys():
seen_auths.add(auth)
# Print CSV headers (FIXME: use CsvFileIO for this?)
seen_auths = sorted(seen_auths)
seen_elems = sorted(seen_elems)
print(",".join(
['ACIS uid', 'name']
+ seen_auths
+ ['latitude', 'longitude', 'start', 'end', 'years']
+ [elems[elem]['desc'] for elem in seen_elems]
))
# Print sites with data
for site in sites:
# Determine if elems are available for entire period or shorter range
start, end = ranges[site.uid]
if start and end:
years = end.year - start.year + 1
elem_ranges = []
for elem in seen_elems:
estart, eend = site.valid_daterange[elem]
if estart is None:
erange = ""
elif estart == start and eend == end:
erange = "period"
else:
erange = "%s to %s" % (estart.date(), eend.date())
elem_ranges.append(erange)
# Output CSV row
print(",".join(map(
str,
[site.uid, site.name]
+ [site.sids.get(auth, "") for auth in seen_auths]
+ [site.latitude, site.longitude]
+ [start.date(), end.date(), years]
+ elem_ranges
)))
# Print CSV rows for sites without data
for site in nodata_sites:
print(",".join(map(
str,
[site.uid, site.name]
+ [site.sids.get(auth, "") for auth in seen_auths]
+ [site.latitude, site.longitude]
+ ["NO DATA"]
))) | python | def load_sites(*basin_ids):
"""
Load metadata for all sites in given basin codes.
"""
# Resolve basin ids to HUC8s if needed
basins = []
for basin in basin_ids:
if basin.isdigit() and len(basin) == 8:
basins.append(basin)
else:
from climata.huc8 import get_huc8
basins.extend(get_huc8(basin))
# Load sites with data since 1900
sites = StationMetaIO(
basin=basins,
parameter=list(elems.keys()),
start_date='1900-01-01',
end_date=date.today(),
meta=ALL_META_FIELDS,
)
# Load all sites (to get sites without data)
seen_sites = [site.uid for site in sites]
nodata_sites = [
site for site in StationMetaIO(basin=basins)
if site.uid not in seen_sites
]
# Determine the following from the site lists:
seen_auths = set() # Which authority codes are actually used by any site
seen_elems = set() # Which elems actually have data in any site
ranges = {} # The overall period of record for each site
for site in sites:
for auth in site.sids.keys():
seen_auths.add(auth)
start, end = None, None
for elem in site.valid_daterange:
s, e = site.valid_daterange[elem]
seen_elems.add(elem)
if s is None or e is None:
continue
if start is None or s < start:
start = s
if end is None or e > end:
end = e
ranges[site.uid] = [start, end]
# Check for authority codes that might not be in sites with data
for site in nodata_sites:
for auth in site.sids.keys():
seen_auths.add(auth)
# Print CSV headers (FIXME: use CsvFileIO for this?)
seen_auths = sorted(seen_auths)
seen_elems = sorted(seen_elems)
print(",".join(
['ACIS uid', 'name']
+ seen_auths
+ ['latitude', 'longitude', 'start', 'end', 'years']
+ [elems[elem]['desc'] for elem in seen_elems]
))
# Print sites with data
for site in sites:
# Determine if elems are available for entire period or shorter range
start, end = ranges[site.uid]
if start and end:
years = end.year - start.year + 1
elem_ranges = []
for elem in seen_elems:
estart, eend = site.valid_daterange[elem]
if estart is None:
erange = ""
elif estart == start and eend == end:
erange = "period"
else:
erange = "%s to %s" % (estart.date(), eend.date())
elem_ranges.append(erange)
# Output CSV row
print(",".join(map(
str,
[site.uid, site.name]
+ [site.sids.get(auth, "") for auth in seen_auths]
+ [site.latitude, site.longitude]
+ [start.date(), end.date(), years]
+ elem_ranges
)))
# Print CSV rows for sites without data
for site in nodata_sites:
print(",".join(map(
str,
[site.uid, site.name]
+ [site.sids.get(auth, "") for auth in seen_auths]
+ [site.latitude, site.longitude]
+ ["NO DATA"]
))) | [
"def",
"load_sites",
"(",
"*",
"basin_ids",
")",
":",
"# Resolve basin ids to HUC8s if needed",
"basins",
"=",
"[",
"]",
"for",
"basin",
"in",
"basin_ids",
":",
"if",
"basin",
".",
"isdigit",
"(",
")",
"and",
"len",
"(",
"basin",
")",
"==",
"8",
":",
"ba... | Load metadata for all sites in given basin codes. | [
"Load",
"metadata",
"for",
"all",
"sites",
"in",
"given",
"basin",
"codes",
"."
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/bin/acis_sites.py#L16-L118 | train |
heigeo/climata | climata/huc8/__init__.py | get_huc8 | def get_huc8(prefix):
"""
Return all HUC8s matching the given prefix (e.g. 1801) or basin name
(e.g. Klamath)
"""
if not prefix.isdigit():
# Look up hucs by name
name = prefix
prefix = None
for row in hucs:
if row.basin.lower() == name.lower():
# Use most general huc if two have the same name
if prefix is None or len(row.huc) < len(prefix):
prefix = row.huc
if prefix is None:
return []
huc8s = []
for row in hucs:
# Return all 8-digit hucs with given prefix
if len(row.huc) == 8 and row.huc.startswith(prefix):
huc8s.append(row.huc)
return huc8s | python | def get_huc8(prefix):
"""
Return all HUC8s matching the given prefix (e.g. 1801) or basin name
(e.g. Klamath)
"""
if not prefix.isdigit():
# Look up hucs by name
name = prefix
prefix = None
for row in hucs:
if row.basin.lower() == name.lower():
# Use most general huc if two have the same name
if prefix is None or len(row.huc) < len(prefix):
prefix = row.huc
if prefix is None:
return []
huc8s = []
for row in hucs:
# Return all 8-digit hucs with given prefix
if len(row.huc) == 8 and row.huc.startswith(prefix):
huc8s.append(row.huc)
return huc8s | [
"def",
"get_huc8",
"(",
"prefix",
")",
":",
"if",
"not",
"prefix",
".",
"isdigit",
"(",
")",
":",
"# Look up hucs by name",
"name",
"=",
"prefix",
"prefix",
"=",
"None",
"for",
"row",
"in",
"hucs",
":",
"if",
"row",
".",
"basin",
".",
"lower",
"(",
"... | Return all HUC8s matching the given prefix (e.g. 1801) or basin name
(e.g. Klamath) | [
"Return",
"all",
"HUC8s",
"matching",
"the",
"given",
"prefix",
"(",
"e",
".",
"g",
".",
"1801",
")",
"or",
"basin",
"name",
"(",
"e",
".",
"g",
".",
"Klamath",
")"
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/huc8/__init__.py#L23-L46 | train |
heigeo/climata | climata/acis/__init__.py | StationMetaIO.parse | def parse(self):
"""
Convert ACIS 'll' value into separate latitude and longitude.
"""
super(AcisIO, self).parse()
# This is more of a "mapping" step than a "parsing" step, but mappers
# only allow one-to-one mapping from input fields to output fields.
for row in self.data:
if 'meta' in row:
row = row['meta']
if 'll' in row:
row['longitude'], row['latitude'] = row['ll']
del row['ll'] | python | def parse(self):
"""
Convert ACIS 'll' value into separate latitude and longitude.
"""
super(AcisIO, self).parse()
# This is more of a "mapping" step than a "parsing" step, but mappers
# only allow one-to-one mapping from input fields to output fields.
for row in self.data:
if 'meta' in row:
row = row['meta']
if 'll' in row:
row['longitude'], row['latitude'] = row['ll']
del row['ll'] | [
"def",
"parse",
"(",
"self",
")",
":",
"super",
"(",
"AcisIO",
",",
"self",
")",
".",
"parse",
"(",
")",
"# This is more of a \"mapping\" step than a \"parsing\" step, but mappers",
"# only allow one-to-one mapping from input fields to output fields.",
"for",
"row",
"in",
"... | Convert ACIS 'll' value into separate latitude and longitude. | [
"Convert",
"ACIS",
"ll",
"value",
"into",
"separate",
"latitude",
"and",
"longitude",
"."
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L80-L93 | train |
heigeo/climata | climata/acis/__init__.py | StationMetaIO.map_value | def map_value(self, field, value):
"""
Clean up some values returned from the web service.
(overrides wq.io.mappers.BaseMapper)
"""
if field == 'sids':
# Site identifiers are returned as "[id] [auth_id]";
# Map to auth name for easier usability
ids = {}
for idinfo in value:
id, auth = idinfo.split(' ')
auth = AUTHORITY_BY_ID[auth]
ids[auth['name']] = id
return ids
if field == 'valid_daterange':
# Date ranges for each element are returned in an array
# (sorted by the order the elements were were requested);
# Convert to dictionary with element id as key
elems, complex = self.getlist('parameter')
ranges = {}
for elem, val in zip(elems, value):
if val:
start, end = val
ranges[elem] = (parse_date(start), parse_date(end))
else:
ranges[elem] = None, None
return ranges
return value | python | def map_value(self, field, value):
"""
Clean up some values returned from the web service.
(overrides wq.io.mappers.BaseMapper)
"""
if field == 'sids':
# Site identifiers are returned as "[id] [auth_id]";
# Map to auth name for easier usability
ids = {}
for idinfo in value:
id, auth = idinfo.split(' ')
auth = AUTHORITY_BY_ID[auth]
ids[auth['name']] = id
return ids
if field == 'valid_daterange':
# Date ranges for each element are returned in an array
# (sorted by the order the elements were were requested);
# Convert to dictionary with element id as key
elems, complex = self.getlist('parameter')
ranges = {}
for elem, val in zip(elems, value):
if val:
start, end = val
ranges[elem] = (parse_date(start), parse_date(end))
else:
ranges[elem] = None, None
return ranges
return value | [
"def",
"map_value",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"if",
"field",
"==",
"'sids'",
":",
"# Site identifiers are returned as \"[id] [auth_id]\";",
"# Map to auth name for easier usability",
"ids",
"=",
"{",
"}",
"for",
"idinfo",
"in",
"value",
":",... | Clean up some values returned from the web service.
(overrides wq.io.mappers.BaseMapper) | [
"Clean",
"up",
"some",
"values",
"returned",
"from",
"the",
"web",
"service",
".",
"(",
"overrides",
"wq",
".",
"io",
".",
"mappers",
".",
"BaseMapper",
")"
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L95-L124 | train |
heigeo/climata | climata/acis/__init__.py | StationDataIO.get_field_names | def get_field_names(self):
"""
ACIS web service returns "meta" and "data" for each station;
Use meta attributes as field names
"""
field_names = super(StationDataIO, self).get_field_names()
if set(field_names) == set(['meta', 'data']):
meta_fields = list(self.data[0]['meta'].keys())
if set(meta_fields) < set(self.getvalue('meta')):
meta_fields = self.getvalue('meta')
field_names = list(meta_fields) + ['data']
return field_names | python | def get_field_names(self):
"""
ACIS web service returns "meta" and "data" for each station;
Use meta attributes as field names
"""
field_names = super(StationDataIO, self).get_field_names()
if set(field_names) == set(['meta', 'data']):
meta_fields = list(self.data[0]['meta'].keys())
if set(meta_fields) < set(self.getvalue('meta')):
meta_fields = self.getvalue('meta')
field_names = list(meta_fields) + ['data']
return field_names | [
"def",
"get_field_names",
"(",
"self",
")",
":",
"field_names",
"=",
"super",
"(",
"StationDataIO",
",",
"self",
")",
".",
"get_field_names",
"(",
")",
"if",
"set",
"(",
"field_names",
")",
"==",
"set",
"(",
"[",
"'meta'",
",",
"'data'",
"]",
")",
":",... | ACIS web service returns "meta" and "data" for each station;
Use meta attributes as field names | [
"ACIS",
"web",
"service",
"returns",
"meta",
"and",
"data",
"for",
"each",
"station",
";",
"Use",
"meta",
"attributes",
"as",
"field",
"names"
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L147-L158 | train |
heigeo/climata | climata/acis/__init__.py | StationDataIO.usable_item | def usable_item(self, data):
"""
ACIS web service returns "meta" and "data" for each station; use meta
attributes as item values, and add an IO for iterating over "data"
"""
# Use metadata as item
item = data['meta']
# Add nested IO for data
elems, elems_is_complex = self.getlist('parameter')
if elems_is_complex:
elems = [elem['name'] for elem in elems]
add, add_is_complex = self.getlist('add')
item['data'] = DataIO(
data=data['data'],
parameter=elems,
add=add,
start_date=self.getvalue('start_date'),
end_date=self.getvalue('end_date'),
)
# TupleMapper will convert item to namedtuple
return super(StationDataIO, self).usable_item(item) | python | def usable_item(self, data):
"""
ACIS web service returns "meta" and "data" for each station; use meta
attributes as item values, and add an IO for iterating over "data"
"""
# Use metadata as item
item = data['meta']
# Add nested IO for data
elems, elems_is_complex = self.getlist('parameter')
if elems_is_complex:
elems = [elem['name'] for elem in elems]
add, add_is_complex = self.getlist('add')
item['data'] = DataIO(
data=data['data'],
parameter=elems,
add=add,
start_date=self.getvalue('start_date'),
end_date=self.getvalue('end_date'),
)
# TupleMapper will convert item to namedtuple
return super(StationDataIO, self).usable_item(item) | [
"def",
"usable_item",
"(",
"self",
",",
"data",
")",
":",
"# Use metadata as item",
"item",
"=",
"data",
"[",
"'meta'",
"]",
"# Add nested IO for data",
"elems",
",",
"elems_is_complex",
"=",
"self",
".",
"getlist",
"(",
"'parameter'",
")",
"if",
"elems_is_compl... | ACIS web service returns "meta" and "data" for each station; use meta
attributes as item values, and add an IO for iterating over "data" | [
"ACIS",
"web",
"service",
"returns",
"meta",
"and",
"data",
"for",
"each",
"station",
";",
"use",
"meta",
"attributes",
"as",
"item",
"values",
"and",
"add",
"an",
"IO",
"for",
"iterating",
"over",
"data"
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L175-L199 | train |
heigeo/climata | climata/acis/__init__.py | DataIO.load_data | def load_data(self, data):
"""
MultiStnData data results are arrays without explicit dates;
Infer time series based on start date.
"""
dates = fill_date_range(self.start_date, self.end_date)
for row, date in zip(data, dates):
data = {'date': date}
if self.add:
# If self.add is set, results will contain additional
# attributes (e.g. flags). In that case, create one row per
# result, with attributes "date", "elem", "value", and one for
# each item in self.add.
for elem, vals in zip(self.parameter, row):
data['elem'] = elem
for add, val in zip(['value'] + self.add, vals):
data[add] = val
yield data
else:
# Otherwise, return one row per date, with "date" and each
# element's value as attributes.
for elem, val in zip(self.parameter, row):
# namedtuple doesn't like numeric field names
if elem.isdigit():
elem = "e%s" % elem
data[elem] = val
yield data | python | def load_data(self, data):
"""
MultiStnData data results are arrays without explicit dates;
Infer time series based on start date.
"""
dates = fill_date_range(self.start_date, self.end_date)
for row, date in zip(data, dates):
data = {'date': date}
if self.add:
# If self.add is set, results will contain additional
# attributes (e.g. flags). In that case, create one row per
# result, with attributes "date", "elem", "value", and one for
# each item in self.add.
for elem, vals in zip(self.parameter, row):
data['elem'] = elem
for add, val in zip(['value'] + self.add, vals):
data[add] = val
yield data
else:
# Otherwise, return one row per date, with "date" and each
# element's value as attributes.
for elem, val in zip(self.parameter, row):
# namedtuple doesn't like numeric field names
if elem.isdigit():
elem = "e%s" % elem
data[elem] = val
yield data | [
"def",
"load_data",
"(",
"self",
",",
"data",
")",
":",
"dates",
"=",
"fill_date_range",
"(",
"self",
".",
"start_date",
",",
"self",
".",
"end_date",
")",
"for",
"row",
",",
"date",
"in",
"zip",
"(",
"data",
",",
"dates",
")",
":",
"data",
"=",
"{... | MultiStnData data results are arrays without explicit dates;
Infer time series based on start date. | [
"MultiStnData",
"data",
"results",
"are",
"arrays",
"without",
"explicit",
"dates",
";",
"Infer",
"time",
"series",
"based",
"on",
"start",
"date",
"."
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L216-L243 | train |
heigeo/climata | climata/acis/__init__.py | DataIO.get_field_names | def get_field_names(self):
"""
Different field names depending on self.add setting (see load_data)
For BaseIO
"""
if self.add:
return ['date', 'elem', 'value'] + [flag for flag in self.add]
else:
field_names = ['date']
for elem in self.parameter:
# namedtuple doesn't like numeric field names
if elem.isdigit():
elem = "e%s" % elem
field_names.append(elem)
return field_names | python | def get_field_names(self):
"""
Different field names depending on self.add setting (see load_data)
For BaseIO
"""
if self.add:
return ['date', 'elem', 'value'] + [flag for flag in self.add]
else:
field_names = ['date']
for elem in self.parameter:
# namedtuple doesn't like numeric field names
if elem.isdigit():
elem = "e%s" % elem
field_names.append(elem)
return field_names | [
"def",
"get_field_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"add",
":",
"return",
"[",
"'date'",
",",
"'elem'",
",",
"'value'",
"]",
"+",
"[",
"flag",
"for",
"flag",
"in",
"self",
".",
"add",
"]",
"else",
":",
"field_names",
"=",
"[",
"'dat... | Different field names depending on self.add setting (see load_data)
For BaseIO | [
"Different",
"field",
"names",
"depending",
"on",
"self",
".",
"add",
"setting",
"(",
"see",
"load_data",
")",
"For",
"BaseIO"
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L250-L264 | train |
heigeo/climata | climata/base.py | fill_date_range | def fill_date_range(start_date, end_date, date_format=None):
"""
Function accepts start date, end date, and format (if dates are strings)
and returns a list of Python dates.
"""
if date_format:
start_date = datetime.strptime(start_date, date_format).date()
end_date = datetime.strptime(end_date, date_format).date()
date_list = []
while start_date <= end_date:
date_list.append(start_date)
start_date = start_date + timedelta(days=1)
return date_list | python | def fill_date_range(start_date, end_date, date_format=None):
"""
Function accepts start date, end date, and format (if dates are strings)
and returns a list of Python dates.
"""
if date_format:
start_date = datetime.strptime(start_date, date_format).date()
end_date = datetime.strptime(end_date, date_format).date()
date_list = []
while start_date <= end_date:
date_list.append(start_date)
start_date = start_date + timedelta(days=1)
return date_list | [
"def",
"fill_date_range",
"(",
"start_date",
",",
"end_date",
",",
"date_format",
"=",
"None",
")",
":",
"if",
"date_format",
":",
"start_date",
"=",
"datetime",
".",
"strptime",
"(",
"start_date",
",",
"date_format",
")",
".",
"date",
"(",
")",
"end_date",
... | Function accepts start date, end date, and format (if dates are strings)
and returns a list of Python dates. | [
"Function",
"accepts",
"start",
"date",
"end",
"date",
"and",
"format",
"(",
"if",
"dates",
"are",
"strings",
")",
"and",
"returns",
"a",
"list",
"of",
"Python",
"dates",
"."
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L252-L265 | train |
heigeo/climata | climata/base.py | FilterOpt.parse | def parse(self, value):
"""
Enforce rules and return parsed value
"""
if self.required and value is None:
raise ValueError("%s is required!" % self.name)
elif self.ignored and value is not None:
warn("%s is ignored for this class!" % self.name)
elif not self.multi and isinstance(value, (list, tuple)):
if len(value) > 1:
raise ValueError(
"%s does not accept multiple values!" % self.name
)
return value[0]
elif self.multi and value is not None:
if not isinstance(value, (list, tuple)):
return [value]
return value | python | def parse(self, value):
"""
Enforce rules and return parsed value
"""
if self.required and value is None:
raise ValueError("%s is required!" % self.name)
elif self.ignored and value is not None:
warn("%s is ignored for this class!" % self.name)
elif not self.multi and isinstance(value, (list, tuple)):
if len(value) > 1:
raise ValueError(
"%s does not accept multiple values!" % self.name
)
return value[0]
elif self.multi and value is not None:
if not isinstance(value, (list, tuple)):
return [value]
return value | [
"def",
"parse",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"required",
"and",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"%s is required!\"",
"%",
"self",
".",
"name",
")",
"elif",
"self",
".",
"ignored",
"and",
"value",
"is... | Enforce rules and return parsed value | [
"Enforce",
"rules",
"and",
"return",
"parsed",
"value"
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L32-L49 | train |
heigeo/climata | climata/base.py | DateOpt.parse | def parse(self, value):
"""
Parse date
"""
value = super(DateOpt, self).parse(value)
if value is None:
return None
if isinstance(value, str):
value = self.parse_date(value)
if isinstance(value, datetime) and self.date_only:
value = value.date()
return value | python | def parse(self, value):
"""
Parse date
"""
value = super(DateOpt, self).parse(value)
if value is None:
return None
if isinstance(value, str):
value = self.parse_date(value)
if isinstance(value, datetime) and self.date_only:
value = value.date()
return value | [
"def",
"parse",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"DateOpt",
",",
"self",
")",
".",
"parse",
"(",
"value",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
... | Parse date | [
"Parse",
"date"
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L58-L69 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.