partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | delete | Delete given device model or instance. | google-assistant-sdk/googlesamples/assistant/grpc/devicetool.py | def delete(ctx, resource, id):
"""Delete given device model or instance.
"""
session, api_url, project_id = build_client_from_context(ctx)
url = '/'.join([api_url, resource, id])
r = session.delete(url)
if r.status_code != 200:
raise failed_request_exception('failed to delete resource', ... | def delete(ctx, resource, id):
"""Delete given device model or instance.
"""
session, api_url, project_id = build_client_from_context(ctx)
url = '/'.join([api_url, resource, id])
r = session.delete(url)
if r.status_code != 200:
raise failed_request_exception('failed to delete resource', ... | [
"Delete",
"given",
"device",
"model",
"or",
"instance",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/devicetool.py#L352-L360 | [
"def",
"delete",
"(",
"ctx",
",",
"resource",
",",
"id",
")",
":",
"session",
",",
"api_url",
",",
"project_id",
"=",
"build_client_from_context",
"(",
"ctx",
")",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"api_url",
",",
"resource",
",",
"id",
"]",
... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | EmbeddedAssistantServicer.Converse | Initiates or continues a conversation with the embedded assistant service.
Each call performs one round-trip, sending an audio request to the service
and receiving the audio response. Uses bidirectional streaming to receive
results, such as the `END_OF_UTTERANCE` event, while sending audio.
A conversat... | google-assistant-grpc/google/assistant/embedded/v1alpha1/embedded_assistant_pb2_grpc.py | def Converse(self, request_iterator, context):
"""Initiates or continues a conversation with the embedded assistant service.
Each call performs one round-trip, sending an audio request to the service
and receiving the audio response. Uses bidirectional streaming to receive
results, such as the `END_OF_U... | def Converse(self, request_iterator, context):
"""Initiates or continues a conversation with the embedded assistant service.
Each call performs one round-trip, sending an audio request to the service
and receiving the audio response. Uses bidirectional streaming to receive
results, such as the `END_OF_U... | [
"Initiates",
"or",
"continues",
"a",
"conversation",
"with",
"the",
"embedded",
"assistant",
"service",
".",
"Each",
"call",
"performs",
"one",
"round",
"-",
"trip",
"sending",
"an",
"audio",
"request",
"to",
"the",
"service",
"and",
"receiving",
"the",
"audio... | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-grpc/google/assistant/embedded/v1alpha1/embedded_assistant_pb2_grpc.py#L28-L75 | [
"def",
"Converse",
"(",
"self",
",",
"request_iterator",
",",
"context",
")",
":",
"context",
".",
"set_code",
"(",
"grpc",
".",
"StatusCode",
".",
"UNIMPLEMENTED",
")",
"context",
".",
"set_details",
"(",
"'Method not implemented!'",
")",
"raise",
"NotImplement... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | log_assist_request_without_audio | Log AssistRequest fields without audio data. | google-assistant-sdk/googlesamples/assistant/grpc/assistant_helpers.py | def log_assist_request_without_audio(assist_request):
"""Log AssistRequest fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistRequest()
resp_copy.CopyFrom(assist_request)
if len(resp_copy.audio_in) > 0:
s... | def log_assist_request_without_audio(assist_request):
"""Log AssistRequest fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistRequest()
resp_copy.CopyFrom(assist_request)
if len(resp_copy.audio_in) > 0:
s... | [
"Log",
"AssistRequest",
"fields",
"without",
"audio",
"data",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/assistant_helpers.py#L22-L33 | [
"def",
"log_assist_request_without_audio",
"(",
"assist_request",
")",
":",
"if",
"logging",
".",
"getLogger",
"(",
")",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"resp_copy",
"=",
"embedded_assistant_pb2",
".",
"AssistRequest",
"(",
")",
"res... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | log_assist_response_without_audio | Log AssistResponse fields without audio data. | google-assistant-sdk/googlesamples/assistant/grpc/assistant_helpers.py | def log_assist_response_without_audio(assist_response):
"""Log AssistResponse fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistResponse()
resp_copy.CopyFrom(assist_response)
has_audio_data = (resp_copy.HasField('au... | def log_assist_response_without_audio(assist_response):
"""Log AssistResponse fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistResponse()
resp_copy.CopyFrom(assist_response)
has_audio_data = (resp_copy.HasField('au... | [
"Log",
"AssistResponse",
"fields",
"without",
"audio",
"data",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/assistant_helpers.py#L36-L54 | [
"def",
"log_assist_response_without_audio",
"(",
"assist_response",
")",
":",
"if",
"logging",
".",
"getLogger",
"(",
")",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"resp_copy",
"=",
"embedded_assistant_pb2",
".",
"AssistResponse",
"(",
")",
"... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | DeviceRequestHandler.command | Register a device action handlers. | google-assistant-sdk/googlesamples/assistant/grpc/device_helpers.py | def command(self, intent):
"""Register a device action handlers."""
def decorator(fn):
self.handlers[intent] = fn
return decorator | def command(self, intent):
"""Register a device action handlers."""
def decorator(fn):
self.handlers[intent] = fn
return decorator | [
"Register",
"a",
"device",
"action",
"handlers",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/device_helpers.py#L63-L67 | [
"def",
"command",
"(",
"self",
",",
"intent",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"self",
".",
"handlers",
"[",
"intent",
"]",
"=",
"fn",
"return",
"decorator"
] | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | DeviceRequestHandler.submit_commands | Submit device command executions.
Returns: a list of concurrent.futures for scheduled executions. | google-assistant-sdk/googlesamples/assistant/grpc/device_helpers.py | def submit_commands(self, devices, execution):
"""Submit device command executions.
Returns: a list of concurrent.futures for scheduled executions.
"""
fs = []
for device in devices:
if device[key_id_] != self.device_id:
logging.warning('Ignoring comm... | def submit_commands(self, devices, execution):
"""Submit device command executions.
Returns: a list of concurrent.futures for scheduled executions.
"""
fs = []
for device in devices:
if device[key_id_] != self.device_id:
logging.warning('Ignoring comm... | [
"Submit",
"device",
"command",
"executions",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/device_helpers.py#L69-L88 | [
"def",
"submit_commands",
"(",
"self",
",",
"devices",
",",
"execution",
")",
":",
"fs",
"=",
"[",
"]",
"for",
"device",
"in",
"devices",
":",
"if",
"device",
"[",
"key_id_",
"]",
"!=",
"self",
".",
"device_id",
":",
"logging",
".",
"warning",
"(",
"... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | DeviceRequestHandler.dispatch_command | Dispatch device commands to the appropriate handler. | google-assistant-sdk/googlesamples/assistant/grpc/device_helpers.py | def dispatch_command(self, command, params=None):
"""Dispatch device commands to the appropriate handler."""
try:
if command in self.handlers:
self.handlers[command](**params)
else:
logging.warning('Unsupported command: %s: %s',
... | def dispatch_command(self, command, params=None):
"""Dispatch device commands to the appropriate handler."""
try:
if command in self.handlers:
self.handlers[command](**params)
else:
logging.warning('Unsupported command: %s: %s',
... | [
"Dispatch",
"device",
"commands",
"to",
"the",
"appropriate",
"handler",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/device_helpers.py#L90-L101 | [
"def",
"dispatch_command",
"(",
"self",
",",
"command",
",",
"params",
"=",
"None",
")",
":",
"try",
":",
"if",
"command",
"in",
"self",
".",
"handlers",
":",
"self",
".",
"handlers",
"[",
"command",
"]",
"(",
"*",
"*",
"params",
")",
"else",
":",
... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | normalize_audio_buffer | Adjusts the loudness of the audio data in the given buffer.
Volume normalization is done by scaling the amplitude of the audio
in the buffer by a scale factor of 2^(volume_percentage/100)-1.
For example, 50% volume scales the amplitude by a factor of 0.414,
and 75% volume scales the amplitude by a fact... | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def normalize_audio_buffer(buf, volume_percentage, sample_width=2):
"""Adjusts the loudness of the audio data in the given buffer.
Volume normalization is done by scaling the amplitude of the audio
in the buffer by a scale factor of 2^(volume_percentage/100)-1.
For example, 50% volume scales the amplit... | def normalize_audio_buffer(buf, volume_percentage, sample_width=2):
"""Adjusts the loudness of the audio data in the given buffer.
Volume normalization is done by scaling the amplitude of the audio
in the buffer by a scale factor of 2^(volume_percentage/100)-1.
For example, 50% volume scales the amplit... | [
"Adjusts",
"the",
"loudness",
"of",
"the",
"audio",
"data",
"in",
"the",
"given",
"buffer",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L35-L58 | [
"def",
"normalize_audio_buffer",
"(",
"buf",
",",
"volume_percentage",
",",
"sample_width",
"=",
"2",
")",
":",
"if",
"sample_width",
"!=",
"2",
":",
"raise",
"Exception",
"(",
"'unsupported sample width:'",
",",
"sample_width",
")",
"scale",
"=",
"math",
".",
... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | align_buf | In case of buffer size not aligned to sample_width pad it with 0s | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def align_buf(buf, sample_width):
"""In case of buffer size not aligned to sample_width pad it with 0s"""
remainder = len(buf) % sample_width
if remainder != 0:
buf += b'\0' * (sample_width - remainder)
return buf | def align_buf(buf, sample_width):
"""In case of buffer size not aligned to sample_width pad it with 0s"""
remainder = len(buf) % sample_width
if remainder != 0:
buf += b'\0' * (sample_width - remainder)
return buf | [
"In",
"case",
"of",
"buffer",
"size",
"not",
"aligned",
"to",
"sample_width",
"pad",
"it",
"with",
"0s"
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L61-L66 | [
"def",
"align_buf",
"(",
"buf",
",",
"sample_width",
")",
":",
"remainder",
"=",
"len",
"(",
"buf",
")",
"%",
"sample_width",
"if",
"remainder",
"!=",
"0",
":",
"buf",
"+=",
"b'\\0'",
"*",
"(",
"sample_width",
"-",
"remainder",
")",
"return",
"buf"
] | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | main | Helper command to test audio stream processing.
- Record 5 seconds of 16-bit samples at 16khz.
- Playback the recorded samples. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def main(record_time, audio_sample_rate, audio_sample_width,
audio_iter_size, audio_block_size, audio_flush_size):
"""Helper command to test audio stream processing.
- Record 5 seconds of 16-bit samples at 16khz.
- Playback the recorded samples.
"""
end_time = time.time() + record_time
... | def main(record_time, audio_sample_rate, audio_sample_width,
audio_iter_size, audio_block_size, audio_flush_size):
"""Helper command to test audio stream processing.
- Record 5 seconds of 16-bit samples at 16khz.
- Playback the recorded samples.
"""
end_time = time.time() + record_time
... | [
"Helper",
"command",
"to",
"test",
"audio",
"stream",
"processing",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L372-L407 | [
"def",
"main",
"(",
"record_time",
",",
"audio_sample_rate",
",",
"audio_sample_width",
",",
"audio_iter_size",
",",
"audio_block_size",
",",
"audio_flush_size",
")",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"record_time",
"audio_device",
"=",
"... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | WaveSource.read | Read bytes from the stream and block until sample rate is achieved.
Args:
size: number of bytes to read from the stream. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def read(self, size):
"""Read bytes from the stream and block until sample rate is achieved.
Args:
size: number of bytes to read from the stream.
"""
now = time.time()
missing_dt = self._sleep_until - now
if missing_dt > 0:
time.sleep(missing_dt)
... | def read(self, size):
"""Read bytes from the stream and block until sample rate is achieved.
Args:
size: number of bytes to read from the stream.
"""
now = time.time()
missing_dt = self._sleep_until - now
if missing_dt > 0:
time.sleep(missing_dt)
... | [
"Read",
"bytes",
"from",
"the",
"stream",
"and",
"block",
"until",
"sample",
"rate",
"is",
"achieved",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L93-L110 | [
"def",
"read",
"(",
"self",
",",
"size",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"missing_dt",
"=",
"self",
".",
"_sleep_until",
"-",
"now",
"if",
"missing_dt",
">",
"0",
":",
"time",
".",
"sleep",
"(",
"missing_dt",
")",
"self",
".",
... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | WaveSource.close | Close the underlying stream. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def close(self):
"""Close the underlying stream."""
if self._wavep:
self._wavep.close()
self._fp.close() | def close(self):
"""Close the underlying stream."""
if self._wavep:
self._wavep.close()
self._fp.close() | [
"Close",
"the",
"underlying",
"stream",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L112-L116 | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wavep",
":",
"self",
".",
"_wavep",
".",
"close",
"(",
")",
"self",
".",
"_fp",
".",
"close",
"(",
")"
] | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | SoundDeviceStream.read | Read bytes from the stream. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def read(self, size):
"""Read bytes from the stream."""
buf, overflow = self._audio_stream.read(size)
if overflow:
logging.warning('SoundDeviceStream read overflow (%d, %d)',
size, len(buf))
return bytes(buf) | def read(self, size):
"""Read bytes from the stream."""
buf, overflow = self._audio_stream.read(size)
if overflow:
logging.warning('SoundDeviceStream read overflow (%d, %d)',
size, len(buf))
return bytes(buf) | [
"Read",
"bytes",
"from",
"the",
"stream",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L196-L202 | [
"def",
"read",
"(",
"self",
",",
"size",
")",
":",
"buf",
",",
"overflow",
"=",
"self",
".",
"_audio_stream",
".",
"read",
"(",
"size",
")",
"if",
"overflow",
":",
"logging",
".",
"warning",
"(",
"'SoundDeviceStream read overflow (%d, %d)'",
",",
"size",
"... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | SoundDeviceStream.write | Write bytes to the stream. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def write(self, buf):
"""Write bytes to the stream."""
underflow = self._audio_stream.write(buf)
if underflow:
logging.warning('SoundDeviceStream write underflow (size: %d)',
len(buf))
return len(buf) | def write(self, buf):
"""Write bytes to the stream."""
underflow = self._audio_stream.write(buf)
if underflow:
logging.warning('SoundDeviceStream write underflow (size: %d)',
len(buf))
return len(buf) | [
"Write",
"bytes",
"to",
"the",
"stream",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L204-L210 | [
"def",
"write",
"(",
"self",
",",
"buf",
")",
":",
"underflow",
"=",
"self",
".",
"_audio_stream",
".",
"write",
"(",
"buf",
")",
"if",
"underflow",
":",
"logging",
".",
"warning",
"(",
"'SoundDeviceStream write underflow (size: %d)'",
",",
"len",
"(",
"buf"... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | SoundDeviceStream.close | Close the underlying stream and audio interface. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def close(self):
"""Close the underlying stream and audio interface."""
if self._audio_stream:
self.stop()
self._audio_stream.close()
self._audio_stream = None | def close(self):
"""Close the underlying stream and audio interface."""
if self._audio_stream:
self.stop()
self._audio_stream.close()
self._audio_stream = None | [
"Close",
"the",
"underlying",
"stream",
"and",
"audio",
"interface",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L226-L231 | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_audio_stream",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"_audio_stream",
".",
"close",
"(",
")",
"self",
".",
"_audio_stream",
"=",
"None"
] | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | ConversationStream.start_recording | Start recording from the audio source. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def start_recording(self):
"""Start recording from the audio source."""
self._recording = True
self._stop_recording.clear()
self._source.start() | def start_recording(self):
"""Start recording from the audio source."""
self._recording = True
self._stop_recording.clear()
self._source.start() | [
"Start",
"recording",
"from",
"the",
"audio",
"source",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L275-L279 | [
"def",
"start_recording",
"(",
"self",
")",
":",
"self",
".",
"_recording",
"=",
"True",
"self",
".",
"_stop_recording",
".",
"clear",
"(",
")",
"self",
".",
"_source",
".",
"start",
"(",
")"
] | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | ConversationStream.stop_recording | Stop recording from the audio source. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def stop_recording(self):
"""Stop recording from the audio source."""
self._stop_recording.set()
with self._source_lock:
self._source.stop()
self._recording = False | def stop_recording(self):
"""Stop recording from the audio source."""
self._stop_recording.set()
with self._source_lock:
self._source.stop()
self._recording = False | [
"Stop",
"recording",
"from",
"the",
"audio",
"source",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L281-L286 | [
"def",
"stop_recording",
"(",
"self",
")",
":",
"self",
".",
"_stop_recording",
".",
"set",
"(",
")",
"with",
"self",
".",
"_source_lock",
":",
"self",
".",
"_source",
".",
"stop",
"(",
")",
"self",
".",
"_recording",
"=",
"False"
] | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | ConversationStream.stop_playback | Stop playback from the audio sink. | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def stop_playback(self):
"""Stop playback from the audio sink."""
self._sink.flush()
self._sink.stop()
self._playing = False | def stop_playback(self):
"""Stop playback from the audio sink."""
self._sink.flush()
self._sink.stop()
self._playing = False | [
"Stop",
"playback",
"from",
"the",
"audio",
"sink",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L293-L297 | [
"def",
"stop_playback",
"(",
"self",
")",
":",
"self",
".",
"_sink",
".",
"flush",
"(",
")",
"self",
".",
"_sink",
".",
"stop",
"(",
")",
"self",
".",
"_playing",
"=",
"False"
] | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | ConversationStream.write | Write bytes to the sink (if currently playing). | google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py | def write(self, buf):
"""Write bytes to the sink (if currently playing).
"""
buf = align_buf(buf, self._sample_width)
buf = normalize_audio_buffer(buf, self.volume_percentage)
return self._sink.write(buf) | def write(self, buf):
"""Write bytes to the sink (if currently playing).
"""
buf = align_buf(buf, self._sample_width)
buf = normalize_audio_buffer(buf, self.volume_percentage)
return self._sink.write(buf) | [
"Write",
"bytes",
"to",
"the",
"sink",
"(",
"if",
"currently",
"playing",
")",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L322-L327 | [
"def",
"write",
"(",
"self",
",",
"buf",
")",
":",
"buf",
"=",
"align_buf",
"(",
"buf",
",",
"self",
".",
"_sample_width",
")",
"buf",
"=",
"normalize_audio_buffer",
"(",
"buf",
",",
"self",
".",
"volume_percentage",
")",
"return",
"self",
".",
"_sink",
... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | SampleTextAssistant.assist | Send a text request to the Assistant and playback the response. | google-assistant-sdk/googlesamples/assistant/grpc/textinput.py | def assist(self, text_query):
"""Send a text request to the Assistant and playback the response.
"""
def iter_assist_requests():
config = embedded_assistant_pb2.AssistConfig(
audio_out_config=embedded_assistant_pb2.AudioOutConfig(
encoding='LINEAR1... | def assist(self, text_query):
"""Send a text request to the Assistant and playback the response.
"""
def iter_assist_requests():
config = embedded_assistant_pb2.AssistConfig(
audio_out_config=embedded_assistant_pb2.AudioOutConfig(
encoding='LINEAR1... | [
"Send",
"a",
"text",
"request",
"to",
"the",
"Assistant",
"and",
"playback",
"the",
"response",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/textinput.py#L80-L121 | [
"def",
"assist",
"(",
"self",
",",
"text_query",
")",
":",
"def",
"iter_assist_requests",
"(",
")",
":",
"config",
"=",
"embedded_assistant_pb2",
".",
"AssistConfig",
"(",
"audio_out_config",
"=",
"embedded_assistant_pb2",
".",
"AudioOutConfig",
"(",
"encoding",
"... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | main | Samples for the Google Assistant API.
Examples:
Run the sample with microphone input and speaker output:
$ python -m googlesamples.assistant
Run the sample with file input and speaker output:
$ python -m googlesamples.assistant -i <input file>
Run the sample with file input an... | google-assistant-sdk/googlesamples/assistant/grpc/pushtotalk.py | def main(api_endpoint, credentials, project_id,
device_model_id, device_id, device_config,
lang, display, verbose,
input_audio_file, output_audio_file,
audio_sample_rate, audio_sample_width,
audio_iter_size, audio_block_size, audio_flush_size,
grpc_deadline, once, *... | def main(api_endpoint, credentials, project_id,
device_model_id, device_id, device_config,
lang, display, verbose,
input_audio_file, output_audio_file,
audio_sample_rate, audio_sample_width,
audio_iter_size, audio_block_size, audio_flush_size,
grpc_deadline, once, *... | [
"Samples",
"for",
"the",
"Google",
"Assistant",
"API",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/pushtotalk.py#L294-L465 | [
"def",
"main",
"(",
"api_endpoint",
",",
"credentials",
",",
"project_id",
",",
"device_model_id",
",",
"device_id",
",",
"device_config",
",",
"lang",
",",
"display",
",",
"verbose",
",",
"input_audio_file",
",",
"output_audio_file",
",",
"audio_sample_rate",
","... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | SampleAssistant.assist | Send a voice request to the Assistant and playback the response.
Returns: True if conversation should continue. | google-assistant-sdk/googlesamples/assistant/grpc/pushtotalk.py | def assist(self):
"""Send a voice request to the Assistant and playback the response.
Returns: True if conversation should continue.
"""
continue_conversation = False
device_actions_futures = []
self.conversation_stream.start_recording()
logging.info('Recording ... | def assist(self):
"""Send a voice request to the Assistant and playback the response.
Returns: True if conversation should continue.
"""
continue_conversation = False
device_actions_futures = []
self.conversation_stream.start_recording()
logging.info('Recording ... | [
"Send",
"a",
"voice",
"request",
"to",
"the",
"Assistant",
"and",
"playback",
"the",
"response",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/pushtotalk.py#L119-L185 | [
"def",
"assist",
"(",
"self",
")",
":",
"continue_conversation",
"=",
"False",
"device_actions_futures",
"=",
"[",
"]",
"self",
".",
"conversation_stream",
".",
"start_recording",
"(",
")",
"logging",
".",
"info",
"(",
"'Recording audio request.'",
")",
"def",
"... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | SampleAssistant.gen_assist_requests | Yields: AssistRequest messages to send to the API. | google-assistant-sdk/googlesamples/assistant/grpc/pushtotalk.py | def gen_assist_requests(self):
"""Yields: AssistRequest messages to send to the API."""
config = embedded_assistant_pb2.AssistConfig(
audio_in_config=embedded_assistant_pb2.AudioInConfig(
encoding='LINEAR16',
sample_rate_hertz=self.conversation_stream.sample_... | def gen_assist_requests(self):
"""Yields: AssistRequest messages to send to the API."""
config = embedded_assistant_pb2.AssistConfig(
audio_in_config=embedded_assistant_pb2.AudioInConfig(
encoding='LINEAR16',
sample_rate_hertz=self.conversation_stream.sample_... | [
"Yields",
":",
"AssistRequest",
"messages",
"to",
"send",
"to",
"the",
"API",
"."
] | googlesamples/assistant-sdk-python | python | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/pushtotalk.py#L187-L219 | [
"def",
"gen_assist_requests",
"(",
"self",
")",
":",
"config",
"=",
"embedded_assistant_pb2",
".",
"AssistConfig",
"(",
"audio_in_config",
"=",
"embedded_assistant_pb2",
".",
"AudioInConfig",
"(",
"encoding",
"=",
"'LINEAR16'",
",",
"sample_rate_hertz",
"=",
"self",
... | 84995692f35be8e085de8dfa7032039a13ae3fab |
train | SoftImpute._svd_step | Returns reconstructed X from low-rank thresholded SVD and
the rank achieved. | fancyimpute/soft_impute.py | def _svd_step(self, X, shrinkage_value, max_rank=None):
"""
Returns reconstructed X from low-rank thresholded SVD and
the rank achieved.
"""
if max_rank:
# if we have a max rank then perform the faster randomized SVD
(U, s, V) = randomized_svd(
... | def _svd_step(self, X, shrinkage_value, max_rank=None):
"""
Returns reconstructed X from low-rank thresholded SVD and
the rank achieved.
"""
if max_rank:
# if we have a max rank then perform the faster randomized SVD
(U, s, V) = randomized_svd(
... | [
"Returns",
"reconstructed",
"X",
"from",
"low",
"-",
"rank",
"thresholded",
"SVD",
"and",
"the",
"rank",
"achieved",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/soft_impute.py#L109-L133 | [
"def",
"_svd_step",
"(",
"self",
",",
"X",
",",
"shrinkage_value",
",",
"max_rank",
"=",
"None",
")",
":",
"if",
"max_rank",
":",
"# if we have a max rank then perform the faster randomized SVD",
"(",
"U",
",",
"s",
",",
"V",
")",
"=",
"randomized_svd",
"(",
"... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | Solver.fill | Parameters
----------
X : np.array
Data array containing NaN entries
missing_mask : np.array
Boolean array indicating where NaN entries are
fill_method : str
"zero": fill missing entries with zeros
"mean": fill with column means
... | fancyimpute/solver.py | def fill(
self,
X,
missing_mask,
fill_method=None,
inplace=False):
"""
Parameters
----------
X : np.array
Data array containing NaN entries
missing_mask : np.array
Boolean array indicating where ... | def fill(
self,
X,
missing_mask,
fill_method=None,
inplace=False):
"""
Parameters
----------
X : np.array
Data array containing NaN entries
missing_mask : np.array
Boolean array indicating where ... | [
"Parameters",
"----------",
"X",
":",
"np",
".",
"array",
"Data",
"array",
"containing",
"NaN",
"entries"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/solver.py#L74-L123 | [
"def",
"fill",
"(",
"self",
",",
"X",
",",
"missing_mask",
",",
"fill_method",
"=",
"None",
",",
"inplace",
"=",
"False",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
",",
"force_all_finite",
"=",
"False",
")",
"if",
"not",
"inplace",
":",
"X",
"=",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | Solver.prepare_input_data | Check to make sure that the input matrix and its mask of missing
values are valid. Returns X and missing mask. | fancyimpute/solver.py | def prepare_input_data(self, X):
"""
Check to make sure that the input matrix and its mask of missing
values are valid. Returns X and missing mask.
"""
X = check_array(X, force_all_finite=False)
if X.dtype != "f" and X.dtype != "d":
X = X.astype(float)
... | def prepare_input_data(self, X):
"""
Check to make sure that the input matrix and its mask of missing
values are valid. Returns X and missing mask.
"""
X = check_array(X, force_all_finite=False)
if X.dtype != "f" and X.dtype != "d":
X = X.astype(float)
... | [
"Check",
"to",
"make",
"sure",
"that",
"the",
"input",
"matrix",
"and",
"its",
"mask",
"of",
"missing",
"values",
"are",
"valid",
".",
"Returns",
"X",
"and",
"missing",
"mask",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/solver.py#L125-L137 | [
"def",
"prepare_input_data",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
",",
"force_all_finite",
"=",
"False",
")",
"if",
"X",
".",
"dtype",
"!=",
"\"f\"",
"and",
"X",
".",
"dtype",
"!=",
"\"d\"",
":",
"X",
"=",
"X",
".",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | Solver.clip | Clip values to fall within any global or column-wise min/max constraints | fancyimpute/solver.py | def clip(self, X):
"""
Clip values to fall within any global or column-wise min/max constraints
"""
X = np.asarray(X)
if self.min_value is not None:
X[X < self.min_value] = self.min_value
if self.max_value is not None:
X[X > self.max_value] = self.... | def clip(self, X):
"""
Clip values to fall within any global or column-wise min/max constraints
"""
X = np.asarray(X)
if self.min_value is not None:
X[X < self.min_value] = self.min_value
if self.max_value is not None:
X[X > self.max_value] = self.... | [
"Clip",
"values",
"to",
"fall",
"within",
"any",
"global",
"or",
"column",
"-",
"wise",
"min",
"/",
"max",
"constraints"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/solver.py#L139-L148 | [
"def",
"clip",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"np",
".",
"asarray",
"(",
"X",
")",
"if",
"self",
".",
"min_value",
"is",
"not",
"None",
":",
"X",
"[",
"X",
"<",
"self",
".",
"min_value",
"]",
"=",
"self",
".",
"min_value",
"if",
"... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | Solver.project_result | First undo normalization and then clip to the user-specified min/max
range. | fancyimpute/solver.py | def project_result(self, X):
"""
First undo normalization and then clip to the user-specified min/max
range.
"""
X = np.asarray(X)
if self.normalizer is not None:
X = self.normalizer.inverse_transform(X)
return self.clip(X) | def project_result(self, X):
"""
First undo normalization and then clip to the user-specified min/max
range.
"""
X = np.asarray(X)
if self.normalizer is not None:
X = self.normalizer.inverse_transform(X)
return self.clip(X) | [
"First",
"undo",
"normalization",
"and",
"then",
"clip",
"to",
"the",
"user",
"-",
"specified",
"min",
"/",
"max",
"range",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/solver.py#L150-L158 | [
"def",
"project_result",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"np",
".",
"asarray",
"(",
"X",
")",
"if",
"self",
".",
"normalizer",
"is",
"not",
"None",
":",
"X",
"=",
"self",
".",
"normalizer",
".",
"inverse_transform",
"(",
"X",
")",
"retur... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | Solver.fit_transform | Fit the imputer and then transform input `X`
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
on new `X_test`. | fancyimpute/solver.py | def fit_transform(self, X, y=None):
"""
Fit the imputer and then transform input `X`
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
... | def fit_transform(self, X, y=None):
"""
Fit the imputer and then transform input `X`
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
... | [
"Fit",
"the",
"imputer",
"and",
"then",
"transform",
"input",
"X"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/solver.py#L168-L198 | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"X_original",
",",
"missing_mask",
"=",
"self",
".",
"prepare_input_data",
"(",
"X",
")",
"observed_mask",
"=",
"~",
"missing_mask",
"X",
"=",
"X_original",
".",
"copy",
"(",... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | Solver.transform | Transform input `X`.
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
on new `X_test`. | fancyimpute/solver.py | def transform(self, X, y=None):
"""
Transform input `X`.
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
on new `X_test`.
... | def transform(self, X, y=None):
"""
Transform input `X`.
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
on new `X_test`.
... | [
"Transform",
"input",
"X",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/solver.py#L215-L228 | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"raise",
"ValueError",
"(",
"\"%s.transform not implemented! This imputation algorithm likely \"",
"\"doesn't support inductive mode. Only %s.fit_transform is \"",
"\"supported at this time.\"",
"%",
"(... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | rescale_pixel_values | Rescale the range of values in images to be between [0, 1] | experiments/complete_faces.py | def rescale_pixel_values(images, order="C"):
"""
Rescale the range of values in images to be between [0, 1]
"""
images = np.asarray(images, order=order).astype("float32")
images -= images.min()
images /= images.max()
return images | def rescale_pixel_values(images, order="C"):
"""
Rescale the range of values in images to be between [0, 1]
"""
images = np.asarray(images, order=order).astype("float32")
images -= images.min()
images /= images.max()
return images | [
"Rescale",
"the",
"range",
"of",
"values",
"in",
"images",
"to",
"be",
"between",
"[",
"0",
"1",
"]"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/experiments/complete_faces.py#L43-L50 | [
"def",
"rescale_pixel_values",
"(",
"images",
",",
"order",
"=",
"\"C\"",
")",
":",
"images",
"=",
"np",
".",
"asarray",
"(",
"images",
",",
"order",
"=",
"order",
")",
".",
"astype",
"(",
"\"float32\"",
")",
"images",
"-=",
"images",
".",
"min",
"(",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | ResultsTable.sorted_errors | Generator for (rank, name, MSE, MAE) sorted by increasing MAE | experiments/complete_faces.py | def sorted_errors(self):
"""
Generator for (rank, name, MSE, MAE) sorted by increasing MAE
"""
for i, (name, mae) in enumerate(
sorted(self.mae_dict.items(), key=lambda x: x[1])):
yield(i + 1, name, self.mse_dict[name], self.mae_dict[name],) | def sorted_errors(self):
"""
Generator for (rank, name, MSE, MAE) sorted by increasing MAE
"""
for i, (name, mae) in enumerate(
sorted(self.mae_dict.items(), key=lambda x: x[1])):
yield(i + 1, name, self.mse_dict[name], self.mae_dict[name],) | [
"Generator",
"for",
"(",
"rank",
"name",
"MSE",
"MAE",
")",
"sorted",
"by",
"increasing",
"MAE"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/experiments/complete_faces.py#L190-L196 | [
"def",
"sorted_errors",
"(",
"self",
")",
":",
"for",
"i",
",",
"(",
"name",
",",
"mae",
")",
"in",
"enumerate",
"(",
"sorted",
"(",
"self",
".",
"mae_dict",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | is_scalar_nan | Tests if x is NaN
This function is meant to overcome the issue that np.isnan does not allow
non-numerical types as input, and that np.nan is not np.float('nan').
Parameters
----------
x : any type
Returns
-------
boolean
Examples
--------
>>> is_scalar_nan(np.nan)
True
... | fancyimpute/iterative_imputer.py | def is_scalar_nan(x):
"""Tests if x is NaN
This function is meant to overcome the issue that np.isnan does not allow
non-numerical types as input, and that np.nan is not np.float('nan').
Parameters
----------
x : any type
Returns
-------
boolean
Examples
--------
>>> is_s... | def is_scalar_nan(x):
"""Tests if x is NaN
This function is meant to overcome the issue that np.isnan does not allow
non-numerical types as input, and that np.nan is not np.float('nan').
Parameters
----------
x : any type
Returns
-------
boolean
Examples
--------
>>> is_s... | [
"Tests",
"if",
"x",
"is",
"NaN",
"This",
"function",
"is",
"meant",
"to",
"overcome",
"the",
"issue",
"that",
"np",
".",
"isnan",
"does",
"not",
"allow",
"non",
"-",
"numerical",
"types",
"as",
"input",
"and",
"that",
"np",
".",
"nan",
"is",
"not",
"... | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L59-L87 | [
"def",
"is_scalar_nan",
"(",
"x",
")",
":",
"# convert from numpy.bool_ to python bool to ensure that testing",
"# is_scalar_nan(x) is True does not fail.",
"# Redondant np.floating is needed because numbers can't match np.float32",
"# in python 2.",
"return",
"bool",
"(",
"isinstance",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | _get_mask | Compute the boolean mask X == missing_values. | fancyimpute/iterative_imputer.py | def _get_mask(X, value_to_mask):
"""Compute the boolean mask X == missing_values."""
if is_scalar_nan(value_to_mask):
if X.dtype.kind == "f":
return np.isnan(X)
elif X.dtype.kind in ("i", "u"):
# can't have NaNs in integer array.
return np.zeros(X.shape, dtype... | def _get_mask(X, value_to_mask):
"""Compute the boolean mask X == missing_values."""
if is_scalar_nan(value_to_mask):
if X.dtype.kind == "f":
return np.isnan(X)
elif X.dtype.kind in ("i", "u"):
# can't have NaNs in integer array.
return np.zeros(X.shape, dtype... | [
"Compute",
"the",
"boolean",
"mask",
"X",
"==",
"missing_values",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L99-L113 | [
"def",
"_get_mask",
"(",
"X",
",",
"value_to_mask",
")",
":",
"if",
"is_scalar_nan",
"(",
"value_to_mask",
")",
":",
"if",
"X",
".",
"dtype",
".",
"kind",
"==",
"\"f\"",
":",
"return",
"np",
".",
"isnan",
"(",
"X",
")",
"elif",
"X",
".",
"dtype",
"... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | _most_frequent | Compute the most frequent value in a 1d array extended with
[extra_value] * n_repeat, where extra_value is assumed to be not part
of the array. | fancyimpute/iterative_imputer.py | def _most_frequent(array, extra_value, n_repeat):
"""Compute the most frequent value in a 1d array extended with
[extra_value] * n_repeat, where extra_value is assumed to be not part
of the array."""
# Compute the most frequent value in array only
if array.size > 0:
with warnings.catch... | def _most_frequent(array, extra_value, n_repeat):
"""Compute the most frequent value in a 1d array extended with
[extra_value] * n_repeat, where extra_value is assumed to be not part
of the array."""
# Compute the most frequent value in array only
if array.size > 0:
with warnings.catch... | [
"Compute",
"the",
"most",
"frequent",
"value",
"in",
"a",
"1d",
"array",
"extended",
"with",
"[",
"extra_value",
"]",
"*",
"n_repeat",
"where",
"extra_value",
"is",
"assumed",
"to",
"be",
"not",
"part",
"of",
"the",
"array",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L116-L147 | [
"def",
"_most_frequent",
"(",
"array",
",",
"extra_value",
",",
"n_repeat",
")",
":",
"# Compute the most frequent value in array only",
"if",
"array",
".",
"size",
">",
"0",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"# stats.mode raises a warni... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | _SimpleImputer.fit | Fit the imputer on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Input data, where ``n_samples`` is the number of samples and
``n_features`` is the number of features.
Returns
-------
self : _SimpleImpute... | fancyimpute/iterative_imputer.py | def fit(self, X, y=None):
"""Fit the imputer on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Input data, where ``n_samples`` is the number of samples and
``n_features`` is the number of features.
Returns
... | def fit(self, X, y=None):
"""Fit the imputer on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Input data, where ``n_samples`` is the number of samples and
``n_features`` is the number of features.
Returns
... | [
"Fit",
"the",
"imputer",
"on",
"X",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L256-L307 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"X",
"=",
"self",
".",
"_validate_input",
"(",
"X",
")",
"# default fill_value is 0 for numerical input and \"missing_value\"",
"# otherwise",
"if",
"self",
".",
"fill_value",
"is",
"None",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | _SimpleImputer._sparse_fit | Fit the transformer on sparse data. | fancyimpute/iterative_imputer.py | def _sparse_fit(self, X, strategy, missing_values, fill_value):
"""Fit the transformer on sparse data."""
mask_data = _get_mask(X.data, missing_values)
n_implicit_zeros = X.shape[0] - np.diff(X.indptr)
statistics = np.empty(X.shape[1])
if strategy == "constant":
# f... | def _sparse_fit(self, X, strategy, missing_values, fill_value):
"""Fit the transformer on sparse data."""
mask_data = _get_mask(X.data, missing_values)
n_implicit_zeros = X.shape[0] - np.diff(X.indptr)
statistics = np.empty(X.shape[1])
if strategy == "constant":
# f... | [
"Fit",
"the",
"transformer",
"on",
"sparse",
"data",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L309-L345 | [
"def",
"_sparse_fit",
"(",
"self",
",",
"X",
",",
"strategy",
",",
"missing_values",
",",
"fill_value",
")",
":",
"mask_data",
"=",
"_get_mask",
"(",
"X",
".",
"data",
",",
"missing_values",
")",
"n_implicit_zeros",
"=",
"X",
".",
"shape",
"[",
"0",
"]",... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | _SimpleImputer._dense_fit | Fit the transformer on dense data. | fancyimpute/iterative_imputer.py | def _dense_fit(self, X, strategy, missing_values, fill_value):
"""Fit the transformer on dense data."""
mask = _get_mask(X, missing_values)
masked_X = ma.masked_array(X, mask=mask)
# Mean
if strategy == "mean":
mean_masked = np.ma.mean(masked_X, axis=0)
#... | def _dense_fit(self, X, strategy, missing_values, fill_value):
"""Fit the transformer on dense data."""
mask = _get_mask(X, missing_values)
masked_X = ma.masked_array(X, mask=mask)
# Mean
if strategy == "mean":
mean_masked = np.ma.mean(masked_X, axis=0)
#... | [
"Fit",
"the",
"transformer",
"on",
"dense",
"data",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L347-L397 | [
"def",
"_dense_fit",
"(",
"self",
",",
"X",
",",
"strategy",
",",
"missing_values",
",",
"fill_value",
")",
":",
"mask",
"=",
"_get_mask",
"(",
"X",
",",
"missing_values",
")",
"masked_X",
"=",
"ma",
".",
"masked_array",
"(",
"X",
",",
"mask",
"=",
"ma... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | _SimpleImputer.transform | Impute all missing values in X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The input data to complete. | fancyimpute/iterative_imputer.py | def transform(self, X):
"""Impute all missing values in X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The input data to complete.
"""
check_is_fitted(self, 'statistics_')
X = self._validate_input(X)
... | def transform(self, X):
"""Impute all missing values in X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The input data to complete.
"""
check_is_fitted(self, 'statistics_')
X = self._validate_input(X)
... | [
"Impute",
"all",
"missing",
"values",
"in",
"X",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L399-L455 | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"'statistics_'",
")",
"X",
"=",
"self",
".",
"_validate_input",
"(",
"X",
")",
"statistics",
"=",
"self",
".",
"statistics_",
"if",
"X",
".",
"shape",
"[",
"1",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | IterativeImputer._impute_one_feature | Impute a single feature from the others provided.
This function predicts the missing values of one of the features using
the current estimates of all the other features. The ``predictor`` must
support ``return_std=True`` in its ``predict`` method for this function
to work.
Para... | fancyimpute/iterative_imputer.py | def _impute_one_feature(self,
X_filled,
mask_missing_values,
feat_idx,
neighbor_feat_idx,
predictor=None,
fit_mode=True):
"""Impute a single fea... | def _impute_one_feature(self,
X_filled,
mask_missing_values,
feat_idx,
neighbor_feat_idx,
predictor=None,
fit_mode=True):
"""Impute a single fea... | [
"Impute",
"a",
"single",
"feature",
"from",
"the",
"others",
"provided",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L611-L696 | [
"def",
"_impute_one_feature",
"(",
"self",
",",
"X_filled",
",",
"mask_missing_values",
",",
"feat_idx",
",",
"neighbor_feat_idx",
",",
"predictor",
"=",
"None",
",",
"fit_mode",
"=",
"True",
")",
":",
"# if nothing is missing, just return the default",
"# (should not h... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | IterativeImputer._get_neighbor_feat_idx | Get a list of other features to predict ``feat_idx``.
If self.n_nearest_features is less than or equal to the total
number of features, then use a probability proportional to the absolute
correlation between ``feat_idx`` and each other feature to randomly
choose a subsample of the other... | fancyimpute/iterative_imputer.py | def _get_neighbor_feat_idx(self,
n_features,
feat_idx,
abs_corr_mat):
"""Get a list of other features to predict ``feat_idx``.
If self.n_nearest_features is less than or equal to the total
number of fea... | def _get_neighbor_feat_idx(self,
n_features,
feat_idx,
abs_corr_mat):
"""Get a list of other features to predict ``feat_idx``.
If self.n_nearest_features is less than or equal to the total
number of fea... | [
"Get",
"a",
"list",
"of",
"other",
"features",
"to",
"predict",
"feat_idx",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L698-L736 | [
"def",
"_get_neighbor_feat_idx",
"(",
"self",
",",
"n_features",
",",
"feat_idx",
",",
"abs_corr_mat",
")",
":",
"if",
"(",
"self",
".",
"n_nearest_features",
"is",
"not",
"None",
"and",
"self",
".",
"n_nearest_features",
"<",
"n_features",
")",
":",
"p",
"=... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | IterativeImputer._get_ordered_idx | Decide in what order we will update the features.
As a homage to the MICE R package, we will have 4 main options of
how to order the updates, and use a random order if anything else
is specified.
Also, this function skips features which have no missing values.
Parameters
... | fancyimpute/iterative_imputer.py | def _get_ordered_idx(self, mask_missing_values):
"""Decide in what order we will update the features.
As a homage to the MICE R package, we will have 4 main options of
how to order the updates, and use a random order if anything else
is specified.
Also, this function skips feat... | def _get_ordered_idx(self, mask_missing_values):
"""Decide in what order we will update the features.
As a homage to the MICE R package, we will have 4 main options of
how to order the updates, and use a random order if anything else
is specified.
Also, this function skips feat... | [
"Decide",
"in",
"what",
"order",
"we",
"will",
"update",
"the",
"features",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L738-L780 | [
"def",
"_get_ordered_idx",
"(",
"self",
",",
"mask_missing_values",
")",
":",
"frac_of_missing_values",
"=",
"mask_missing_values",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"missing_values_idx",
"=",
"np",
".",
"nonzero",
"(",
"frac_of_missing_values",
")",
"[",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | IterativeImputer._get_abs_corr_mat | Get absolute correlation matrix between features.
Parameters
----------
X_filled : ndarray, shape (n_samples, n_features)
Input data with the most recent imputations.
tolerance : float, optional (default=1e-6)
``abs_corr_mat`` can have nans, which will be replac... | fancyimpute/iterative_imputer.py | def _get_abs_corr_mat(self, X_filled, tolerance=1e-6):
"""Get absolute correlation matrix between features.
Parameters
----------
X_filled : ndarray, shape (n_samples, n_features)
Input data with the most recent imputations.
tolerance : float, optional (default=1e-6... | def _get_abs_corr_mat(self, X_filled, tolerance=1e-6):
"""Get absolute correlation matrix between features.
Parameters
----------
X_filled : ndarray, shape (n_samples, n_features)
Input data with the most recent imputations.
tolerance : float, optional (default=1e-6... | [
"Get",
"absolute",
"correlation",
"matrix",
"between",
"features",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L782-L815 | [
"def",
"_get_abs_corr_mat",
"(",
"self",
",",
"X_filled",
",",
"tolerance",
"=",
"1e-6",
")",
":",
"n_features",
"=",
"X_filled",
".",
"shape",
"[",
"1",
"]",
"if",
"(",
"self",
".",
"n_nearest_features",
"is",
"None",
"or",
"self",
".",
"n_nearest_feature... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | IterativeImputer._initial_imputation | Perform initial imputation for input X.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
Returns
-------
Xt : ndarray, shape (n_sam... | fancyimpute/iterative_imputer.py | def _initial_imputation(self, X):
"""Perform initial imputation for input X.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
Returns
... | def _initial_imputation(self, X):
"""Perform initial imputation for input X.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
Returns
... | [
"Perform",
"initial",
"imputation",
"for",
"input",
"X",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L817-L863 | [
"def",
"_initial_imputation",
"(",
"self",
",",
"X",
")",
":",
"# TODO: change False to \"allow-nan\"",
"if",
"is_scalar_nan",
"(",
"self",
".",
"missing_values",
")",
":",
"force_all_finite",
"=",
"False",
"# \"allow-nan\"",
"else",
":",
"force_all_finite",
"=",
"T... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | IterativeImputer.fit_transform | Fits the imputer on X and return the transformed X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
y : ignored.
Returns
-----... | fancyimpute/iterative_imputer.py | def fit_transform(self, X, y=None):
"""Fits the imputer on X and return the transformed X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
... | def fit_transform(self, X, y=None):
"""Fits the imputer on X and return the transformed X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
... | [
"Fits",
"the",
"imputer",
"on",
"X",
"and",
"return",
"the",
"transformed",
"X",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L865-L950 | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"random_state_",
"=",
"getattr",
"(",
"self",
",",
"\"random_state_\"",
",",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
")",
"if",
"self",
".",... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | IterativeImputer.transform | Imputes all missing values in X.
Note that this is stochastic, and that if random_state is not fixed,
repeated calls, or permuted input, will yield different results.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
The input data to complete.
... | fancyimpute/iterative_imputer.py | def transform(self, X):
"""Imputes all missing values in X.
Note that this is stochastic, and that if random_state is not fixed,
repeated calls, or permuted input, will yield different results.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
... | def transform(self, X):
"""Imputes all missing values in X.
Note that this is stochastic, and that if random_state is not fixed,
repeated calls, or permuted input, will yield different results.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
... | [
"Imputes",
"all",
"missing",
"values",
"in",
"X",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L952-L998 | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"'initial_imputer_'",
")",
"X",
",",
"Xt",
",",
"mask_missing_values",
"=",
"self",
".",
"_initial_imputation",
"(",
"X",
")",
"if",
"self",
".",
"n_iter",
"==",
"0... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | NuclearNormMinimization._constraints | Parameters
----------
X : np.array
Data matrix with missing values filled in
missing_mask : np.array
Boolean array indicating where missing values were
S : cvxpy.Variable
Representation of solution variable | fancyimpute/nuclear_norm_minimization.py | def _constraints(self, X, missing_mask, S, error_tolerance):
"""
Parameters
----------
X : np.array
Data matrix with missing values filled in
missing_mask : np.array
Boolean array indicating where missing values were
S : cvxpy.Variable
... | def _constraints(self, X, missing_mask, S, error_tolerance):
"""
Parameters
----------
X : np.array
Data matrix with missing values filled in
missing_mask : np.array
Boolean array indicating where missing values were
S : cvxpy.Variable
... | [
"Parameters",
"----------",
"X",
":",
"np",
".",
"array",
"Data",
"matrix",
"with",
"missing",
"values",
"filled",
"in"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/nuclear_norm_minimization.py#L67-L95 | [
"def",
"_constraints",
"(",
"self",
",",
"X",
",",
"missing_mask",
",",
"S",
",",
"error_tolerance",
")",
":",
"ok_mask",
"=",
"~",
"missing_mask",
"masked_X",
"=",
"cvxpy",
".",
"multiply",
"(",
"ok_mask",
",",
"X",
")",
"masked_S",
"=",
"cvxpy",
".",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | NuclearNormMinimization._create_objective | Parameters
----------
m, n : int
Dimensions that of solution matrix
Returns the objective function and a variable representing the
solution to the convex optimization problem. | fancyimpute/nuclear_norm_minimization.py | def _create_objective(self, m, n):
"""
Parameters
----------
m, n : int
Dimensions that of solution matrix
Returns the objective function and a variable representing the
solution to the convex optimization problem.
"""
# S is the completed matr... | def _create_objective(self, m, n):
"""
Parameters
----------
m, n : int
Dimensions that of solution matrix
Returns the objective function and a variable representing the
solution to the convex optimization problem.
"""
# S is the completed matr... | [
"Parameters",
"----------",
"m",
"n",
":",
"int",
"Dimensions",
"that",
"of",
"solution",
"matrix",
"Returns",
"the",
"objective",
"function",
"and",
"a",
"variable",
"representing",
"the",
"solution",
"to",
"the",
"convex",
"optimization",
"problem",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/nuclear_norm_minimization.py#L97-L111 | [
"def",
"_create_objective",
"(",
"self",
",",
"m",
",",
"n",
")",
":",
"# S is the completed matrix",
"shape",
"=",
"(",
"m",
",",
"n",
")",
"S",
"=",
"cvxpy",
".",
"Variable",
"(",
"shape",
",",
"name",
"=",
"\"S\"",
")",
"norm",
"=",
"cvxpy",
".",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | import_from | usage example:
grid = import_from('sklearn.model_selection', 'GridSearchCV')
is equivalent to:
from sklearn.model_selection import GridSearchV as grid | fancyimpute/common.py | def import_from(module, name):
'''
usage example:
grid = import_from('sklearn.model_selection', 'GridSearchCV')
is equivalent to:
from sklearn.model_selection import GridSearchV as grid
'''
module = importlib.import_module(module)
return getattr(module, name) | def import_from(module, name):
'''
usage example:
grid = import_from('sklearn.model_selection', 'GridSearchCV')
is equivalent to:
from sklearn.model_selection import GridSearchV as grid
'''
module = importlib.import_module(module)
return getattr(module, name) | [
"usage",
"example",
":",
"grid",
"=",
"import_from",
"(",
"sklearn",
".",
"model_selection",
"GridSearchCV",
")",
"is",
"equivalent",
"to",
":",
"from",
"sklearn",
".",
"model_selection",
"import",
"GridSearchV",
"as",
"grid"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/common.py#L21-L29 | [
"def",
"import_from",
"(",
"module",
",",
"name",
")",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module",
")",
"return",
"getattr",
"(",
"module",
",",
"name",
")"
] | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | choose_solution_using_percentiles | It's tricky to pick a single matrix out of all the candidate
solutions with differing shrinkage thresholds.
Our heuristic is to pick the matrix whose percentiles match best
between the missing and observed data. | fancyimpute/common.py | def choose_solution_using_percentiles(
X_original,
solutions,
parameters=None,
verbose=False,
percentiles=list(range(10, 100, 10))):
"""
It's tricky to pick a single matrix out of all the candidate
solutions with differing shrinkage thresholds.
Our heuristic is to... | def choose_solution_using_percentiles(
X_original,
solutions,
parameters=None,
verbose=False,
percentiles=list(range(10, 100, 10))):
"""
It's tricky to pick a single matrix out of all the candidate
solutions with differing shrinkage thresholds.
Our heuristic is to... | [
"It",
"s",
"tricky",
"to",
"pick",
"a",
"single",
"matrix",
"out",
"of",
"all",
"the",
"candidate",
"solutions",
"with",
"differing",
"shrinkage",
"thresholds",
".",
"Our",
"heuristic",
"is",
"to",
"pick",
"the",
"matrix",
"whose",
"percentiles",
"match",
"b... | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/common.py#L58-L105 | [
"def",
"choose_solution_using_percentiles",
"(",
"X_original",
",",
"solutions",
",",
"parameters",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"percentiles",
"=",
"list",
"(",
"range",
"(",
"10",
",",
"100",
",",
"10",
")",
")",
")",
":",
"missing_mas... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | BiScaler.estimate_row_means | row_center[i] =
sum{j in observed[i, :]}{
(1 / column_scale[j]) * (X[i, j] - column_center[j])
}
------------------------------------------------------------
sum{j in observed[i, :]}{1 / column_scale[j]} | fancyimpute/scaler.py | def estimate_row_means(
self,
X,
observed,
column_means,
column_scales):
"""
row_center[i] =
sum{j in observed[i, :]}{
(1 / column_scale[j]) * (X[i, j] - column_center[j])
}
----------------------------------... | def estimate_row_means(
self,
X,
observed,
column_means,
column_scales):
"""
row_center[i] =
sum{j in observed[i, :]}{
(1 / column_scale[j]) * (X[i, j] - column_center[j])
}
----------------------------------... | [
"row_center",
"[",
"i",
"]",
"=",
"sum",
"{",
"j",
"in",
"observed",
"[",
"i",
":",
"]",
"}",
"{",
"(",
"1",
"/",
"column_scale",
"[",
"j",
"]",
")",
"*",
"(",
"X",
"[",
"i",
"j",
"]",
"-",
"column_center",
"[",
"j",
"]",
")",
"}",
"-------... | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/scaler.py#L100-L130 | [
"def",
"estimate_row_means",
"(",
"self",
",",
"X",
",",
"observed",
",",
"column_means",
",",
"column_scales",
")",
":",
"n_rows",
",",
"n_cols",
"=",
"X",
".",
"shape",
"column_means",
"=",
"np",
".",
"asarray",
"(",
"column_means",
")",
"if",
"len",
"... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | BiScaler.estimate_column_means | column_center[j] =
sum{i in observed[:, j]}{
(1 / row_scale[i]) * (X[i, j]) - row_center[i])
}
------------------------------------------------------------
sum{i in observed[:, j]}{1 / row_scale[i]} | fancyimpute/scaler.py | def estimate_column_means(
self,
X,
observed,
row_means,
row_scales):
"""
column_center[j] =
sum{i in observed[:, j]}{
(1 / row_scale[i]) * (X[i, j]) - row_center[i])
}
---------------------------------------... | def estimate_column_means(
self,
X,
observed,
row_means,
row_scales):
"""
column_center[j] =
sum{i in observed[:, j]}{
(1 / row_scale[i]) * (X[i, j]) - row_center[i])
}
---------------------------------------... | [
"column_center",
"[",
"j",
"]",
"=",
"sum",
"{",
"i",
"in",
"observed",
"[",
":",
"j",
"]",
"}",
"{",
"(",
"1",
"/",
"row_scale",
"[",
"i",
"]",
")",
"*",
"(",
"X",
"[",
"i",
"j",
"]",
")",
"-",
"row_center",
"[",
"i",
"]",
")",
"}",
"---... | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/scaler.py#L132-L162 | [
"def",
"estimate_column_means",
"(",
"self",
",",
"X",
",",
"observed",
",",
"row_means",
",",
"row_scales",
")",
":",
"n_rows",
",",
"n_cols",
"=",
"X",
".",
"shape",
"row_means",
"=",
"np",
".",
"asarray",
"(",
"row_means",
")",
"if",
"len",
"(",
"ro... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | BiScaler.estimate_row_scales | row_scale[i]**2 =
mean{j in observed[i, :]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
--------------------------------------------------
column_scale[j] ** 2
} | fancyimpute/scaler.py | def estimate_row_scales(
self,
X_centered,
column_scales):
"""
row_scale[i]**2 =
mean{j in observed[i, :]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
--------------------------------------------------
col... | def estimate_row_scales(
self,
X_centered,
column_scales):
"""
row_scale[i]**2 =
mean{j in observed[i, :]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
--------------------------------------------------
col... | [
"row_scale",
"[",
"i",
"]",
"**",
"2",
"=",
"mean",
"{",
"j",
"in",
"observed",
"[",
"i",
":",
"]",
"}",
"{",
"(",
"X",
"[",
"i",
"j",
"]",
"-",
"row_center",
"[",
"i",
"]",
"-",
"column_center",
"[",
"j",
"]",
")",
"**",
"2",
"--------------... | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/scaler.py#L188-L212 | [
"def",
"estimate_row_scales",
"(",
"self",
",",
"X_centered",
",",
"column_scales",
")",
":",
"n_rows",
",",
"n_cols",
"=",
"X_centered",
".",
"shape",
"column_scales",
"=",
"np",
".",
"asarray",
"(",
"column_scales",
")",
"if",
"len",
"(",
"column_scales",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | BiScaler.estimate_column_scales | column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
row_scale[i] ** 2
} | fancyimpute/scaler.py | def estimate_column_scales(
self,
X_centered,
row_scales):
"""
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
... | def estimate_column_scales(
self,
X_centered,
row_scales):
"""
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
... | [
"column_scale",
"[",
"j",
"]",
"**",
"2",
"=",
"mean",
"{",
"i",
"in",
"observed",
"[",
":",
"j",
"]",
"}",
"{",
"(",
"X",
"[",
"i",
"j",
"]",
"-",
"row_center",
"[",
"i",
"]",
"-",
"column_center",
"[",
"j",
"]",
")",
"**",
"2",
"-----------... | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/scaler.py#L214-L240 | [
"def",
"estimate_column_scales",
"(",
"self",
",",
"X_centered",
",",
"row_scales",
")",
":",
"n_rows",
",",
"n_cols",
"=",
"X_centered",
".",
"shape",
"row_scales",
"=",
"np",
".",
"asarray",
"(",
"row_scales",
")",
"if",
"len",
"(",
"row_scales",
")",
"!... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | SimilarityWeightedAveraging.jacard_similarity_from_nested_dicts | Compute the continuous Jacard similarity between all pairs
of keys in dictionary-of-dictionaries given as an input.
Returns three element tuple:
- similarity dictionary: (key, key) -> float
- overlap count dictionary: key -> key -> int
- weight dictionary: key -> key... | fancyimpute/similarity_weighted_averaging.py | def jacard_similarity_from_nested_dicts(self, nested_dictionaries):
"""
Compute the continuous Jacard similarity between all pairs
of keys in dictionary-of-dictionaries given as an input.
Returns three element tuple:
- similarity dictionary: (key, key) -> float
-... | def jacard_similarity_from_nested_dicts(self, nested_dictionaries):
"""
Compute the continuous Jacard similarity between all pairs
of keys in dictionary-of-dictionaries given as an input.
Returns three element tuple:
- similarity dictionary: (key, key) -> float
-... | [
"Compute",
"the",
"continuous",
"Jacard",
"similarity",
"between",
"all",
"pairs",
"of",
"keys",
"in",
"dictionary",
"-",
"of",
"-",
"dictionaries",
"given",
"as",
"an",
"input",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/similarity_weighted_averaging.py#L76-L111 | [
"def",
"jacard_similarity_from_nested_dicts",
"(",
"self",
",",
"nested_dictionaries",
")",
":",
"sims",
"=",
"{",
"}",
"overlaps",
"=",
"{",
"}",
"weights",
"=",
"{",
"}",
"for",
"a",
",",
"column_dict_a",
"in",
"nested_dictionaries",
".",
"items",
"(",
")"... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | SimilarityWeightedAveraging.complete_dict | Keys of nested dictionaries can be arbitrary objects. | fancyimpute/similarity_weighted_averaging.py | def complete_dict(
self,
values_dict):
"""
Keys of nested dictionaries can be arbitrary objects.
"""
if self.orientation != "rows":
values_dict = transpose_nested_dictionary(values_dict)
row_keys, column_keys = collect_nested_keys(values_dict)... | def complete_dict(
self,
values_dict):
"""
Keys of nested dictionaries can be arbitrary objects.
"""
if self.orientation != "rows":
values_dict = transpose_nested_dictionary(values_dict)
row_keys, column_keys = collect_nested_keys(values_dict)... | [
"Keys",
"of",
"nested",
"dictionaries",
"can",
"be",
"arbitrary",
"objects",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/similarity_weighted_averaging.py#L113-L153 | [
"def",
"complete_dict",
"(",
"self",
",",
"values_dict",
")",
":",
"if",
"self",
".",
"orientation",
"!=",
"\"rows\"",
":",
"values_dict",
"=",
"transpose_nested_dictionary",
"(",
"values_dict",
")",
"row_keys",
",",
"column_keys",
"=",
"collect_nested_keys",
"(",... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | nested_key_indices | Give an ordering to the outer and inner keys used in a dictionary that
maps to dictionaries. | fancyimpute/dictionary_helpers.py | def nested_key_indices(nested_dict):
"""
Give an ordering to the outer and inner keys used in a dictionary that
maps to dictionaries.
"""
outer_keys, inner_keys = collect_nested_keys(nested_dict)
outer_key_indices = {k: i for (i, k) in enumerate(outer_keys)}
inner_key_indices = {k: i for (i,... | def nested_key_indices(nested_dict):
"""
Give an ordering to the outer and inner keys used in a dictionary that
maps to dictionaries.
"""
outer_keys, inner_keys = collect_nested_keys(nested_dict)
outer_key_indices = {k: i for (i, k) in enumerate(outer_keys)}
inner_key_indices = {k: i for (i,... | [
"Give",
"an",
"ordering",
"to",
"the",
"outer",
"and",
"inner",
"keys",
"used",
"in",
"a",
"dictionary",
"that",
"maps",
"to",
"dictionaries",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L39-L47 | [
"def",
"nested_key_indices",
"(",
"nested_dict",
")",
":",
"outer_keys",
",",
"inner_keys",
"=",
"collect_nested_keys",
"(",
"nested_dict",
")",
"outer_key_indices",
"=",
"{",
"k",
":",
"i",
"for",
"(",
"i",
",",
"k",
")",
"in",
"enumerate",
"(",
"outer_keys... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | flattened_nested_key_indices | Combine the outer and inner keys of nested dictionaries into a single
ordering. | fancyimpute/dictionary_helpers.py | def flattened_nested_key_indices(nested_dict):
"""
Combine the outer and inner keys of nested dictionaries into a single
ordering.
"""
outer_keys, inner_keys = collect_nested_keys(nested_dict)
combined_keys = list(sorted(set(outer_keys + inner_keys)))
return {k: i for (i, k) in enumerate(com... | def flattened_nested_key_indices(nested_dict):
"""
Combine the outer and inner keys of nested dictionaries into a single
ordering.
"""
outer_keys, inner_keys = collect_nested_keys(nested_dict)
combined_keys = list(sorted(set(outer_keys + inner_keys)))
return {k: i for (i, k) in enumerate(com... | [
"Combine",
"the",
"outer",
"and",
"inner",
"keys",
"of",
"nested",
"dictionaries",
"into",
"a",
"single",
"ordering",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L50-L57 | [
"def",
"flattened_nested_key_indices",
"(",
"nested_dict",
")",
":",
"outer_keys",
",",
"inner_keys",
"=",
"collect_nested_keys",
"(",
"nested_dict",
")",
"combined_keys",
"=",
"list",
"(",
"sorted",
"(",
"set",
"(",
"outer_keys",
"+",
"inner_keys",
")",
")",
")... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | array_from_nested_dictionary | Parameters
----------
nested_dict : dict
Dictionary which contains dictionaries
array_fn : function
Takes shape and dtype as arguments, returns empty array.
dtype : dtype
NumPy dtype of result array
square_result : bool
Combine keys from outer and inner dictionarie... | fancyimpute/dictionary_helpers.py | def array_from_nested_dictionary(
nested_dict,
array_fn,
dtype="float32",
square_result=False):
"""
Parameters
----------
nested_dict : dict
Dictionary which contains dictionaries
array_fn : function
Takes shape and dtype as arguments, returns empty a... | def array_from_nested_dictionary(
nested_dict,
array_fn,
dtype="float32",
square_result=False):
"""
Parameters
----------
nested_dict : dict
Dictionary which contains dictionaries
array_fn : function
Takes shape and dtype as arguments, returns empty a... | [
"Parameters",
"----------",
"nested_dict",
":",
"dict",
"Dictionary",
"which",
"contains",
"dictionaries"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L67-L107 | [
"def",
"array_from_nested_dictionary",
"(",
"nested_dict",
",",
"array_fn",
",",
"dtype",
"=",
"\"float32\"",
",",
"square_result",
"=",
"False",
")",
":",
"if",
"square_result",
":",
"outer_key_indices",
"=",
"inner_key_indices",
"=",
"flattened_nested_key_indices",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | matrix_to_pair_dictionary | X : numpy.ndarray
row_keys : dict
Dictionary mapping indices to row names. If omitted then maps each
number to its string representation, such as 1 -> "1".
column_keys : dict
If omitted and matrix is square, then use the same dictionary
as the rows. Otherwise map each column in... | fancyimpute/dictionary_helpers.py | def matrix_to_pair_dictionary(
X, row_keys=None, column_keys=None, filter_fn=None):
"""
X : numpy.ndarray
row_keys : dict
Dictionary mapping indices to row names. If omitted then maps each
number to its string representation, such as 1 -> "1".
column_keys : dict
If omit... | def matrix_to_pair_dictionary(
X, row_keys=None, column_keys=None, filter_fn=None):
"""
X : numpy.ndarray
row_keys : dict
Dictionary mapping indices to row names. If omitted then maps each
number to its string representation, such as 1 -> "1".
column_keys : dict
If omit... | [
"X",
":",
"numpy",
".",
"ndarray"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L132-L178 | [
"def",
"matrix_to_pair_dictionary",
"(",
"X",
",",
"row_keys",
"=",
"None",
",",
"column_keys",
"=",
"None",
",",
"filter_fn",
"=",
"None",
")",
":",
"n_rows",
",",
"n_cols",
"=",
"X",
".",
"shape",
"if",
"row_keys",
"is",
"None",
":",
"row_keys",
"=",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | curry_pair_dictionary | Transform dictionary from pairs of keys to dict -> dict -> float | fancyimpute/dictionary_helpers.py | def curry_pair_dictionary(key_pair_dict, default_value=0.0):
"""
Transform dictionary from pairs of keys to dict -> dict -> float
"""
result = defaultdict(dict)
for (a, b), value in key_pair_dict.items():
result[a][b] = value
return result | def curry_pair_dictionary(key_pair_dict, default_value=0.0):
"""
Transform dictionary from pairs of keys to dict -> dict -> float
"""
result = defaultdict(dict)
for (a, b), value in key_pair_dict.items():
result[a][b] = value
return result | [
"Transform",
"dictionary",
"from",
"pairs",
"of",
"keys",
"to",
"dict",
"-",
">",
"dict",
"-",
">",
"float"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L181-L188 | [
"def",
"curry_pair_dictionary",
"(",
"key_pair_dict",
",",
"default_value",
"=",
"0.0",
")",
":",
"result",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"(",
"a",
",",
"b",
")",
",",
"value",
"in",
"key_pair_dict",
".",
"items",
"(",
")",
":",
"result",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | uncurry_nested_dictionary | Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float | fancyimpute/dictionary_helpers.py | def uncurry_nested_dictionary(curried_dict):
"""
Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float
"""
result = {}
for a, a_dict in curried_dict.items():
for b, value in a_dict.items():
result[(a, b)] = value
return result | def uncurry_nested_dictionary(curried_dict):
"""
Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float
"""
result = {}
for a, a_dict in curried_dict.items():
for b, value in a_dict.items():
result[(a, b)] = value
return result | [
"Transform",
"dictionary",
"from",
"(",
"key_a",
"-",
">",
"key_b",
"-",
">",
"float",
")",
"to",
"(",
"key_a",
"key_b",
")",
"-",
">",
"float"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L191-L200 | [
"def",
"uncurry_nested_dictionary",
"(",
"curried_dict",
")",
":",
"result",
"=",
"{",
"}",
"for",
"a",
",",
"a_dict",
"in",
"curried_dict",
".",
"items",
"(",
")",
":",
"for",
"b",
",",
"value",
"in",
"a_dict",
".",
"items",
"(",
")",
":",
"result",
... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | array_from_pair_dictionary | Convert a dictionary whose keys are pairs (k1, k2) into a sparse
or incomplete array.
Parameters
----------
pair_dict : dict
Dictionary from pairs of keys to values.
array_fn : function
Takes shape and dtype as arguments, returns empty array.
dtype : dtype
NumPy dtype ... | fancyimpute/dictionary_helpers.py | def array_from_pair_dictionary(
pair_dict,
array_fn,
dtype="float32",
square_result=False):
"""
Convert a dictionary whose keys are pairs (k1, k2) into a sparse
or incomplete array.
Parameters
----------
pair_dict : dict
Dictionary from pairs of keys to v... | def array_from_pair_dictionary(
pair_dict,
array_fn,
dtype="float32",
square_result=False):
"""
Convert a dictionary whose keys are pairs (k1, k2) into a sparse
or incomplete array.
Parameters
----------
pair_dict : dict
Dictionary from pairs of keys to v... | [
"Convert",
"a",
"dictionary",
"whose",
"keys",
"are",
"pairs",
"(",
"k1",
"k2",
")",
"into",
"a",
"sparse",
"or",
"incomplete",
"array",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L225-L272 | [
"def",
"array_from_pair_dictionary",
"(",
"pair_dict",
",",
"array_fn",
",",
"dtype",
"=",
"\"float32\"",
",",
"square_result",
"=",
"False",
")",
":",
"row_key_set",
",",
"column_key_set",
"=",
"pair_dict_key_sets",
"(",
"pair_dict",
")",
"if",
"square_result",
"... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | transpose_nested_dictionary | Given a nested dictionary from k1 -> k2 > value
transpose its outer and inner keys so it maps
k2 -> k1 -> value. | fancyimpute/dictionary_helpers.py | def transpose_nested_dictionary(nested_dict):
"""
Given a nested dictionary from k1 -> k2 > value
transpose its outer and inner keys so it maps
k2 -> k1 -> value.
"""
result = defaultdict(dict)
for k1, d in nested_dict.items():
for k2, v in d.items():
result[k2][k1] = v
... | def transpose_nested_dictionary(nested_dict):
"""
Given a nested dictionary from k1 -> k2 > value
transpose its outer and inner keys so it maps
k2 -> k1 -> value.
"""
result = defaultdict(dict)
for k1, d in nested_dict.items():
for k2, v in d.items():
result[k2][k1] = v
... | [
"Given",
"a",
"nested",
"dictionary",
"from",
"k1",
"-",
">",
"k2",
">",
"value",
"transpose",
"its",
"outer",
"and",
"inner",
"keys",
"so",
"it",
"maps",
"k2",
"-",
">",
"k1",
"-",
">",
"value",
"."
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L297-L307 | [
"def",
"transpose_nested_dictionary",
"(",
"nested_dict",
")",
":",
"result",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"k1",
",",
"d",
"in",
"nested_dict",
".",
"items",
"(",
")",
":",
"for",
"k2",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":"... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | reverse_lookup_from_nested_dict | Create reverse-lookup dictionary mapping each row key to a list of triplets:
[(column key, value), ...]
Parameters
----------
nested_values_dict : dict
column_key -> row_key -> value
weights_dict : dict
column_key -> row_key -> sample weight
Returns dictionary mapping row_key ... | fancyimpute/dictionary_helpers.py | def reverse_lookup_from_nested_dict(values_dict):
"""
Create reverse-lookup dictionary mapping each row key to a list of triplets:
[(column key, value), ...]
Parameters
----------
nested_values_dict : dict
column_key -> row_key -> value
weights_dict : dict
column_key -> row... | def reverse_lookup_from_nested_dict(values_dict):
"""
Create reverse-lookup dictionary mapping each row key to a list of triplets:
[(column key, value), ...]
Parameters
----------
nested_values_dict : dict
column_key -> row_key -> value
weights_dict : dict
column_key -> row... | [
"Create",
"reverse",
"-",
"lookup",
"dictionary",
"mapping",
"each",
"row",
"key",
"to",
"a",
"list",
"of",
"triplets",
":",
"[",
"(",
"column",
"key",
"value",
")",
"...",
"]"
] | iskandr/fancyimpute | python | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/dictionary_helpers.py#L310-L330 | [
"def",
"reverse_lookup_from_nested_dict",
"(",
"values_dict",
")",
":",
"reverse_lookup",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"column_key",
",",
"column_dict",
"in",
"values_dict",
".",
"items",
"(",
")",
":",
"for",
"row_key",
",",
"value",
"in",
"co... | 9f0837d387c7303d5c8c925a9989ca77a1a96e3e |
train | _cells | Yield all cells in an nbformat-insensitive manner | scripts/strip_examples.py | def _cells(nb):
"""Yield all cells in an nbformat-insensitive manner"""
if nb.nbformat < 4:
for ws in nb.worksheets:
for cell in ws.cells:
yield cell
else:
for cell in nb.cells:
yield cell | def _cells(nb):
"""Yield all cells in an nbformat-insensitive manner"""
if nb.nbformat < 4:
for ws in nb.worksheets:
for cell in ws.cells:
yield cell
else:
for cell in nb.cells:
yield cell | [
"Yield",
"all",
"cells",
"in",
"an",
"nbformat",
"-",
"insensitive",
"manner"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/scripts/strip_examples.py#L52-L60 | [
"def",
"_cells",
"(",
"nb",
")",
":",
"if",
"nb",
".",
"nbformat",
"<",
"4",
":",
"for",
"ws",
"in",
"nb",
".",
"worksheets",
":",
"for",
"cell",
"in",
"ws",
".",
"cells",
":",
"yield",
"cell",
"else",
":",
"for",
"cell",
"in",
"nb",
".",
"cell... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | strip_output | strip the outputs from a notebook object | scripts/strip_examples.py | def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
nb.metadata.pop('widgets', None)
for cell in _cells(nb):
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
... | def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
nb.metadata.pop('widgets', None)
for cell in _cells(nb):
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
... | [
"strip",
"the",
"outputs",
"from",
"a",
"notebook",
"object"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/scripts/strip_examples.py#L63-L72 | [
"def",
"strip_output",
"(",
"nb",
")",
":",
"nb",
".",
"metadata",
".",
"pop",
"(",
"'signature'",
",",
"None",
")",
"nb",
".",
"metadata",
".",
"pop",
"(",
"'widgets'",
",",
"None",
")",
"for",
"cell",
"in",
"_cells",
"(",
"nb",
")",
":",
"if",
... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _BoundedFloat._validate_min | Enforce min <= value <= max | ipywidgets/widgets/widget_float.py | def _validate_min(self, proposal):
"""Enforce min <= value <= max"""
min = proposal['value']
if min > self.max:
raise TraitError('Setting min > max')
if min > self.value:
self.value = min
return min | def _validate_min(self, proposal):
"""Enforce min <= value <= max"""
min = proposal['value']
if min > self.max:
raise TraitError('Setting min > max')
if min > self.value:
self.value = min
return min | [
"Enforce",
"min",
"<",
"=",
"value",
"<",
"=",
"max"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_float.py#L42-L49 | [
"def",
"_validate_min",
"(",
"self",
",",
"proposal",
")",
":",
"min",
"=",
"proposal",
"[",
"'value'",
"]",
"if",
"min",
">",
"self",
".",
"max",
":",
"raise",
"TraitError",
"(",
"'Setting min > max'",
")",
"if",
"min",
">",
"self",
".",
"value",
":",... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _BoundedFloat._validate_max | Enforce min <= value <= max | ipywidgets/widgets/widget_float.py | def _validate_max(self, proposal):
"""Enforce min <= value <= max"""
max = proposal['value']
if max < self.min:
raise TraitError('setting max < min')
if max < self.value:
self.value = max
return max | def _validate_max(self, proposal):
"""Enforce min <= value <= max"""
max = proposal['value']
if max < self.min:
raise TraitError('setting max < min')
if max < self.value:
self.value = max
return max | [
"Enforce",
"min",
"<",
"=",
"value",
"<",
"=",
"max"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_float.py#L52-L59 | [
"def",
"_validate_max",
"(",
"self",
",",
"proposal",
")",
":",
"max",
"=",
"proposal",
"[",
"'value'",
"]",
"if",
"max",
"<",
"self",
".",
"min",
":",
"raise",
"TraitError",
"(",
"'setting max < min'",
")",
"if",
"max",
"<",
"self",
".",
"value",
":",... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _BoundedLogFloat._validate_value | Cap and floor value | ipywidgets/widgets/widget_float.py | def _validate_value(self, proposal):
"""Cap and floor value"""
value = proposal['value']
if self.base ** self.min > value or self.base ** self.max < value:
value = min(max(value, self.base ** self.min), self.base ** self.max)
return value | def _validate_value(self, proposal):
"""Cap and floor value"""
value = proposal['value']
if self.base ** self.min > value or self.base ** self.max < value:
value = min(max(value, self.base ** self.min), self.base ** self.max)
return value | [
"Cap",
"and",
"floor",
"value"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_float.py#L68-L73 | [
"def",
"_validate_value",
"(",
"self",
",",
"proposal",
")",
":",
"value",
"=",
"proposal",
"[",
"'value'",
"]",
"if",
"self",
".",
"base",
"**",
"self",
".",
"min",
">",
"value",
"or",
"self",
".",
"base",
"**",
"self",
".",
"max",
"<",
"value",
"... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | show_inline_matplotlib_plots | Show matplotlib plots immediately if using the inline backend.
With ipywidgets 6.0, matplotlib plots don't work well with interact when
using the inline backend that comes with ipykernel. Basically, the inline
backend only shows the plot after the entire cell executes, which does not
play well with dra... | ipywidgets/widgets/interaction.py | def show_inline_matplotlib_plots():
"""Show matplotlib plots immediately if using the inline backend.
With ipywidgets 6.0, matplotlib plots don't work well with interact when
using the inline backend that comes with ipykernel. Basically, the inline
backend only shows the plot after the entire cell exec... | def show_inline_matplotlib_plots():
"""Show matplotlib plots immediately if using the inline backend.
With ipywidgets 6.0, matplotlib plots don't work well with interact when
using the inline backend that comes with ipykernel. Basically, the inline
backend only shows the plot after the entire cell exec... | [
"Show",
"matplotlib",
"plots",
"immediately",
"if",
"using",
"the",
"inline",
"backend",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L35-L57 | [
"def",
"show_inline_matplotlib_plots",
"(",
")",
":",
"if",
"'matplotlib'",
"not",
"in",
"sys",
".",
"modules",
":",
"# matplotlib hasn't been imported, nothing to do.",
"return",
"try",
":",
"import",
"matplotlib",
"as",
"mpl",
"from",
"ipykernel",
".",
"pylab",
".... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | interactive_output | Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually. | ipywidgets/widgets/interaction.py | def interactive_output(f, controls):
"""Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually.
"""
... | def interactive_output(f, controls):
"""Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually.
"""
... | [
"Connect",
"widget",
"controls",
"to",
"a",
"function",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L60-L80 | [
"def",
"interactive_output",
"(",
"f",
",",
"controls",
")",
":",
"out",
"=",
"Output",
"(",
")",
"def",
"observer",
"(",
"change",
")",
":",
"kwargs",
"=",
"{",
"k",
":",
"v",
".",
"value",
"for",
"k",
",",
"v",
"in",
"controls",
".",
"items",
"... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _matches | Match a pattern of types in a sequence. | ipywidgets/widgets/interaction.py | def _matches(o, pattern):
"""Match a pattern of types in a sequence."""
if not len(o) == len(pattern):
return False
comps = zip(o,pattern)
return all(isinstance(obj,kind) for obj,kind in comps) | def _matches(o, pattern):
"""Match a pattern of types in a sequence."""
if not len(o) == len(pattern):
return False
comps = zip(o,pattern)
return all(isinstance(obj,kind) for obj,kind in comps) | [
"Match",
"a",
"pattern",
"of",
"types",
"in",
"a",
"sequence",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L83-L88 | [
"def",
"_matches",
"(",
"o",
",",
"pattern",
")",
":",
"if",
"not",
"len",
"(",
"o",
")",
"==",
"len",
"(",
"pattern",
")",
":",
"return",
"False",
"comps",
"=",
"zip",
"(",
"o",
",",
"pattern",
")",
"return",
"all",
"(",
"isinstance",
"(",
"obj"... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _get_min_max_value | Return min, max, value given input values with possible None. | ipywidgets/widgets/interaction.py | def _get_min_max_value(min, max, value=None, step=None):
"""Return min, max, value given input values with possible None."""
# Either min and max need to be given, or value needs to be given
if value is None:
if min is None or max is None:
raise ValueError('unable to infer range, value f... | def _get_min_max_value(min, max, value=None, step=None):
"""Return min, max, value given input values with possible None."""
# Either min and max need to be given, or value needs to be given
if value is None:
if min is None or max is None:
raise ValueError('unable to infer range, value f... | [
"Return",
"min",
"max",
"value",
"given",
"input",
"values",
"with",
"possible",
"None",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L91-L123 | [
"def",
"_get_min_max_value",
"(",
"min",
",",
"max",
",",
"value",
"=",
"None",
",",
"step",
"=",
"None",
")",
":",
"# Either min and max need to be given, or value needs to be given",
"if",
"value",
"is",
"None",
":",
"if",
"min",
"is",
"None",
"or",
"max",
"... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _yield_abbreviations_for_parameter | Get an abbreviation for a function parameter. | ipywidgets/widgets/interaction.py | def _yield_abbreviations_for_parameter(param, kwargs):
"""Get an abbreviation for a function parameter."""
name = param.name
kind = param.kind
ann = param.annotation
default = param.default
not_found = (name, empty, empty)
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):... | def _yield_abbreviations_for_parameter(param, kwargs):
"""Get an abbreviation for a function parameter."""
name = param.name
kind = param.kind
ann = param.annotation
default = param.default
not_found = (name, empty, empty)
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):... | [
"Get",
"an",
"abbreviation",
"for",
"a",
"function",
"parameter",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L125-L147 | [
"def",
"_yield_abbreviations_for_parameter",
"(",
"param",
",",
"kwargs",
")",
":",
"name",
"=",
"param",
".",
"name",
"kind",
"=",
"param",
".",
"kind",
"ann",
"=",
"param",
".",
"annotation",
"default",
"=",
"param",
".",
"default",
"not_found",
"=",
"("... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | interactive.update | Call the interact function and update the output widget with
the result of the function call.
Parameters
----------
*args : ignored
Required for this method to be used as traitlets callback. | ipywidgets/widgets/interaction.py | def update(self, *args):
"""
Call the interact function and update the output widget with
the result of the function call.
Parameters
----------
*args : ignored
Required for this method to be used as traitlets callback.
"""
self.kwargs = {}
... | def update(self, *args):
"""
Call the interact function and update the output widget with
the result of the function call.
Parameters
----------
*args : ignored
Required for this method to be used as traitlets callback.
"""
self.kwargs = {}
... | [
"Call",
"the",
"interact",
"function",
"and",
"update",
"the",
"output",
"widget",
"with",
"the",
"result",
"of",
"the",
"function",
"call",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L230-L263 | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"manual",
":",
"self",
".",
"manual_button",
".",
"disabled",
"=",
"True",
"try",
":",
"show_inline_matplotlib_plots",
"(",
")",
"with",
... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | interactive.find_abbreviations | Find the abbreviations for the given function and kwargs.
Return (name, abbrev, default) tuples. | ipywidgets/widgets/interaction.py | def find_abbreviations(self, kwargs):
"""Find the abbreviations for the given function and kwargs.
Return (name, abbrev, default) tuples.
"""
new_kwargs = []
try:
sig = self.signature()
except (ValueError, TypeError):
# can't inspect, no info from ... | def find_abbreviations(self, kwargs):
"""Find the abbreviations for the given function and kwargs.
Return (name, abbrev, default) tuples.
"""
new_kwargs = []
try:
sig = self.signature()
except (ValueError, TypeError):
# can't inspect, no info from ... | [
"Find",
"the",
"abbreviations",
"for",
"the",
"given",
"function",
"and",
"kwargs",
".",
"Return",
"(",
"name",
"abbrev",
"default",
")",
"tuples",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L269-L285 | [
"def",
"find_abbreviations",
"(",
"self",
",",
"kwargs",
")",
":",
"new_kwargs",
"=",
"[",
"]",
"try",
":",
"sig",
"=",
"self",
".",
"signature",
"(",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"# can't inspect, no info from function; only u... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | interactive.widgets_from_abbreviations | Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets. | ipywidgets/widgets/interaction.py | def widgets_from_abbreviations(self, seq):
"""Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets."""
result = []
for name, abbrev, default in seq:
widget = self.widget_from_abbrev(abbrev, default)
if not (isinstance(widget, ValueWidget) or is... | def widgets_from_abbreviations(self, seq):
"""Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets."""
result = []
for name, abbrev, default in seq:
widget = self.widget_from_abbrev(abbrev, default)
if not (isinstance(widget, ValueWidget) or is... | [
"Given",
"a",
"sequence",
"of",
"(",
"name",
"abbrev",
"default",
")",
"tuples",
"return",
"a",
"sequence",
"of",
"Widgets",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L288-L302 | [
"def",
"widgets_from_abbreviations",
"(",
"self",
",",
"seq",
")",
":",
"result",
"=",
"[",
"]",
"for",
"name",
",",
"abbrev",
",",
"default",
"in",
"seq",
":",
"widget",
"=",
"self",
".",
"widget_from_abbrev",
"(",
"abbrev",
",",
"default",
")",
"if",
... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | interactive.widget_from_abbrev | Build a ValueWidget instance given an abbreviation or Widget. | ipywidgets/widgets/interaction.py | def widget_from_abbrev(cls, abbrev, default=empty):
"""Build a ValueWidget instance given an abbreviation or Widget."""
if isinstance(abbrev, ValueWidget) or isinstance(abbrev, fixed):
return abbrev
if isinstance(abbrev, tuple):
widget = cls.widget_from_tuple(abbrev)
... | def widget_from_abbrev(cls, abbrev, default=empty):
"""Build a ValueWidget instance given an abbreviation or Widget."""
if isinstance(abbrev, ValueWidget) or isinstance(abbrev, fixed):
return abbrev
if isinstance(abbrev, tuple):
widget = cls.widget_from_tuple(abbrev)
... | [
"Build",
"a",
"ValueWidget",
"instance",
"given",
"an",
"abbreviation",
"or",
"Widget",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L305-L338 | [
"def",
"widget_from_abbrev",
"(",
"cls",
",",
"abbrev",
",",
"default",
"=",
"empty",
")",
":",
"if",
"isinstance",
"(",
"abbrev",
",",
"ValueWidget",
")",
"or",
"isinstance",
"(",
"abbrev",
",",
"fixed",
")",
":",
"return",
"abbrev",
"if",
"isinstance",
... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | interactive.widget_from_single_value | Make widgets from single values, which can be used as parameter defaults. | ipywidgets/widgets/interaction.py | def widget_from_single_value(o):
"""Make widgets from single values, which can be used as parameter defaults."""
if isinstance(o, string_types):
return Text(value=unicode_type(o))
elif isinstance(o, bool):
return Checkbox(value=o)
elif isinstance(o, Integral):
... | def widget_from_single_value(o):
"""Make widgets from single values, which can be used as parameter defaults."""
if isinstance(o, string_types):
return Text(value=unicode_type(o))
elif isinstance(o, bool):
return Checkbox(value=o)
elif isinstance(o, Integral):
... | [
"Make",
"widgets",
"from",
"single",
"values",
"which",
"can",
"be",
"used",
"as",
"parameter",
"defaults",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L341-L354 | [
"def",
"widget_from_single_value",
"(",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"string_types",
")",
":",
"return",
"Text",
"(",
"value",
"=",
"unicode_type",
"(",
"o",
")",
")",
"elif",
"isinstance",
"(",
"o",
",",
"bool",
")",
":",
"return"... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | interactive.widget_from_tuple | Make widgets from a tuple abbreviation. | ipywidgets/widgets/interaction.py | def widget_from_tuple(o):
"""Make widgets from a tuple abbreviation."""
if _matches(o, (Real, Real)):
min, max, value = _get_min_max_value(o[0], o[1])
if all(isinstance(_, Integral) for _ in o):
cls = IntSlider
else:
cls = FloatSlider
... | def widget_from_tuple(o):
"""Make widgets from a tuple abbreviation."""
if _matches(o, (Real, Real)):
min, max, value = _get_min_max_value(o[0], o[1])
if all(isinstance(_, Integral) for _ in o):
cls = IntSlider
else:
cls = FloatSlider
... | [
"Make",
"widgets",
"from",
"a",
"tuple",
"abbreviation",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L357-L375 | [
"def",
"widget_from_tuple",
"(",
"o",
")",
":",
"if",
"_matches",
"(",
"o",
",",
"(",
"Real",
",",
"Real",
")",
")",
":",
"min",
",",
"max",
",",
"value",
"=",
"_get_min_max_value",
"(",
"o",
"[",
"0",
"]",
",",
"o",
"[",
"1",
"]",
")",
"if",
... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | interactive.widget_from_iterable | Make widgets from an iterable. This should not be done for
a string or tuple. | ipywidgets/widgets/interaction.py | def widget_from_iterable(o):
"""Make widgets from an iterable. This should not be done for
a string or tuple."""
# Dropdown expects a dict or list, so we convert an arbitrary
# iterable to either of those.
if isinstance(o, (list, dict)):
return Dropdown(options=o)
... | def widget_from_iterable(o):
"""Make widgets from an iterable. This should not be done for
a string or tuple."""
# Dropdown expects a dict or list, so we convert an arbitrary
# iterable to either of those.
if isinstance(o, (list, dict)):
return Dropdown(options=o)
... | [
"Make",
"widgets",
"from",
"an",
"iterable",
".",
"This",
"should",
"not",
"be",
"done",
"for",
"a",
"string",
"or",
"tuple",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L378-L388 | [
"def",
"widget_from_iterable",
"(",
"o",
")",
":",
"# Dropdown expects a dict or list, so we convert an arbitrary",
"# iterable to either of those.",
"if",
"isinstance",
"(",
"o",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"return",
"Dropdown",
"(",
"options",
"=",... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _InteractFactory.widget | Return an interactive function widget for the given function.
The widget is only constructed, not displayed nor attached to
the function.
Returns
-------
An instance of ``self.cls`` (typically :class:`interactive`).
Parameters
----------
f : function
... | ipywidgets/widgets/interaction.py | def widget(self, f):
"""
Return an interactive function widget for the given function.
The widget is only constructed, not displayed nor attached to
the function.
Returns
-------
An instance of ``self.cls`` (typically :class:`interactive`).
Parameters
... | def widget(self, f):
"""
Return an interactive function widget for the given function.
The widget is only constructed, not displayed nor attached to
the function.
Returns
-------
An instance of ``self.cls`` (typically :class:`interactive`).
Parameters
... | [
"Return",
"an",
"interactive",
"function",
"widget",
"for",
"the",
"given",
"function",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L423-L439 | [
"def",
"widget",
"(",
"self",
",",
"f",
")",
":",
"return",
"self",
".",
"cls",
"(",
"f",
",",
"self",
".",
"opts",
",",
"*",
"*",
"self",
".",
"kwargs",
")"
] | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _InteractFactory.options | Change options for interactive functions.
Returns
-------
A new :class:`_InteractFactory` which will apply the
options when called. | ipywidgets/widgets/interaction.py | def options(self, **kwds):
"""
Change options for interactive functions.
Returns
-------
A new :class:`_InteractFactory` which will apply the
options when called.
"""
opts = dict(self.opts)
for k in kwds:
try:
# Ensure ... | def options(self, **kwds):
"""
Change options for interactive functions.
Returns
-------
A new :class:`_InteractFactory` which will apply the
options when called.
"""
opts = dict(self.opts)
for k in kwds:
try:
# Ensure ... | [
"Change",
"options",
"for",
"interactive",
"functions",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L535-L553 | [
"def",
"options",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"opts",
"=",
"dict",
"(",
"self",
".",
"opts",
")",
"for",
"k",
"in",
"kwds",
":",
"try",
":",
"# Ensure that the key exists because we want to change",
"# existing options, not add new ones.",
"_",... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _SelectionContainer.set_title | Sets the title of a container page.
Parameters
----------
index : int
Index of the container page
title : unicode
New title | ipywidgets/widgets/widget_selectioncontainer.py | def set_title(self, index, title):
"""Sets the title of a container page.
Parameters
----------
index : int
Index of the container page
title : unicode
New title
"""
# JSON dictionaries have string keys, so we convert index to a string
... | def set_title(self, index, title):
"""Sets the title of a container page.
Parameters
----------
index : int
Index of the container page
title : unicode
New title
"""
# JSON dictionaries have string keys, so we convert index to a string
... | [
"Sets",
"the",
"title",
"of",
"a",
"container",
"page",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selectioncontainer.py#L33-L46 | [
"def",
"set_title",
"(",
"self",
",",
"index",
",",
"title",
")",
":",
"# JSON dictionaries have string keys, so we convert index to a string",
"index",
"=",
"unicode_type",
"(",
"int",
"(",
"index",
")",
")",
"self",
".",
"_titles",
"[",
"index",
"]",
"=",
"tit... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _SelectionContainer.get_title | Gets the title of a container pages.
Parameters
----------
index : int
Index of the container page | ipywidgets/widgets/widget_selectioncontainer.py | def get_title(self, index):
"""Gets the title of a container pages.
Parameters
----------
index : int
Index of the container page
"""
# JSON dictionaries have string keys, so we convert index to a string
index = unicode_type(int(index))
if ind... | def get_title(self, index):
"""Gets the title of a container pages.
Parameters
----------
index : int
Index of the container page
"""
# JSON dictionaries have string keys, so we convert index to a string
index = unicode_type(int(index))
if ind... | [
"Gets",
"the",
"title",
"of",
"a",
"container",
"pages",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selectioncontainer.py#L48-L61 | [
"def",
"get_title",
"(",
"self",
",",
"index",
")",
":",
"# JSON dictionaries have string keys, so we convert index to a string",
"index",
"=",
"unicode_type",
"(",
"int",
"(",
"index",
")",
")",
"if",
"index",
"in",
"self",
".",
"_titles",
":",
"return",
"self",
... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | bash | Runs a bash script in the local directory | docs/source/conf.py | def bash(filename):
"""Runs a bash script in the local directory"""
sys.stdout.flush()
subprocess.call("bash {}".format(filename), shell=True) | def bash(filename):
"""Runs a bash script in the local directory"""
sys.stdout.flush()
subprocess.call("bash {}".format(filename), shell=True) | [
"Runs",
"a",
"bash",
"script",
"in",
"the",
"local",
"directory"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/docs/source/conf.py#L20-L23 | [
"def",
"bash",
"(",
"filename",
")",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"subprocess",
".",
"call",
"(",
"\"bash {}\"",
".",
"format",
"(",
"filename",
")",
",",
"shell",
"=",
"True",
")"
] | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _put_buffers | The inverse of _remove_buffers, except here we modify the existing dict/lists.
Modifying should be fine, since this is used when state comes from the wire. | ipywidgets/widgets/widget.py | def _put_buffers(state, buffer_paths, buffers):
"""The inverse of _remove_buffers, except here we modify the existing dict/lists.
Modifying should be fine, since this is used when state comes from the wire.
"""
for buffer_path, buffer in zip(buffer_paths, buffers):
# we'd like to set say sync_da... | def _put_buffers(state, buffer_paths, buffers):
"""The inverse of _remove_buffers, except here we modify the existing dict/lists.
Modifying should be fine, since this is used when state comes from the wire.
"""
for buffer_path, buffer in zip(buffer_paths, buffers):
# we'd like to set say sync_da... | [
"The",
"inverse",
"of",
"_remove_buffers",
"except",
"here",
"we",
"modify",
"the",
"existing",
"dict",
"/",
"lists",
".",
"Modifying",
"should",
"be",
"fine",
"since",
"this",
"is",
"used",
"when",
"state",
"comes",
"from",
"the",
"wire",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L59-L69 | [
"def",
"_put_buffers",
"(",
"state",
",",
"buffer_paths",
",",
"buffers",
")",
":",
"for",
"buffer_path",
",",
"buffer",
"in",
"zip",
"(",
"buffer_paths",
",",
"buffers",
")",
":",
"# we'd like to set say sync_data['x'][0]['y'] = buffer",
"# where buffer_path in this ex... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _separate_buffers | For internal, see _remove_buffers | ipywidgets/widgets/widget.py | def _separate_buffers(substate, path, buffer_paths, buffers):
"""For internal, see _remove_buffers"""
# remove binary types from dicts and lists, but keep track of their paths
# any part of the dict/list that needs modification will be cloned, so the original stays untouched
# e.g. {'x': {'ar': ar}, 'y'... | def _separate_buffers(substate, path, buffer_paths, buffers):
"""For internal, see _remove_buffers"""
# remove binary types from dicts and lists, but keep track of their paths
# any part of the dict/list that needs modification will be cloned, so the original stays untouched
# e.g. {'x': {'ar': ar}, 'y'... | [
"For",
"internal",
"see",
"_remove_buffers"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L71-L114 | [
"def",
"_separate_buffers",
"(",
"substate",
",",
"path",
",",
"buffer_paths",
",",
"buffers",
")",
":",
"# remove binary types from dicts and lists, but keep track of their paths",
"# any part of the dict/list that needs modification will be cloned, so the original stays untouched",
"# ... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _remove_buffers | Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memoryview(ar2)}}
>>> _remove_buffe... | ipywidgets/widgets/widget.py | def _remove_buffers(state):
"""Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memo... | def _remove_buffers(state):
"""Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memo... | [
"Return",
"(",
"state_without_buffers",
"buffer_paths",
"buffers",
")",
"for",
"binary",
"message",
"parts"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L117-L130 | [
"def",
"_remove_buffers",
"(",
"state",
")",
":",
"buffer_paths",
",",
"buffers",
"=",
"[",
"]",
",",
"[",
"]",
"state",
"=",
"_separate_buffers",
"(",
"state",
",",
"[",
"]",
",",
"buffer_paths",
",",
"buffers",
")",
"return",
"state",
",",
"buffer_path... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _buffer_list_equal | Compare two lists of buffers for equality.
Used to decide whether two sequences of buffers (memoryviews,
bytearrays, or python 3 bytes) differ, such that a sync is needed.
Returns True if equal, False if unequal | ipywidgets/widgets/widget.py | def _buffer_list_equal(a, b):
"""Compare two lists of buffers for equality.
Used to decide whether two sequences of buffers (memoryviews,
bytearrays, or python 3 bytes) differ, such that a sync is needed.
Returns True if equal, False if unequal
"""
if len(a) != len(b):
return False
... | def _buffer_list_equal(a, b):
"""Compare two lists of buffers for equality.
Used to decide whether two sequences of buffers (memoryviews,
bytearrays, or python 3 bytes) differ, such that a sync is needed.
Returns True if equal, False if unequal
"""
if len(a) != len(b):
return False
... | [
"Compare",
"two",
"lists",
"of",
"buffers",
"for",
"equality",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L132-L161 | [
"def",
"_buffer_list_equal",
"(",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"return",
"False",
"if",
"a",
"==",
"b",
":",
"return",
"True",
"for",
"ia",
",",
"ib",
"in",
"zip",
"(",
"a",
",",
"b",
... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | _show_traceback | decorator for showing tracebacks in IPython | ipywidgets/widgets/widget.py | def _show_traceback(method):
"""decorator for showing tracebacks in IPython"""
def m(self, *args, **kwargs):
try:
return(method(self, *args, **kwargs))
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warning("Exception in widg... | def _show_traceback(method):
"""decorator for showing tracebacks in IPython"""
def m(self, *args, **kwargs):
try:
return(method(self, *args, **kwargs))
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warning("Exception in widg... | [
"decorator",
"for",
"showing",
"tracebacks",
"in",
"IPython"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L212-L223 | [
"def",
"_show_traceback",
"(",
"method",
")",
":",
"def",
"m",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"(",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"except",
"E... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | register | For backwards compatibility, we support @register(name) syntax. | ipywidgets/widgets/widget.py | def register(name=''):
"For backwards compatibility, we support @register(name) syntax."
def reg(widget):
"""A decorator registering a widget class in the widget registry."""
w = widget.class_traits()
Widget.widget_types.register(w['_model_module'].default_value,
... | def register(name=''):
"For backwards compatibility, we support @register(name) syntax."
def reg(widget):
"""A decorator registering a widget class in the widget registry."""
w = widget.class_traits()
Widget.widget_types.register(w['_model_module'].default_value,
... | [
"For",
"backwards",
"compatibility",
"we",
"support"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L266-L284 | [
"def",
"register",
"(",
"name",
"=",
"''",
")",
":",
"def",
"reg",
"(",
"widget",
")",
":",
"\"\"\"A decorator registering a widget class in the widget registry.\"\"\"",
"w",
"=",
"widget",
".",
"class_traits",
"(",
")",
"Widget",
".",
"widget_types",
".",
"regist... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | CallbackDispatcher.register_callback | (Un)Register a callback
Parameters
----------
callback: method handle
Method to be registered or unregistered.
remove=False: bool
Whether to unregister the callback. | ipywidgets/widgets/widget.py | def register_callback(self, callback, remove=False):
"""(Un)Register a callback
Parameters
----------
callback: method handle
Method to be registered or unregistered.
remove=False: bool
Whether to unregister the callback."""
# (Un)Register the ca... | def register_callback(self, callback, remove=False):
"""(Un)Register a callback
Parameters
----------
callback: method handle
Method to be registered or unregistered.
remove=False: bool
Whether to unregister the callback."""
# (Un)Register the ca... | [
"(",
"Un",
")",
"Register",
"a",
"callback"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L196-L210 | [
"def",
"register_callback",
"(",
"self",
",",
"callback",
",",
"remove",
"=",
"False",
")",
":",
"# (Un)Register the callback.",
"if",
"remove",
"and",
"callback",
"in",
"self",
".",
"callbacks",
":",
"self",
".",
"callbacks",
".",
"remove",
"(",
"callback",
... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | WidgetRegistry.register | Register a value | ipywidgets/widgets/widget.py | def register(self, model_module, model_module_version_range, model_name, view_module, view_module_version_range, view_name, klass):
"""Register a value"""
model_module = self._registry.setdefault(model_module, {})
model_version = model_module.setdefault(model_module_version_range, {})
mo... | def register(self, model_module, model_module_version_range, model_name, view_module, view_module_version_range, view_name, klass):
"""Register a value"""
model_module = self._registry.setdefault(model_module, {})
model_version = model_module.setdefault(model_module_version_range, {})
mo... | [
"Register",
"a",
"value"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L231-L238 | [
"def",
"register",
"(",
"self",
",",
"model_module",
",",
"model_module_version_range",
",",
"model_name",
",",
"view_module",
",",
"view_module_version_range",
",",
"view_name",
",",
"klass",
")",
":",
"model_module",
"=",
"self",
".",
"_registry",
".",
"setdefau... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | WidgetRegistry.get | Get a value | ipywidgets/widgets/widget.py | def get(self, model_module, model_module_version, model_name, view_module, view_module_version, view_name):
"""Get a value"""
module_versions = self._registry[model_module]
# The python semver module doesn't work well, for example, it can't do match('3', '*')
# so we just take the first ... | def get(self, model_module, model_module_version, model_name, view_module, view_module_version, view_name):
"""Get a value"""
module_versions = self._registry[model_module]
# The python semver module doesn't work well, for example, it can't do match('3', '*')
# so we just take the first ... | [
"Get",
"a",
"value"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L240-L255 | [
"def",
"get",
"(",
"self",
",",
"model_module",
",",
"model_module_version",
",",
"model_name",
",",
"view_module",
",",
"view_module_version",
",",
"view_name",
")",
":",
"module_versions",
"=",
"self",
".",
"_registry",
"[",
"model_module",
"]",
"# The python se... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | Widget._call_widget_constructed | Static method, called when a widget is constructed. | ipywidgets/widgets/widget.py | def _call_widget_constructed(widget):
"""Static method, called when a widget is constructed."""
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
Widget._widget_construction_callback(widget) | def _call_widget_constructed(widget):
"""Static method, called when a widget is constructed."""
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
Widget._widget_construction_callback(widget) | [
"Static",
"method",
"called",
"when",
"a",
"widget",
"is",
"constructed",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L313-L316 | [
"def",
"_call_widget_constructed",
"(",
"widget",
")",
":",
"if",
"Widget",
".",
"_widget_construction_callback",
"is",
"not",
"None",
"and",
"callable",
"(",
"Widget",
".",
"_widget_construction_callback",
")",
":",
"Widget",
".",
"_widget_construction_callback",
"("... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | Widget.handle_comm_opened | Static method, called when a widget is constructed. | ipywidgets/widgets/widget.py | def handle_comm_opened(comm, msg):
"""Static method, called when a widget is constructed."""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget protocol versions: received version %r, expected... | def handle_comm_opened(comm, msg):
"""Static method, called when a widget is constructed."""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget protocol versions: received version %r, expected... | [
"Static",
"method",
"called",
"when",
"a",
"widget",
"is",
"constructed",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L319-L337 | [
"def",
"handle_comm_opened",
"(",
"comm",
",",
"msg",
")",
":",
"version",
"=",
"msg",
".",
"get",
"(",
"'metadata'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'version'",
",",
"''",
")",
"if",
"version",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | Widget.get_manager_state | Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return: | ipywidgets/widgets/widget.py | def get_manager_state(drop_defaults=False, widgets=None):
"""Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
... | def get_manager_state(drop_defaults=False, widgets=None):
"""Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
... | [
"Returns",
"the",
"full",
"state",
"for",
"a",
"widget",
"manager",
"for",
"embedding"
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L340-L352 | [
"def",
"get_manager_state",
"(",
"drop_defaults",
"=",
"False",
",",
"widgets",
"=",
"None",
")",
":",
"state",
"=",
"{",
"}",
"if",
"widgets",
"is",
"None",
":",
"widgets",
"=",
"Widget",
".",
"widgets",
".",
"values",
"(",
")",
"for",
"widget",
"in",... | 36fe37594cd5a268def228709ca27e37b99ac606 |
train | Widget.open | Open a comm to the frontend if one isn't already open. | ipywidgets/widgets/widget.py | def open(self):
"""Open a comm to the frontend if one isn't already open."""
if self.comm is None:
state, buffer_paths, buffers = _remove_buffers(self.get_state())
args = dict(target_name='jupyter.widget',
data={'state': state, 'buffer_paths': buffer_path... | def open(self):
"""Open a comm to the frontend if one isn't already open."""
if self.comm is None:
state, buffer_paths, buffers = _remove_buffers(self.get_state())
args = dict(target_name='jupyter.widget',
data={'state': state, 'buffer_paths': buffer_path... | [
"Open",
"a",
"comm",
"to",
"the",
"frontend",
"if",
"one",
"isn",
"t",
"already",
"open",
"."
] | jupyter-widgets/ipywidgets | python | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L424-L437 | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"comm",
"is",
"None",
":",
"state",
",",
"buffer_paths",
",",
"buffers",
"=",
"_remove_buffers",
"(",
"self",
".",
"get_state",
"(",
")",
")",
"args",
"=",
"dict",
"(",
"target_name",
"=",
"'ju... | 36fe37594cd5a268def228709ca27e37b99ac606 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.