id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
37,267 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
def str2bool(string):
str2val = {"True": True, "False": False}
if string in str2val:
return str2val[string]
else:
raise ValueError(f"Expected one of {set(str2val.keys())}, got {string}") | null |
37,268 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
def optional_int(string):
return None if string == "None" else int(string) | null |
37,269 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
def optional_float(string):
return None if string == "None" else float(string) | null |
37,270 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
def compression_ratio(text) -> float:
text_bytes = text.encode("utf-8")
return len(text_bytes) / len(zlib.compress(text_bytes)) | null |
37,271 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
def format_timestamp(seconds: float, always_include_hours: bool = False, decimal_marker: str = '.'):
assert seconds >= 0, "non-negative timestamp expected"
milliseconds = round(seconds * 1000.0)
hours = milliseconds // 3_600_... | null |
37,272 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
class WriteTXT(ResultWriter):
extension: str = "txt"
def write_result(self, result: dict, file: TextIO):
for segment in result["segments"]:
print(segment['text'].strip(), file=file, flush=True)
class WriteVTT(Re... | null |
37,273 | from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Sequence, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.distributions import Categorical
from .audio import CHUNK_LENGTH
from .tokenizer import To... | Detect the spoken language in the audio, and return them as list of strings, along with the ids of the most probable language tokens and the probability distribution over all language tokens. This is performed outside the main decode loop in order to not interfere with kv-caching. Returns ------- language_tokens : Tens... |
37,274 | from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Sequence, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.distributions import Categorical
from .audio import CHUNK_LENGTH
from .tokenizer import To... | Performs decoding of 30-second audio segment(s), provided as Mel spectrogram(s). Parameters ---------- model: Whisper the Whisper model instance mel: torch.Tensor, shape = (80, 3000) or (*, 80, 3000) A tensor containing the Mel spectrogram(s) options: DecodingOptions A dataclass that contains all necessary options for ... |
37,275 | from functools import lru_cache
from typing import Union
import ffmpeg
import numpy as np
import torch
import torch.nn.functional as F
from librosa.filters import mel as librosa_mel_fn
from .utils import exact_div
N_SAMPLES = CHUNK_LENGTH * SAMPLE_RATE
The provided code snippet includes necessary dependencies for impl... | Pad or trim the audio array to N_SAMPLES, as expected by the encoder. |
37,276 | from functools import lru_cache
from typing import Union
import ffmpeg
import numpy as np
import torch
import torch.nn.functional as F
from librosa.filters import mel as librosa_mel_fn
from .utils import exact_div
N_FFT = 400
N_MELS = 80
HOP_LENGTH = 160
def load_audio(file: str, sr: int = SAMPLE_RATE):
"""
O... | Compute the log-Mel spectrogram of Parameters ---------- audio: Union[str, np.ndarray, torch.Tensor], shape = (*) The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz n_mels: int The number of Mel-frequency filters, only 80 is supported Returns ------- torch.Tensor, shape = (80, n... |
37,277 | from dataclasses import dataclass
from typing import Dict, Iterable, Optional
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from .decoding import decode as decode_function
from .decoding import detect_language as detect_language_function
The provided code snippet includes... | Returns sinusoids for positional embedding |
37,278 | import math
from collections import defaultdict
from typing import List, Optional, Tuple
import torch
from torch import Tensor, nn
from torch.nn import Module
from .hardconcrete import HardConcrete
from .pruning_utils import (
prune_conv1d_layer,
prune_layer_norm,
prune_linear_layer,
)
The provided code sn... | Generate the padding mask given the padded input and the lengths Tensors. Args: input (Tensor): The padded Tensor of dimension `[batch, max_len, frequency]`. lengths (Tensor): The lengths Tensor of dimension `[batch,]`. Returns: (Tensor): The padding mask. |
37,279 | from typing import Union
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `prune_linear_layer` function. Write a Python function `def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: str)` to solve the following problem:
Prune linear la... | Prune linear layer in place. |
37,280 | from typing import Union
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `prune_conv1d_layer` function. Write a Python function `def prune_conv1d_layer(layer: nn.Conv1d, index: torch.LongTensor, dim: str)` to solve the following problem:
Prune conv1d in... | Prune conv1d in place. |
37,281 | from typing import Union
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `prune_layer_norm` function. Write a Python function `def prune_layer_norm(layernorm: Union[nn.LayerNorm, nn.GroupNorm], index: torch.LongTensor)` to solve the following problem:
P... | Prune layer norm or group norm in place. |
37,282 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
class Wav2Vec2Model(Module):
"""Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.
Note:
To build the model, pleas... | Builds "base" :class:`~torchaudio.models.Wav2Vec2Model` from *wav2vec 2.0* :cite:`baevski2020wav2vec` Args: encoder_projection_dropout (float): See :py:func:`wav2vec2_model`. encoder_attention_dropout (float): See :py:func:`wav2vec2_model`. encoder_ff_interm_dropout (float): See :py:func:`wav2vec2_model`. encoder_dropo... |
37,283 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
class Wav2Vec2Model(Module):
"""Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.
Note:
To build the model, pleas... | Builds "large" :class:`~torchaudio.models.Wav2Vec2Model` from *wav2vec 2.0* :cite:`baevski2020wav2vec` Args: encoder_projection_dropout (float): See :py:func:`wav2vec2_model`. encoder_attention_dropout (float): See :py:func:`wav2vec2_model`. encoder_ff_interm_dropout (float): See :py:func:`wav2vec2_model`. encoder_drop... |
37,284 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
class Wav2Vec2Model(Module):
"""Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.
Note:
To build the model, pleas... | Builds "large lv-60k" :class:`~torchaudio.models.Wav2Vec2Model` from *wav2vec 2.0* :cite:`baevski2020wav2vec` Args: encoder_projection_dropout (float): See :py:func:`wav2vec2_model`. encoder_attention_dropout (float): See :py:func:`wav2vec2_model`. encoder_ff_interm_dropout (float): See :py:func:`wav2vec2_model`. encod... |
37,285 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
class Wav2Vec2Model(Module):
"""Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.
Note:
To build the model, pleas... | Builds "base" :class:`HuBERT <torchaudio.models.Wav2Vec2Model>` from *HuBERT* :cite:`hsu2021hubert` Args: encoder_projection_dropout (float): See :py:func:`wav2vec2_model`. encoder_attention_dropout (float): See :py:func:`wav2vec2_model`. encoder_ff_interm_dropout (float): See :py:func:`wav2vec2_model`. encoder_dropout... |
37,286 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
class Wav2Vec2Model(Module):
"""Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.
Note:
To build the model, pleas... | Builds "large" :class:`HuBERT <torchaudio.models.Wav2Vec2Model>` from *HuBERT* :cite:`hsu2021hubert` Args: encoder_projection_dropout (float): See :py:func:`wav2vec2_model`. encoder_attention_dropout (float): See :py:func:`wav2vec2_model`. encoder_ff_interm_dropout (float): See :py:func:`wav2vec2_model`. encoder_dropou... |
37,287 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
class Wav2Vec2Model(Module):
"""Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.
Note:
To build the model, pleas... | Builds "extra large" :class:`HuBERT <torchaudio.models.Wav2Vec2Model>` from *HuBERT* :cite:`hsu2021hubert` Args: encoder_projection_dropout (float): See :py:func:`wav2vec2_model`. encoder_attention_dropout (float): See :py:func:`wav2vec2_model`. encoder_ff_interm_dropout (float): See :py:func:`wav2vec2_model`. encoder_... |
37,288 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
def _init_hubert_pretrain_model(module):
if isinstance(module, components.LayerNorm):
torch.nn.init.kaiming_normal_(module.conv.wei... | null |
37,289 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
class Wav2Vec2Model(Module):
"""Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.
Note:
To build the model, pleas... | Builds "base" WaveLM model :cite:`chen2022wavlm`. The architecture is compatible with Wav2Vec2 model :cite:`baevski2020wav2vec`, and so the output class is :class:`~torchaudio.models.Wav2Vec2Model`. Args: encoder_projection_dropout (float): See :py:func:`wav2vec2_model`. encoder_attention_dropout (float): See :py:func:... |
37,290 | import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from . import components
class Wav2Vec2Model(Module):
"""Acoustic model used in *wav2vec 2.0* :cite:`baevski2020wav2vec`.
Note:
To build the model, pleas... | Builds "large" WaveLM model :cite:`chen2022wavlm`. The architecture is compatible with Wav2Vec2 model :cite:`baevski2020wav2vec`, and so the output class is :class:`~torchaudio.models.Wav2Vec2Model`. Args: encoder_projection_dropout (float): See :py:func:`wav2vec2_model`. encoder_attention_dropout (float): See :py:func... |
37,291 | import logging
from typing import Any, Dict
from torch.nn import Module
from ..model import Wav2Vec2Model, wav2vec2_model, wavlm_model
_LG = logging.getLogger(__name__)
def _get_config(cfg):
config = {
"extractor_mode": f"{cfg.feat_extract_norm}_norm",
"extractor_conv_layer_config": list(zip(cfg.con... | Builds :class:`Wav2Vec2Model` from the corresponding model object of `Transformers <https://huggingface.co/transformers/>`_. Args: original (torch.nn.Module): An instance of ``Wav2Vec2ForCTC`` from ``transformers``. Returns: Wav2Vec2Model: Imported model. Example >>> from torchaudio.models.wav2vec2.utils import import_... |
37,292 | import io
import numpy as np
import soundfile
from flask import Flask, request, send_file
from inference import infer_tool, slicer
def wav2wav():
request_form = request.form
audio_path = request_form.get("audio_path", None) # wav文件地址
tran = int(float(request_form.get("tran", 0))) # 音调
spk = request_f... | null |
37,293 | import argparse
import json
import torch
import utils
from onnxexport.model_onnx_speaker_mix import SynthesizerTrn
class SynthesizerTrn(nn.Module):
"""
Synthesizer for Training
"""
def __init__(self,
spec_channels,
segment_size,
inter_channels,
... | null |
37,294 | import glob
import os
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def plot_spectrogram(spectrogram):
fig, ax = plt.subplots(figsize=(10, 2))
im = ax.imshow(spectrogram, aspect="auto", origin="lower",
interpolation='none')
plt.colorbar(im, ax=ax)
... | null |
37,295 | import glob
import os
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std) | null |
37,296 | import glob
import os
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def apply_weight_norm(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
weight_norm(m) | null |
37,297 | import glob
import os
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def get_padding(kernel_size, dilation=1):
return int((kernel_size*dilation - dilation)/2) | null |
37,298 | import glob
import os
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def load_checkpoint(filepath, device):
assert os.path.isfile(filepath)
print("Loading '{}'".format(filepath))
checkpoint_dict = torch.load(filepath, map_location=device)
print("Complete.")
retur... | null |
37,299 | import glob
import os
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def save_checkpoint(filepath, obj):
print("Saving checkpoint to {}".format(filepath))
torch.save(obj, filepath)
print("Complete.") | null |
37,300 | import glob
import os
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def del_old_checkpoints(cp_dir, prefix, n_models=2):
pattern = os.path.join(cp_dir, prefix + '????????')
cp_list = glob.glob(pattern) # get checkpoint paths
cp_list = sorted(cp_list)# sort by iter
i... | null |
37,301 | import glob
import os
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def scan_checkpoint(cp_dir, prefix):
pattern = os.path.join(cp_dir, prefix + '????????')
cp_list = glob.glob(pattern)
if len(cp_list) == 0:
return None
return sorted(cp_list)[-1] | null |
37,302 | import os
import librosa
import numpy as np
import soundfile as sf
import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False):
sampling_rate = None
try:
data, sampling_rate = sf.read(full_path,... | null |
37,303 | import os
import librosa
import numpy as np
import soundfile as sf
import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def dynamic_range_compression(x, C=1, clip_val=1e-5):
return np.log(np.clip(x, a_min=clip_val, a_max=None) * C) | null |
37,304 | import os
import librosa
import numpy as np
import soundfile as sf
import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def dynamic_range_decompression(x, C=1):
return np.exp(x) / C | null |
37,305 | import os
import librosa
import numpy as np
import soundfile as sf
import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
return torch.log(torch.clamp(x, min=clip_val) * C) | null |
37,306 | import os
import librosa
import numpy as np
import soundfile as sf
import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def dynamic_range_decompression_torch(x, C=1):
return torch.exp(x) / C | null |
37,307 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from vdecoder.hifiganwithsnake.alias.act import SnakeAlias
from .env impor... | null |
37,308 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from vdecoder.hifiganwithsnake.alias.act import SnakeAlias
from .env impor... | null |
37,309 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from vdecoder.hifiganwithsnake.alias.act import SnakeAlias
from .env impor... | null |
37,310 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from vdecoder.hifiganwithsnake.alias.act import SnakeAlias
from .env impor... | null |
37,311 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from vdecoder.hifiganwithsnake.alias.act import SnakeAlias
from .env impor... | null |
37,312 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
if 'sinc' in dir(torch):
sinc = torch.sinc
else:
# This code is adopted from adefossez's julius.core.sinc under the MIT License
# https://adefossez.github.io/julius/julius/core.html
# LICENSE is in incl_licenses directory.
... | null |
37,327 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from .env import AttrDict
from .utils import get_padding, init_weights
cla... | null |
37,328 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from .env import AttrDict
from .utils import get_padding, init_weights
de... | null |
37,329 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from .env import AttrDict
from .utils import get_padding, init_weights
de... | null |
37,330 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from .env import AttrDict
from .utils import get_padding, init_weights
de... | null |
37,331 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from .env import AttrDict
from .utils import get_padding, init_weights
de... | null |
37,333 | import glob
import os
import matplotlib
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def plot_spectrogram(spectrogram):
fig, ax = plt.subplots(figsize=(10, 2))
im = ax.imshow(spectrogram, aspect="auto", origin="lower",
interpolation='none')
plt.color... | null |
37,334 | import glob
import os
import matplotlib
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std) | null |
37,335 | import glob
import os
import matplotlib
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def apply_weight_norm(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
weight_norm(m) | null |
37,336 | import glob
import os
import matplotlib
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def get_padding(kernel_size, dilation=1):
return int((kernel_size*dilation - dilation)/2) | null |
37,337 | import glob
import os
import matplotlib
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def load_checkpoint(filepath, device):
assert os.path.isfile(filepath)
print("Loading '{}'".format(filepath))
checkpoint_dict = torch.load(filepath, map_location=device)
print("Com... | null |
37,338 | import glob
import os
import matplotlib
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def save_checkpoint(filepath, obj):
print("Saving checkpoint to {}".format(filepath))
torch.save(obj, filepath)
print("Complete.") | null |
37,339 | import glob
import os
import matplotlib
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def del_old_checkpoints(cp_dir, prefix, n_models=2):
pattern = os.path.join(cp_dir, prefix + '????????')
cp_list = glob.glob(pattern) # get checkpoint paths
cp_list = sorted(cp_list)# ... | null |
37,340 | import glob
import os
import matplotlib
import matplotlib.pylab as plt
import torch
from torch.nn.utils import weight_norm
def scan_checkpoint(cp_dir, prefix):
pattern = os.path.join(cp_dir, prefix + '????????')
cp_list = glob.glob(pattern)
if len(cp_list) == 0:
return None
return sorted(cp_lis... | null |
37,346 | import json
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from .env import AttrDict
from .utils import get_padding, init_weights
def... | null |
37,351 | import argparse
import logging
import os
import random
from concurrent.futures import ProcessPoolExecutor
from glob import glob
from random import shuffle
import librosa
import numpy as np
import torch
import torch.multiprocessing as mp
from loguru import logger
from tqdm import tqdm
import diffusion.logger.utils as du... | null |
37,352 | import os
import re
from typing import List
import numpy as np
import torch
from evaluators.evaluator import Evaluator
from tqdm import tqdm
def sample_top_p(probs, p):
probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
probs_sum = torch.cumsum(probs_sort, dim=-1)
mask = probs_sum - probs_s... | null |
37,353 | import json
import os
import time
from evaluators.llama import LLaMA_Evaluator
from pathlib import Path
from typing import Tuple
import fire
import pandas as pd
import torch
from fairscale.nn.model_parallel.initialize import initialize_model_parallel
from llama import ModelArgs, Tokenizer, Transformer
choices = ["A", "... | null |
37,354 | from subprocess import check_output
from typing import List, Optional, Tuple
from recoverpy.models.partition import Partition
def _fetch_lsblk_output() -> str:
return check_output(
["lsblk", "-r", "-n", "-o", "NAME,TYPE,FSTYPE,MOUNTPOINT"],
encoding="utf-8",
)
def _parse_lsblk_output(lsblk_outpu... | null |
37,355 | from os import geteuid
from platform import system
from sys import exit, version_info
from textual.app import App
from recoverpy.lib.helper import is_dependency_installed
from recoverpy.log.logger import log
from recoverpy.ui.screens.modal import install_and_push_modal
_root_error_message = "The current user is not roo... | null |
37,356 | from __future__ import annotations
from io import BufferedReader
from queue import Queue
from subprocess import PIPE, Popen
from threading import Thread
from typing import Callable
from recoverpy.lib.helper import is_dependency_installed
from recoverpy.lib.search.progress_monitoring import monitor_search_progress
from ... | null |
37,357 | from __future__ import annotations
from io import BufferedReader
from queue import Queue
from subprocess import PIPE, Popen
from threading import Thread
from typing import Callable
from recoverpy.lib.helper import is_dependency_installed
from recoverpy.lib.search.progress_monitoring import monitor_search_progress
from ... | null |
37,358 | from __future__ import annotations
from io import BufferedReader
from queue import Queue
from subprocess import PIPE, Popen
from threading import Thread
from typing import Callable
from recoverpy.lib.helper import is_dependency_installed
from recoverpy.lib.search.progress_monitoring import monitor_search_progress
from ... | null |
37,359 | from __future__ import annotations
from io import BufferedReader
from queue import Queue
from subprocess import PIPE, Popen
from threading import Thread
from typing import Callable
from recoverpy.lib.helper import is_dependency_installed
from recoverpy.lib.search.progress_monitoring import monitor_search_progress
from ... | null |
37,360 | from __future__ import annotations
from asyncio import AbstractEventLoop
from asyncio import Queue as AsyncQueue
from asyncio import new_event_loop
from io import BufferedReader
from queue import Queue
from subprocess import Popen
from typing import List
from recoverpy.lib.helper import get_dd_output, decode_result, ge... | null |
37,361 | from re import findall
from subprocess import DEVNULL, call, check_output
def decode_result(result: bytes) -> str:
return result.decode("utf-8", errors="ignore") | null |
37,362 | from re import findall
from subprocess import DEVNULL, call, check_output
def get_printable(result: str) -> str:
return "".join(([c for c in result.replace("\n", " ") if c.isprintable()])) | null |
37,363 | from re import findall
from subprocess import DEVNULL, call, check_output
def get_block_size(partition: str) -> int:
return int(
check_output(
["blockdev", "--getbsz", partition],
encoding="utf-8",
)
) | null |
37,364 | from re import findall
from subprocess import DEVNULL, call, check_output
def get_inode(string: str) -> int:
match = findall(r"^(\d+):", string)
return int(match[0]) | null |
37,365 | from re import findall
from subprocess import DEVNULL, call, check_output
def get_dd_output(partition: str, block_size: int, inode: int) -> bytes:
return check_output(
[
"dd",
f"if={partition}",
"count=1",
"status=none",
f"bs={block_size}",
... | null |
37,366 | from typing import Dict, Optional
from textual.widgets import Label, ListItem, ListView
from recoverpy.lib.lsblk import get_partitions
from recoverpy.log.logger import log
from recoverpy.models.partition import Partition
class Partition:
name: str
fs_type: str
is_mounted: bool
mount_point: Optional[str... | null |
37,367 | from typing import Dict, Optional
from textual.widgets import Label, ListItem, ListView
from recoverpy.lib.lsblk import get_partitions
from recoverpy.log.logger import log
from recoverpy.models.partition import Partition
class Partition:
name: str
fs_type: str
is_mounted: bool
mount_point: Optional[str... | null |
37,368 | import plistlib
import pprint
import xml
from typing import IO, Optional
import click
from scapy.packet import Packet, Raw
from scapy.sendrecv import sniff
The provided code snippet includes necessary dependencies for implementing the `cli` function. Write a Python function `def cli()` to solve the following problem:
... | Parse RemoteXPC traffic |
37,369 | import plistlib
import pprint
import xml
from typing import IO, Optional
import click
from scapy.packet import Packet, Raw
from scapy.sendrecv import sniff
class PcapSniffer:
def __init__(self, file: Optional[IO] = None):
self.file = file
def process_packet(self, packet: Packet) -> None:
packet ... | Parse RemoteXPC traffic from a .pcap file |
37,370 | import plistlib
import pprint
import xml
from typing import IO, Optional
import click
from scapy.packet import Packet, Raw
from scapy.sendrecv import sniff
class PcapSniffer:
def __init__(self, file: Optional[IO] = None):
self.file = file
def process_packet(self, packet: Packet) -> None:
packet ... | Parse RemoteXPC live from a given network interface |
37,371 | import logging
from pprint import pformat
from typing import List, MutableMapping, Optional
import click
import coloredlogs
from construct import ConstError, StreamError
from hexdump import hexdump
from hyperframe.frame import DataFrame, Frame, GoAwayFrame, HeadersFrame
from scapy.layers.inet import IP, TCP
from scapy.... | null |
37,372 | import logging
from pprint import pformat
from typing import List, MutableMapping, Optional
import click
import coloredlogs
from construct import ConstError, StreamError
from hexdump import hexdump
from hyperframe.frame import DataFrame, Frame, GoAwayFrame, HeadersFrame
from scapy.layers.inet import IP, TCP
from scapy.... | Parse RemoteXPC traffic |
37,373 | import logging
from pprint import pformat
from typing import List, MutableMapping, Optional
import click
import coloredlogs
from construct import ConstError, StreamError
from hexdump import hexdump
from hyperframe.frame import DataFrame, Frame, GoAwayFrame, HeadersFrame
from scapy.layers.inet import IP, TCP
from scapy.... | Parse RemoteXPC traffic from a .pcap file |
37,374 | import logging
from pprint import pformat
from typing import List, MutableMapping, Optional
import click
import coloredlogs
from construct import ConstError, StreamError
from hexdump import hexdump
from hyperframe.frame import DataFrame, Frame, GoAwayFrame, HeadersFrame
from scapy.layers.inet import IP, TCP
from scapy.... | Parse RemoteXPC live from a given network interface |
37,375 | import asyncio
import platform
import socket
import traceback
from functools import wraps
from typing import Callable
from construct import Int8ul, Int16ul, Int32ul, Int64ul, Select
def plist_access_path(d, path: tuple, type_=None, required=False):
for component in path:
d = d.get(component)
if d i... | null |
37,376 | import asyncio
import platform
import socket
import traceback
from functools import wraps
from typing import Callable
from construct import Int8ul, Int16ul, Int32ul, Int64ul, Select
def bytes_to_uint(b: bytes):
return Select(u64=Int64ul, u32=Int32ul, u16=Int16ul, u8=Int8ul).parse(b) | null |
37,377 | import asyncio
import platform
import socket
import traceback
from functools import wraps
from typing import Callable
from construct import Int8ul, Int16ul, Int32ul, Int64ul, Select
def try_decode(s: bytes):
try:
return s.decode('utf8')
except UnicodeDecodeError:
return s | null |
37,378 | import asyncio
import platform
import socket
import traceback
from functools import wraps
from typing import Callable
from construct import Int8ul, Int16ul, Int32ul, Int64ul, Select
def asyncio_print_traceback(f: Callable):
@wraps(f)
async def wrapper(*args, **kwargs):
try:
return await f(*... | null |
37,379 | import asyncio
import platform
import socket
import traceback
from functools import wraps
from typing import Callable
from construct import Int8ul, Int16ul, Int32ul, Int64ul, Select
DEFAULT_AFTER_IDLE_SEC = 3
DEFAULT_INTERVAL_SEC = 3
DEFAULT_MAX_FAILS = 3
def _set_keepalive_linux(sock: socket.socket, after_idle_sec: in... | set keep-alive parameters on a given socket :param sock: socket to operate on :param after_idle_sec: idle time used when SO_KEEPALIVE is enabled :param interval_sec: interval between keepalives :param max_fails: number of keepalives before close |
37,380 | import datetime
import logging
import os
import plistlib
import tempfile
import time
from abc import ABC, abstractmethod
from contextlib import contextmanager, suppress
from enum import Enum
from functools import wraps
from pathlib import Path
from typing import Dict, Mapping, Optional
from packaging.version import Ver... | lockdownd's _socket_select will close the connection after 60 seconds of "radio-silent" (no data has been transmitted). When this happens, we'll attempt to reconnect. |
37,381 | import datetime
import logging
import os
import plistlib
import tempfile
import time
from abc import ABC, abstractmethod
from contextlib import contextmanager, suppress
from enum import Enum
from functools import wraps
from pathlib import Path
from typing import Dict, Mapping, Optional
from packaging.version import Ver... | Create a TcpLockdownClient instance :param hostname: The target device hostname :param identifier: Used as an identifier to look for the device pair record :param label: lockdownd user-agent :param autopair: Attempt to pair with device (blocking) if not already paired :param pair_timeout: Timeout for autopair :param lo... |
37,382 | import datetime
import logging
import os
import plistlib
import tempfile
import time
from abc import ABC, abstractmethod
from contextlib import contextmanager, suppress
from enum import Enum
from functools import wraps
from pathlib import Path
from typing import Dict, Mapping, Optional
from packaging.version import Ver... | Create a TcpLockdownClient instance over RSD :param hostname: The target device hostname :param identifier: Used as an identifier to look for the device pair record :param label: lockdownd user-agent :param autopair: Attempt to pair with device (blocking) if not already paired :param pair_timeout: Timeout for autopair ... |
37,383 | import logging
import os
import platform
import plistlib
import sys
import uuid
from contextlib import suppress
from pathlib import Path
from typing import Mapping, Optional
from pymobiledevice3 import usbmux
from pymobiledevice3.common import get_home_folder
from pymobiledevice3.exceptions import MuxException, NotPair... | null |
37,384 | import logging
import os
import platform
import plistlib
import sys
import uuid
from contextlib import suppress
from pathlib import Path
from typing import Mapping, Optional
from pymobiledevice3 import usbmux
from pymobiledevice3.common import get_home_folder
from pymobiledevice3.exceptions import MuxException, NotPair... | look for an existing pair record to connected device by following order: - usbmuxd - iTunes - local storage |
37,385 | import logging
import os
import platform
import plistlib
import sys
import uuid
from contextlib import suppress
from pathlib import Path
from typing import Mapping, Optional
from pymobiledevice3 import usbmux
from pymobiledevice3.common import get_home_folder
from pymobiledevice3.exceptions import MuxException, NotPair... | null |
37,386 | import logging
import sys
import traceback
import click
import coloredlogs
from pymobiledevice3.exceptions import AccessDeniedError, ConnectionFailedToUsbmuxdError, DeprecationError, \
DeveloperModeError, DeveloperModeIsNotEnabledError, DeviceHasPasscodeSetError, DeviceNotFoundError, InternalError, \
InvalidSer... | null |
37,387 | import logging
import plistlib
import typing
from uuid import uuid4
import asn1
import requests
from ipsw_parser.img4 import COMPONENT_FOURCC
from pymobiledevice3.exceptions import PyMobileDevice3Exception
from pymobiledevice3.utils import bytes_to_uint, plist_access_path
def get_with_or_without_comma(obj: typing.Mapp... | null |
37,388 | import logging
import plistlib
import select
import socket
import struct
import threading
from enum import Enum
from pymobiledevice3 import usbmux
from pymobiledevice3.exceptions import ConnectionFailedError, NoDeviceConnectedError, PyMobileDevice3Exception
from pymobiledevice3.service_connection import LockdownService... | null |
37,389 | from datetime import datetime, timedelta
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, PrivateFormat, load_pem_public_key
from cryptography.x509.oi... | null |
37,390 | import json
import logging
import os.path
from uuid import UUID
import click
import coloredlogs
MAP_FILENAME = os.path.join(os.path.dirname(__file__), 'dsc_uuid_map.json')
def get_dsc_map(dsc_uuid):
with open(MAP_FILENAME) as f:
uuid_map = json.load(f)
return uuid_map.get(dsc_uuid) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.