repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
mishbahr/djangocms-forms
djangocms_forms/admin.py
FormSubmissionAdmin.get_urls
def get_urls(self): """ Add the export view to urls. """ urls = super(FormSubmissionAdmin, self).get_urls() from django.conf.urls import url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs)...
python
def get_urls(self): """ Add the export view to urls. """ urls = super(FormSubmissionAdmin, self).get_urls() from django.conf.urls import url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs)...
[ "def", "get_urls", "(", "self", ")", ":", "urls", "=", "super", "(", "FormSubmissionAdmin", ",", "self", ")", ".", "get_urls", "(", ")", "from", "django", ".", "conf", ".", "urls", "import", "url", "def", "wrap", "(", "view", ")", ":", "def", "wrappe...
Add the export view to urls.
[ "Add", "the", "export", "view", "to", "urls", "." ]
train
https://github.com/mishbahr/djangocms-forms/blob/9d7a4ef9769fd5e1526921c084d6da7b8070a2c1/djangocms_forms/admin.py#L96-L113
mishbahr/djangocms-forms
djangocms_forms/admin.py
FormSubmissionAdmin.export_view
def export_view(self, request, form_url=''): """The 'export' admin view for this model.""" info = self.opts.app_label, self.opts.model_name if not self.has_export_permission(request): raise PermissionDenied form = SubmissionExportForm(data=request.POST if request.method ==...
python
def export_view(self, request, form_url=''): """The 'export' admin view for this model.""" info = self.opts.app_label, self.opts.model_name if not self.has_export_permission(request): raise PermissionDenied form = SubmissionExportForm(data=request.POST if request.method ==...
[ "def", "export_view", "(", "self", ",", "request", ",", "form_url", "=", "''", ")", ":", "info", "=", "self", ".", "opts", ".", "app_label", ",", "self", ".", "opts", ".", "model_name", "if", "not", "self", ".", "has_export_permission", "(", "request", ...
The 'export' admin view for this model.
[ "The", "export", "admin", "view", "for", "this", "model", "." ]
train
https://github.com/mishbahr/djangocms-forms/blob/9d7a4ef9769fd5e1526921c084d6da7b8070a2c1/djangocms_forms/admin.py#L138-L258
mishbahr/djangocms-forms
djangocms_forms/admin.py
FormSubmissionAdmin.render_export_form
def render_export_form(self, request, context, form_url=''): """ Render the from submission export form. """ context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), 'opts': self.opts, ...
python
def render_export_form(self, request, context, form_url=''): """ Render the from submission export form. """ context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), 'opts': self.opts, ...
[ "def", "render_export_form", "(", "self", ",", "request", ",", "context", ",", "form_url", "=", "''", ")", ":", "context", ".", "update", "(", "{", "'has_change_permission'", ":", "self", ".", "has_change_permission", "(", "request", ")", ",", "'form_url'", ...
Render the from submission export form.
[ "Render", "the", "from", "submission", "export", "form", "." ]
train
https://github.com/mishbahr/djangocms-forms/blob/9d7a4ef9769fd5e1526921c084d6da7b8070a2c1/djangocms_forms/admin.py#L260-L272
mishbahr/djangocms-forms
djangocms_forms/forms.py
FormDefinitionAdminForm.clean_form_template
def clean_form_template(self): """ Check if template exists """ form_template = self.cleaned_data.get('form_template', '') if form_template: try: get_template(form_template) except TemplateDoesNotExist: msg = _('Selected Form Template does ...
python
def clean_form_template(self): """ Check if template exists """ form_template = self.cleaned_data.get('form_template', '') if form_template: try: get_template(form_template) except TemplateDoesNotExist: msg = _('Selected Form Template does ...
[ "def", "clean_form_template", "(", "self", ")", ":", "form_template", "=", "self", ".", "cleaned_data", ".", "get", "(", "'form_template'", ",", "''", ")", "if", "form_template", ":", "try", ":", "get_template", "(", "form_template", ")", "except", "TemplateDo...
Check if template exists
[ "Check", "if", "template", "exists" ]
train
https://github.com/mishbahr/djangocms-forms/blob/9d7a4ef9769fd5e1526921c084d6da7b8070a2c1/djangocms_forms/forms.py#L75-L84
nikdon/pyEntropy
pyentrp/entropy.py
_embed
def _embed(x, order=3, delay=1): """Time-delay embedding. Parameters ---------- x : 1d-array, shape (n_times) Time series order : int Embedding dimension (order) delay : int Delay. Returns ------- embedded : ndarray, shape (n_times - (order - 1) * delay, ord...
python
def _embed(x, order=3, delay=1): """Time-delay embedding. Parameters ---------- x : 1d-array, shape (n_times) Time series order : int Embedding dimension (order) delay : int Delay. Returns ------- embedded : ndarray, shape (n_times - (order - 1) * delay, ord...
[ "def", "_embed", "(", "x", ",", "order", "=", "3", ",", "delay", "=", "1", ")", ":", "N", "=", "len", "(", "x", ")", "Y", "=", "np", ".", "empty", "(", "(", "order", ",", "N", "-", "(", "order", "-", "1", ")", "*", "delay", ")", ")", "f...
Time-delay embedding. Parameters ---------- x : 1d-array, shape (n_times) Time series order : int Embedding dimension (order) delay : int Delay. Returns ------- embedded : ndarray, shape (n_times - (order - 1) * delay, order) Embedded time-series.
[ "Time", "-", "delay", "embedding", "." ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L10-L31
nikdon/pyEntropy
pyentrp/entropy.py
util_pattern_space
def util_pattern_space(time_series, lag, dim): """Create a set of sequences with given lag and dimension Args: time_series: Vector or string of the sample data lag: Lag between beginning of sequences dim: Dimension (number of patterns) Returns: 2D array of vectors """ ...
python
def util_pattern_space(time_series, lag, dim): """Create a set of sequences with given lag and dimension Args: time_series: Vector or string of the sample data lag: Lag between beginning of sequences dim: Dimension (number of patterns) Returns: 2D array of vectors """ ...
[ "def", "util_pattern_space", "(", "time_series", ",", "lag", ",", "dim", ")", ":", "n", "=", "len", "(", "time_series", ")", "if", "lag", "*", "dim", ">", "n", ":", "raise", "Exception", "(", "'Result matrix exceeded size limit, try to change lag or dim.'", ")",...
Create a set of sequences with given lag and dimension Args: time_series: Vector or string of the sample data lag: Lag between beginning of sequences dim: Dimension (number of patterns) Returns: 2D array of vectors
[ "Create", "a", "set", "of", "sequences", "with", "given", "lag", "and", "dimension" ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L34-L57
nikdon/pyEntropy
pyentrp/entropy.py
util_granulate_time_series
def util_granulate_time_series(time_series, scale): """Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor """ n = len(time_series) b = int(np.fix(n / scale)) tem...
python
def util_granulate_time_series(time_series, scale): """Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor """ n = len(time_series) b = int(np.fix(n / scale)) tem...
[ "def", "util_granulate_time_series", "(", "time_series", ",", "scale", ")", ":", "n", "=", "len", "(", "time_series", ")", "b", "=", "int", "(", "np", ".", "fix", "(", "n", "/", "scale", ")", ")", "temp", "=", "np", ".", "reshape", "(", "time_series"...
Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor
[ "Extract", "coarse", "-", "grained", "time", "series" ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L64-L78
nikdon/pyEntropy
pyentrp/entropy.py
shannon_entropy
def shannon_entropy(time_series): """Return the Shannon Entropy of the sample data. Args: time_series: Vector or string of the sample data Returns: The Shannon Entropy as float value """ # Check if string if not isinstance(time_series, str): time_series = list(time_ser...
python
def shannon_entropy(time_series): """Return the Shannon Entropy of the sample data. Args: time_series: Vector or string of the sample data Returns: The Shannon Entropy as float value """ # Check if string if not isinstance(time_series, str): time_series = list(time_ser...
[ "def", "shannon_entropy", "(", "time_series", ")", ":", "# Check if string", "if", "not", "isinstance", "(", "time_series", ",", "str", ")", ":", "time_series", "=", "list", "(", "time_series", ")", "# Create a frequency data", "data_set", "=", "list", "(", "set...
Return the Shannon Entropy of the sample data. Args: time_series: Vector or string of the sample data Returns: The Shannon Entropy as float value
[ "Return", "the", "Shannon", "Entropy", "of", "the", "sample", "data", "." ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L81-L110
nikdon/pyEntropy
pyentrp/entropy.py
sample_entropy
def sample_entropy(time_series, sample_length, tolerance = None): """Calculates the sample entropy of degree m of a time_series. This method uses chebychev norm. It is quite fast for random data, but can be slower is there is structure in the input time series. Args: time_series: numpy arr...
python
def sample_entropy(time_series, sample_length, tolerance = None): """Calculates the sample entropy of degree m of a time_series. This method uses chebychev norm. It is quite fast for random data, but can be slower is there is structure in the input time series. Args: time_series: numpy arr...
[ "def", "sample_entropy", "(", "time_series", ",", "sample_length", ",", "tolerance", "=", "None", ")", ":", "#The code below follows the sample length convention of Ref [1] so:", "M", "=", "sample_length", "-", "1", "time_series", "=", "np", ".", "array", "(", "time_s...
Calculates the sample entropy of degree m of a time_series. This method uses chebychev norm. It is quite fast for random data, but can be slower is there is structure in the input time series. Args: time_series: numpy array of time series sample_length: length of longest template vecto...
[ "Calculates", "the", "sample", "entropy", "of", "degree", "m", "of", "a", "time_series", "." ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L113-L179
nikdon/pyEntropy
pyentrp/entropy.py
multiscale_entropy
def multiscale_entropy(time_series, sample_length, tolerance = None, maxscale = None): """Calculate the Multiscale Entropy of the given time series considering different time-scales of the time series. Args: time_series: Time series for analysis sample_length: Bandwidth or group of points ...
python
def multiscale_entropy(time_series, sample_length, tolerance = None, maxscale = None): """Calculate the Multiscale Entropy of the given time series considering different time-scales of the time series. Args: time_series: Time series for analysis sample_length: Bandwidth or group of points ...
[ "def", "multiscale_entropy", "(", "time_series", ",", "sample_length", ",", "tolerance", "=", "None", ",", "maxscale", "=", "None", ")", ":", "if", "tolerance", "is", "None", ":", "#we need to fix the tolerance at this level. If it remains 'None' it will be changed in call ...
Calculate the Multiscale Entropy of the given time series considering different time-scales of the time series. Args: time_series: Time series for analysis sample_length: Bandwidth or group of points tolerance: Tolerance (default = 0.1*std(time_series)) Returns: Vector cont...
[ "Calculate", "the", "Multiscale", "Entropy", "of", "the", "given", "time", "series", "considering", "different", "time", "-", "scales", "of", "the", "time", "series", "." ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L182-L209
nikdon/pyEntropy
pyentrp/entropy.py
permutation_entropy
def permutation_entropy(time_series, order=3, delay=1, normalize=False): """Permutation Entropy. Parameters ---------- time_series : list or np.array Time series order : int Order of permutation entropy delay : int Time delay normalize : bool If True, divide ...
python
def permutation_entropy(time_series, order=3, delay=1, normalize=False): """Permutation Entropy. Parameters ---------- time_series : list or np.array Time series order : int Order of permutation entropy delay : int Time delay normalize : bool If True, divide ...
[ "def", "permutation_entropy", "(", "time_series", ",", "order", "=", "3", ",", "delay", "=", "1", ",", "normalize", "=", "False", ")", ":", "x", "=", "np", ".", "array", "(", "time_series", ")", "hashmult", "=", "np", ".", "power", "(", "order", ",",...
Permutation Entropy. Parameters ---------- time_series : list or np.array Time series order : int Order of permutation entropy delay : int Time delay normalize : bool If True, divide by log2(factorial(m)) to normalize the entropy between 0 and 1. Otherwis...
[ "Permutation", "Entropy", "." ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L212-L278
nikdon/pyEntropy
pyentrp/entropy.py
multiscale_permutation_entropy
def multiscale_permutation_entropy(time_series, m, delay, scale): """Calculate the Multiscale Permutation Entropy Args: time_series: Time series for analysis m: Order of permutation entropy delay: Time delay scale: Scale factor Returns: Vector containing Multiscale ...
python
def multiscale_permutation_entropy(time_series, m, delay, scale): """Calculate the Multiscale Permutation Entropy Args: time_series: Time series for analysis m: Order of permutation entropy delay: Time delay scale: Scale factor Returns: Vector containing Multiscale ...
[ "def", "multiscale_permutation_entropy", "(", "time_series", ",", "m", ",", "delay", ",", "scale", ")", ":", "mspe", "=", "[", "]", "for", "i", "in", "range", "(", "scale", ")", ":", "coarse_time_series", "=", "util_granulate_time_series", "(", "time_series", ...
Calculate the Multiscale Permutation Entropy Args: time_series: Time series for analysis m: Order of permutation entropy delay: Time delay scale: Scale factor Returns: Vector containing Multiscale Permutation Entropy Reference: [1] Francesco Carlo Morabito ...
[ "Calculate", "the", "Multiscale", "Permutation", "Entropy" ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L281-L303
nikdon/pyEntropy
pyentrp/entropy.py
composite_multiscale_entropy
def composite_multiscale_entropy(time_series, sample_length, scale, tolerance=None): """Calculate the Composite Multiscale Entropy of the given time series. Args: time_series: Time series for analysis sample_length: Number of sequential points of the time series scale: Scale factor ...
python
def composite_multiscale_entropy(time_series, sample_length, scale, tolerance=None): """Calculate the Composite Multiscale Entropy of the given time series. Args: time_series: Time series for analysis sample_length: Number of sequential points of the time series scale: Scale factor ...
[ "def", "composite_multiscale_entropy", "(", "time_series", ",", "sample_length", ",", "scale", ",", "tolerance", "=", "None", ")", ":", "cmse", "=", "np", ".", "zeros", "(", "(", "1", ",", "scale", ")", ")", "for", "i", "in", "range", "(", "scale", ")"...
Calculate the Composite Multiscale Entropy of the given time series. Args: time_series: Time series for analysis sample_length: Number of sequential points of the time series scale: Scale factor tolerance: Tolerance (default = 0.1...0.2 * std(time_series)) Returns: Vect...
[ "Calculate", "the", "Composite", "Multiscale", "Entropy", "of", "the", "given", "time", "series", "." ]
train
https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L307-L329
kyan001/ping3
ping3.py
ones_comp_sum16
def ones_comp_sum16(num1: int, num2: int) -> int: """Calculates the 1's complement sum for 16-bit numbers. Args: num1: 16-bit number. num2: 16-bit number. Returns: The calculated result. """ carry = 1 << 16 result = num1 + num2 return result if result < carry else ...
python
def ones_comp_sum16(num1: int, num2: int) -> int: """Calculates the 1's complement sum for 16-bit numbers. Args: num1: 16-bit number. num2: 16-bit number. Returns: The calculated result. """ carry = 1 << 16 result = num1 + num2 return result if result < carry else ...
[ "def", "ones_comp_sum16", "(", "num1", ":", "int", ",", "num2", ":", "int", ")", "->", "int", ":", "carry", "=", "1", "<<", "16", "result", "=", "num1", "+", "num2", "return", "result", "if", "result", "<", "carry", "else", "result", "+", "1", "-",...
Calculates the 1's complement sum for 16-bit numbers. Args: num1: 16-bit number. num2: 16-bit number. Returns: The calculated result.
[ "Calculates", "the", "1", "s", "complement", "sum", "for", "16", "-", "bit", "numbers", "." ]
train
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L34-L47
kyan001/ping3
ping3.py
checksum
def checksum(source: bytes) -> int: """Calculates the checksum of the input bytes. RFC1071: https://tools.ietf.org/html/rfc1071 RFC792: https://tools.ietf.org/html/rfc792 Args: source: The input to be calculated. Returns: Calculated checksum. """ if len(source) % 2: # if ...
python
def checksum(source: bytes) -> int: """Calculates the checksum of the input bytes. RFC1071: https://tools.ietf.org/html/rfc1071 RFC792: https://tools.ietf.org/html/rfc792 Args: source: The input to be calculated. Returns: Calculated checksum. """ if len(source) % 2: # if ...
[ "def", "checksum", "(", "source", ":", "bytes", ")", "->", "int", ":", "if", "len", "(", "source", ")", "%", "2", ":", "# if the total length is odd, padding with one octet of zeros for computing the checksum", "source", "+=", "b'\\x00'", "sum", "=", "0", "for", "...
Calculates the checksum of the input bytes. RFC1071: https://tools.ietf.org/html/rfc1071 RFC792: https://tools.ietf.org/html/rfc792 Args: source: The input to be calculated. Returns: Calculated checksum.
[ "Calculates", "the", "checksum", "of", "the", "input", "bytes", "." ]
train
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L50-L67
kyan001/ping3
ping3.py
send_one_ping
def send_one_ping(sock: socket, dest_addr: str, icmp_id: int, seq: int, size: int): """Sends one ping to the given destination. ICMP Header (bits): type (8), code (8), checksum (16), id (16), sequence (16) ICMP Payload: time (double), data ICMP Wikipedia: https://en.wikipedia.org/wiki/Internet_Control_...
python
def send_one_ping(sock: socket, dest_addr: str, icmp_id: int, seq: int, size: int): """Sends one ping to the given destination. ICMP Header (bits): type (8), code (8), checksum (16), id (16), sequence (16) ICMP Payload: time (double), data ICMP Wikipedia: https://en.wikipedia.org/wiki/Internet_Control_...
[ "def", "send_one_ping", "(", "sock", ":", "socket", ",", "dest_addr", ":", "str", ",", "icmp_id", ":", "int", ",", "seq", ":", "int", ",", "size", ":", "int", ")", ":", "try", ":", "dest_addr", "=", "socket", ".", "gethostbyname", "(", "dest_addr", "...
Sends one ping to the given destination. ICMP Header (bits): type (8), code (8), checksum (16), id (16), sequence (16) ICMP Payload: time (double), data ICMP Wikipedia: https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol Args: sock: Socket. dest_addr: The destination addres...
[ "Sends", "one", "ping", "to", "the", "given", "destination", "." ]
train
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L70-L100
kyan001/ping3
ping3.py
receive_one_ping
def receive_one_ping(sock: socket, icmp_id: int, seq: int, timeout: int) -> float or None: """Receives the ping from the socket. IP Header (bits): version (8), type of service (8), length (16), id (16), flags (16), time to live (8), protocol (8), checksum (16), source ip (32), destination ip (32). ICMP Pac...
python
def receive_one_ping(sock: socket, icmp_id: int, seq: int, timeout: int) -> float or None: """Receives the ping from the socket. IP Header (bits): version (8), type of service (8), length (16), id (16), flags (16), time to live (8), protocol (8), checksum (16), source ip (32), destination ip (32). ICMP Pac...
[ "def", "receive_one_ping", "(", "sock", ":", "socket", ",", "icmp_id", ":", "int", ",", "seq", ":", "int", ",", "timeout", ":", "int", ")", "->", "float", "or", "None", ":", "ip_header_slice", "=", "slice", "(", "0", ",", "struct", ".", "calcsize", "...
Receives the ping from the socket. IP Header (bits): version (8), type of service (8), length (16), id (16), flags (16), time to live (8), protocol (8), checksum (16), source ip (32), destination ip (32). ICMP Packet (bytes): IP Header (20), ICMP Header (8), ICMP Payload (*). Ping Wikipedia: https://en.wik...
[ "Receives", "the", "ping", "from", "the", "socket", "." ]
train
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L103-L149
kyan001/ping3
ping3.py
ping
def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56) -> float or None: """ Send one ping to destination address with the given timeout. Args: dest_addr: The destination address, can be an IP address or a domain name. Ex. "192...
python
def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56) -> float or None: """ Send one ping to destination address with the given timeout. Args: dest_addr: The destination address, can be an IP address or a domain name. Ex. "192...
[ "def", "ping", "(", "dest_addr", ":", "str", ",", "timeout", ":", "int", "=", "4", ",", "unit", ":", "str", "=", "\"s\"", ",", "src_addr", ":", "str", "=", "None", ",", "ttl", ":", "int", "=", "64", ",", "seq", ":", "int", "=", "0", ",", "siz...
Send one ping to destination address with the given timeout. Args: dest_addr: The destination address, can be an IP address or a domain name. Ex. "192.168.1.1"/"example.com" timeout: Timeout in seconds. Default is 4s, same as Windows CMD. (default 4) unit: The unit of returned value. "s" fo...
[ "Send", "one", "ping", "to", "destination", "address", "with", "the", "given", "timeout", "." ]
train
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L152-L188
kyan001/ping3
ping3.py
verbose_ping
def verbose_ping(dest_addr: str, count: int = 4, *args, **kwargs): """ Send pings to destination address with the given timeout and display the result. Args: dest_addr: The destination address. Ex. "192.168.1.1"/"example.com" count: How many pings should be sent. Default is 4, same as Windo...
python
def verbose_ping(dest_addr: str, count: int = 4, *args, **kwargs): """ Send pings to destination address with the given timeout and display the result. Args: dest_addr: The destination address. Ex. "192.168.1.1"/"example.com" count: How many pings should be sent. Default is 4, same as Windo...
[ "def", "verbose_ping", "(", "dest_addr", ":", "str", ",", "count", ":", "int", "=", "4", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "kwargs", ".", "get", "(", "\"timeout\"", ")", "src", "=", "kwargs", ".", "get", "(", "\...
Send pings to destination address with the given timeout and display the result. Args: dest_addr: The destination address. Ex. "192.168.1.1"/"example.com" count: How many pings should be sent. Default is 4, same as Windows CMD. (default 4) *args and **kwargs: And all the other arguments ava...
[ "Send", "pings", "to", "destination", "address", "with", "the", "given", "timeout", "and", "display", "the", "result", "." ]
train
https://github.com/kyan001/ping3/blob/fc9e8a4b828965a800036dfbd019e97114ad80b3/ping3.py#L191-L215
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.distance
def distance(self, val): """ set the distance parameter """ tmp = 2 try: int(val) if val > 0 and val <= 2: tmp = val except (ValueError, TypeError): pass self._distance = tmp
python
def distance(self, val): """ set the distance parameter """ tmp = 2 try: int(val) if val > 0 and val <= 2: tmp = val except (ValueError, TypeError): pass self._distance = tmp
[ "def", "distance", "(", "self", ",", "val", ")", ":", "tmp", "=", "2", "try", ":", "int", "(", "val", ")", "if", "val", ">", "0", "and", "val", "<=", "2", ":", "tmp", "=", "val", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", ...
set the distance parameter
[ "set", "the", "distance", "parameter" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L79-L88
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.export
def export(self, filepath, encoding="utf-8", gzipped=True): """ Export the word frequency list for import in the future Args: filepath (str): The filepath to the exported dictionary encoding (str): The encoding of the resulting output gzipped (bool):...
python
def export(self, filepath, encoding="utf-8", gzipped=True): """ Export the word frequency list for import in the future Args: filepath (str): The filepath to the exported dictionary encoding (str): The encoding of the resulting output gzipped (bool):...
[ "def", "export", "(", "self", ",", "filepath", ",", "encoding", "=", "\"utf-8\"", ",", "gzipped", "=", "True", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ".", "word_frequency", ".", "dictionary", ",", "sort_keys", "=", "True", ")", "writ...
Export the word frequency list for import in the future Args: filepath (str): The filepath to the exported dictionary encoding (str): The encoding of the resulting output gzipped (bool): Whether to gzip the dictionary or not
[ "Export", "the", "word", "frequency", "list", "for", "import", "in", "the", "future" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L100-L108
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.word_probability
def word_probability(self, word, total_words=None): """ Calculate the probability of the `word` being the desired, correct word Args: word (str): The word for which the word probability is \ calculated total_words (int): The total number o...
python
def word_probability(self, word, total_words=None): """ Calculate the probability of the `word` being the desired, correct word Args: word (str): The word for which the word probability is \ calculated total_words (int): The total number o...
[ "def", "word_probability", "(", "self", ",", "word", ",", "total_words", "=", "None", ")", ":", "if", "total_words", "is", "None", ":", "total_words", "=", "self", ".", "_word_frequency", ".", "total_words", "return", "self", ".", "_word_frequency", ".", "di...
Calculate the probability of the `word` being the desired, correct word Args: word (str): The word for which the word probability is \ calculated total_words (int): The total number of words to use in the \ calculation; use the def...
[ "Calculate", "the", "probability", "of", "the", "word", "being", "the", "desired", "correct", "word" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L110-L124
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.correction
def correction(self, word): """ The most probable correct spelling for the word Args: word (str): The word to correct Returns: str: The most likely candidate """ return max(self.candidates(word), key=self.word_probability)
python
def correction(self, word): """ The most probable correct spelling for the word Args: word (str): The word to correct Returns: str: The most likely candidate """ return max(self.candidates(word), key=self.word_probability)
[ "def", "correction", "(", "self", ",", "word", ")", ":", "return", "max", "(", "self", ".", "candidates", "(", "word", ")", ",", "key", "=", "self", ".", "word_probability", ")" ]
The most probable correct spelling for the word Args: word (str): The word to correct Returns: str: The most likely candidate
[ "The", "most", "probable", "correct", "spelling", "for", "the", "word" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L126-L133
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.candidates
def candidates(self, word): """ Generate possible spelling corrections for the provided word up to an edit distance of two, if and only when needed Args: word (str): The word for which to calculate candidate spellings Returns: set: The set of ...
python
def candidates(self, word): """ Generate possible spelling corrections for the provided word up to an edit distance of two, if and only when needed Args: word (str): The word for which to calculate candidate spellings Returns: set: The set of ...
[ "def", "candidates", "(", "self", ",", "word", ")", ":", "if", "self", ".", "known", "(", "[", "word", "]", ")", ":", "# short-cut if word is correct already", "return", "{", "word", "}", "# get edit distance 1...", "res", "=", "[", "x", "for", "x", "in", ...
Generate possible spelling corrections for the provided word up to an edit distance of two, if and only when needed Args: word (str): The word for which to calculate candidate spellings Returns: set: The set of words that are possible candidates
[ "Generate", "possible", "spelling", "corrections", "for", "the", "provided", "word", "up", "to", "an", "edit", "distance", "of", "two", "if", "and", "only", "when", "needed" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L135-L155
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.known
def known(self, words): """ The subset of `words` that appear in the dictionary of words Args: words (list): List of words to determine which are in the \ corpus Returns: set: The set of those words from the input that are in the \ ...
python
def known(self, words): """ The subset of `words` that appear in the dictionary of words Args: words (list): List of words to determine which are in the \ corpus Returns: set: The set of those words from the input that are in the \ ...
[ "def", "known", "(", "self", ",", "words", ")", ":", "tmp", "=", "[", "w", ".", "lower", "(", ")", "for", "w", "in", "words", "]", "return", "set", "(", "w", "for", "w", "in", "tmp", "if", "w", "in", "self", ".", "_word_frequency", ".", "dictio...
The subset of `words` that appear in the dictionary of words Args: words (list): List of words to determine which are in the \ corpus Returns: set: The set of those words from the input that are in the \ corpus
[ "The", "subset", "of", "words", "that", "appear", "in", "the", "dictionary", "of", "words" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L157-L172
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.edit_distance_1
def edit_distance_1(self, word): """ Compute all strings that are one edit away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit...
python
def edit_distance_1(self, word): """ Compute all strings that are one edit away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit...
[ "def", "edit_distance_1", "(", "self", ",", "word", ")", ":", "word", "=", "word", ".", "lower", "(", ")", "if", "self", ".", "_check_if_should_check", "(", "word", ")", "is", "False", ":", "return", "{", "word", "}", "letters", "=", "self", ".", "_w...
Compute all strings that are one edit away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit distance one from the \ prov...
[ "Compute", "all", "strings", "that", "are", "one", "edit", "away", "from", "word", "using", "only", "the", "letters", "in", "the", "corpus" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L186-L204
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.edit_distance_2
def edit_distance_2(self, word): """ Compute all strings that are two edits away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edi...
python
def edit_distance_2(self, word): """ Compute all strings that are two edits away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edi...
[ "def", "edit_distance_2", "(", "self", ",", "word", ")", ":", "word", "=", "word", ".", "lower", "(", ")", "return", "[", "e2", "for", "e1", "in", "self", ".", "edit_distance_1", "(", "word", ")", "for", "e2", "in", "self", ".", "edit_distance_1", "(...
Compute all strings that are two edits away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit distance two from the \ pro...
[ "Compute", "all", "strings", "that", "are", "two", "edits", "away", "from", "word", "using", "only", "the", "letters", "in", "the", "corpus" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L206-L218
barrust/pyspellchecker
spellchecker/spellchecker.py
SpellChecker.__edit_distance_alt
def __edit_distance_alt(self, words): """ Compute all strings that are 1 edits away from all the words using only the letters in the corpus Args: words (list): The words for which to calculate the edit distance Returns: set: The set of strings...
python
def __edit_distance_alt(self, words): """ Compute all strings that are 1 edits away from all the words using only the letters in the corpus Args: words (list): The words for which to calculate the edit distance Returns: set: The set of strings...
[ "def", "__edit_distance_alt", "(", "self", ",", "words", ")", ":", "words", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "words", "]", "return", "[", "e2", "for", "e1", "in", "words", "for", "e2", "in", "self", ".", "edit_distance_1", "...
Compute all strings that are 1 edits away from all the words using only the letters in the corpus Args: words (list): The words for which to calculate the edit distance Returns: set: The set of strings that are edit distance two from the \ ...
[ "Compute", "all", "strings", "that", "are", "1", "edits", "away", "from", "all", "the", "words", "using", "only", "the", "letters", "in", "the", "corpus" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L220-L230
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.pop
def pop(self, key, default=None): """ Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present """ return self._dictionary.pop(key.lower(), d...
python
def pop(self, key, default=None): """ Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present """ return self._dictionary.pop(key.lower(), d...
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_dictionary", ".", "pop", "(", "key", ".", "lower", "(", ")", ",", "default", ")" ]
Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present
[ "Remove", "the", "key", "and", "return", "the", "associated", "value", "or", "default", "if", "not", "found" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L275-L282
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.items
def items(self): """ Iterator over the words in the dictionary Yields: str: The next word in the dictionary int: The number of instances in the dictionary Note: This is the same as `dict.items()` """ for word in self._dictionary.ke...
python
def items(self): """ Iterator over the words in the dictionary Yields: str: The next word in the dictionary int: The number of instances in the dictionary Note: This is the same as `dict.items()` """ for word in self._dictionary.ke...
[ "def", "items", "(", "self", ")", ":", "for", "word", "in", "self", ".", "_dictionary", ".", "keys", "(", ")", ":", "yield", "word", ",", "self", ".", "_dictionary", "[", "word", "]" ]
Iterator over the words in the dictionary Yields: str: The next word in the dictionary int: The number of instances in the dictionary Note: This is the same as `dict.items()`
[ "Iterator", "over", "the", "words", "in", "the", "dictionary" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L350-L359
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.load_dictionary
def load_dictionary(self, filename, encoding="utf-8"): """ Load in a pre-built word frequency list Args: filename (str): The filepath to the json (optionally gzipped) \ file to be loaded encoding (str): The encoding of the dictionary """ with ...
python
def load_dictionary(self, filename, encoding="utf-8"): """ Load in a pre-built word frequency list Args: filename (str): The filepath to the json (optionally gzipped) \ file to be loaded encoding (str): The encoding of the dictionary """ with ...
[ "def", "load_dictionary", "(", "self", ",", "filename", ",", "encoding", "=", "\"utf-8\"", ")", ":", "with", "load_file", "(", "filename", ",", "encoding", ")", "as", "data", ":", "self", ".", "_dictionary", ".", "update", "(", "json", ".", "loads", "(",...
Load in a pre-built word frequency list Args: filename (str): The filepath to the json (optionally gzipped) \ file to be loaded encoding (str): The encoding of the dictionary
[ "Load", "in", "a", "pre", "-", "built", "word", "frequency", "list" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L361-L370
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.load_text_file
def load_text_file(self, filename, encoding="utf-8", tokenizer=None): """ Load in a text file from which to generate a word frequency list Args: filename (str): The filepath to the text file to be loaded encoding (str): The encoding of the text file t...
python
def load_text_file(self, filename, encoding="utf-8", tokenizer=None): """ Load in a text file from which to generate a word frequency list Args: filename (str): The filepath to the text file to be loaded encoding (str): The encoding of the text file t...
[ "def", "load_text_file", "(", "self", ",", "filename", ",", "encoding", "=", "\"utf-8\"", ",", "tokenizer", "=", "None", ")", ":", "with", "load_file", "(", "filename", ",", "encoding", "=", "encoding", ")", "as", "data", ":", "self", ".", "load_text", "...
Load in a text file from which to generate a word frequency list Args: filename (str): The filepath to the text file to be loaded encoding (str): The encoding of the text file tokenizer (function): The function to use to tokenize a string
[ "Load", "in", "a", "text", "file", "from", "which", "to", "generate", "a", "word", "frequency", "list" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L372-L381
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.load_text
def load_text(self, text, tokenizer=None): """ Load text from which to generate a word frequency list Args: text (str): The text to be loaded tokenizer (function): The function to use to tokenize a string """ if tokenizer: words = [x.lower...
python
def load_text(self, text, tokenizer=None): """ Load text from which to generate a word frequency list Args: text (str): The text to be loaded tokenizer (function): The function to use to tokenize a string """ if tokenizer: words = [x.lower...
[ "def", "load_text", "(", "self", ",", "text", ",", "tokenizer", "=", "None", ")", ":", "if", "tokenizer", ":", "words", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "tokenizer", "(", "text", ")", "]", "else", ":", "words", "=", "self"...
Load text from which to generate a word frequency list Args: text (str): The text to be loaded tokenizer (function): The function to use to tokenize a string
[ "Load", "text", "from", "which", "to", "generate", "a", "word", "frequency", "list" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L383-L396
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.load_words
def load_words(self, words): """ Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded """ self._dictionary.update([word.lower() for word in words]) self._update_dictionary()
python
def load_words(self, words): """ Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded """ self._dictionary.update([word.lower() for word in words]) self._update_dictionary()
[ "def", "load_words", "(", "self", ",", "words", ")", ":", "self", ".", "_dictionary", ".", "update", "(", "[", "word", ".", "lower", "(", ")", "for", "word", "in", "words", "]", ")", "self", ".", "_update_dictionary", "(", ")" ]
Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded
[ "Load", "a", "list", "of", "words", "from", "which", "to", "generate", "a", "word", "frequency", "list" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L398-L404
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.remove_words
def remove_words(self, words): """ Remove a list of words from the word frequency list Args: words (list): The list of words to remove """ for word in words: self._dictionary.pop(word.lower()) self._update_dictionary()
python
def remove_words(self, words): """ Remove a list of words from the word frequency list Args: words (list): The list of words to remove """ for word in words: self._dictionary.pop(word.lower()) self._update_dictionary()
[ "def", "remove_words", "(", "self", ",", "words", ")", ":", "for", "word", "in", "words", ":", "self", ".", "_dictionary", ".", "pop", "(", "word", ".", "lower", "(", ")", ")", "self", ".", "_update_dictionary", "(", ")" ]
Remove a list of words from the word frequency list Args: words (list): The list of words to remove
[ "Remove", "a", "list", "of", "words", "from", "the", "word", "frequency", "list" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L413-L420
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.remove
def remove(self, word): """ Remove a word from the word frequency list Args: word (str): The word to remove """ self._dictionary.pop(word.lower()) self._update_dictionary()
python
def remove(self, word): """ Remove a word from the word frequency list Args: word (str): The word to remove """ self._dictionary.pop(word.lower()) self._update_dictionary()
[ "def", "remove", "(", "self", ",", "word", ")", ":", "self", ".", "_dictionary", ".", "pop", "(", "word", ".", "lower", "(", ")", ")", "self", ".", "_update_dictionary", "(", ")" ]
Remove a word from the word frequency list Args: word (str): The word to remove
[ "Remove", "a", "word", "from", "the", "word", "frequency", "list" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L422-L428
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency.remove_by_threshold
def remove_by_threshold(self, threshold=5): """ Remove all words at, or below, the provided threshold Args: threshold (int): The threshold at which a word is to be \ removed """ keys = [x for x in self._dictionary.keys()] for key in keys: ...
python
def remove_by_threshold(self, threshold=5): """ Remove all words at, or below, the provided threshold Args: threshold (int): The threshold at which a word is to be \ removed """ keys = [x for x in self._dictionary.keys()] for key in keys: ...
[ "def", "remove_by_threshold", "(", "self", ",", "threshold", "=", "5", ")", ":", "keys", "=", "[", "x", "for", "x", "in", "self", ".", "_dictionary", ".", "keys", "(", ")", "]", "for", "key", "in", "keys", ":", "if", "self", ".", "_dictionary", "["...
Remove all words at, or below, the provided threshold Args: threshold (int): The threshold at which a word is to be \ removed
[ "Remove", "all", "words", "at", "or", "below", "the", "provided", "threshold" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L430-L440
barrust/pyspellchecker
spellchecker/spellchecker.py
WordFrequency._update_dictionary
def _update_dictionary(self): """ Update the word frequency object """ self._total_words = sum(self._dictionary.values()) self._unique_words = len(self._dictionary.keys()) self._letters = set() for key in self._dictionary: self._letters.update(key)
python
def _update_dictionary(self): """ Update the word frequency object """ self._total_words = sum(self._dictionary.values()) self._unique_words = len(self._dictionary.keys()) self._letters = set() for key in self._dictionary: self._letters.update(key)
[ "def", "_update_dictionary", "(", "self", ")", ":", "self", ".", "_total_words", "=", "sum", "(", "self", ".", "_dictionary", ".", "values", "(", ")", ")", "self", ".", "_unique_words", "=", "len", "(", "self", ".", "_dictionary", ".", "keys", "(", ")"...
Update the word frequency object
[ "Update", "the", "word", "frequency", "object" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L442-L448
barrust/pyspellchecker
spellchecker/utils.py
load_file
def load_file(filename, encoding): """ Context manager to handle opening a gzip or text file correctly and reading all the data Args: filename (str): The filename to open encoding (str): The file encoding to use Yields: str: The string data from the file ...
python
def load_file(filename, encoding): """ Context manager to handle opening a gzip or text file correctly and reading all the data Args: filename (str): The filename to open encoding (str): The file encoding to use Yields: str: The string data from the file ...
[ "def", "load_file", "(", "filename", ",", "encoding", ")", ":", "try", ":", "with", "gzip", ".", "open", "(", "filename", ",", "mode", "=", "\"rt\"", ")", "as", "fobj", ":", "yield", "fobj", ".", "read", "(", ")", "except", "(", "OSError", ",", "IO...
Context manager to handle opening a gzip or text file correctly and reading all the data Args: filename (str): The filename to open encoding (str): The file encoding to use Yields: str: The string data from the file read
[ "Context", "manager", "to", "handle", "opening", "a", "gzip", "or", "text", "file", "correctly", "and", "reading", "all", "the", "data" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/utils.py#L16-L31
barrust/pyspellchecker
spellchecker/utils.py
write_file
def write_file(filepath, encoding, gzipped, data): """ Write the data to file either as a gzip file or text based on the gzipped parameter Args: filepath (str): The filename to open encoding (str): The file encoding to use gzipped (bool): Whether the file should ...
python
def write_file(filepath, encoding, gzipped, data): """ Write the data to file either as a gzip file or text based on the gzipped parameter Args: filepath (str): The filename to open encoding (str): The file encoding to use gzipped (bool): Whether the file should ...
[ "def", "write_file", "(", "filepath", ",", "encoding", ",", "gzipped", ",", "data", ")", ":", "if", "gzipped", ":", "with", "gzip", ".", "open", "(", "filepath", ",", "\"wt\"", ")", "as", "fobj", ":", "fobj", ".", "write", "(", "data", ")", "else", ...
Write the data to file either as a gzip file or text based on the gzipped parameter Args: filepath (str): The filename to open encoding (str): The file encoding to use gzipped (bool): Whether the file should be gzipped or not data (str): The data to be wr...
[ "Write", "the", "data", "to", "file", "either", "as", "a", "gzip", "file", "or", "text", "based", "on", "the", "gzipped", "parameter" ]
train
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/utils.py#L34-L51
merantix/picasso
picasso/examples/keras/model.py
KerasMNISTModel.preprocess
def preprocess(self, raw_inputs): """Convert images into the format required by our model. Our model requires that inputs be grayscale (mode 'L'), be resized to `MNIST_DIM`, and be represented as float32 numpy arrays in range [0, 1]. Args: raw_inputs (list of Images...
python
def preprocess(self, raw_inputs): """Convert images into the format required by our model. Our model requires that inputs be grayscale (mode 'L'), be resized to `MNIST_DIM`, and be represented as float32 numpy arrays in range [0, 1]. Args: raw_inputs (list of Images...
[ "def", "preprocess", "(", "self", ",", "raw_inputs", ")", ":", "image_arrays", "=", "[", "]", "for", "raw_im", "in", "raw_inputs", ":", "im", "=", "raw_im", ".", "convert", "(", "'L'", ")", "im", "=", "im", ".", "resize", "(", "MNIST_DIM", ",", "Imag...
Convert images into the format required by our model. Our model requires that inputs be grayscale (mode 'L'), be resized to `MNIST_DIM`, and be represented as float32 numpy arrays in range [0, 1]. Args: raw_inputs (list of Images): a list of PIL Image objects Retur...
[ "Convert", "images", "into", "the", "format", "required", "by", "our", "model", "." ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/examples/keras/model.py#L23-L47
merantix/picasso
picasso/interfaces/rest.py
initialize_new_session
def initialize_new_session(): """Check session and initialize if necessary Before every request, check the user session. If no session exists, add one and provide temporary locations for images """ if 'image_uid_counter' in session and 'image_list' in session: logger.debug('images are alr...
python
def initialize_new_session(): """Check session and initialize if necessary Before every request, check the user session. If no session exists, add one and provide temporary locations for images """ if 'image_uid_counter' in session and 'image_list' in session: logger.debug('images are alr...
[ "def", "initialize_new_session", "(", ")", ":", "if", "'image_uid_counter'", "in", "session", "and", "'image_list'", "in", "session", ":", "logger", ".", "debug", "(", "'images are already being tracked'", ")", "else", ":", "# reset image list counter for the session", ...
Check session and initialize if necessary Before every request, check the user session. If no session exists, add one and provide temporary locations for images
[ "Check", "session", "and", "initialize", "if", "necessary" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L42-L60
merantix/picasso
picasso/interfaces/rest.py
images
def images(): """Upload images via REST interface Check if file upload was successful and sanatize user input. TODO: return file URL instead of filename """ if request.method == 'POST': file_upload = request.files['file'] if file_upload: image = dict() imag...
python
def images(): """Upload images via REST interface Check if file upload was successful and sanatize user input. TODO: return file URL instead of filename """ if request.method == 'POST': file_upload = request.files['file'] if file_upload: image = dict() imag...
[ "def", "images", "(", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "file_upload", "=", "request", ".", "files", "[", "'file'", "]", "if", "file_upload", ":", "image", "=", "dict", "(", ")", "image", "[", "'filename'", "]", "=", "sec...
Upload images via REST interface Check if file upload was successful and sanatize user input. TODO: return file URL instead of filename
[ "Upload", "images", "via", "REST", "interface" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L84-L109
merantix/picasso
picasso/interfaces/rest.py
visualizers
def visualizers(): """Get a list of available visualizers Responses with a JSON list of available visualizers """ list_of_visualizers = [] for visualizer in get_visualizations(): list_of_visualizers.append({'name': visualizer}) return jsonify(visualizers=list_of_visualizers)
python
def visualizers(): """Get a list of available visualizers Responses with a JSON list of available visualizers """ list_of_visualizers = [] for visualizer in get_visualizations(): list_of_visualizers.append({'name': visualizer}) return jsonify(visualizers=list_of_visualizers)
[ "def", "visualizers", "(", ")", ":", "list_of_visualizers", "=", "[", "]", "for", "visualizer", "in", "get_visualizations", "(", ")", ":", "list_of_visualizers", ".", "append", "(", "{", "'name'", ":", "visualizer", "}", ")", "return", "jsonify", "(", "visua...
Get a list of available visualizers Responses with a JSON list of available visualizers
[ "Get", "a", "list", "of", "available", "visualizers" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L113-L122
merantix/picasso
picasso/interfaces/rest.py
visualize
def visualize(): """Trigger a visualization via the REST API Takes a single image and generates the visualization data, returning the output exactly as given by the target visualization. """ session['settings'] = {} image_uid = request.args.get('image') vis_name = request.args.get('visual...
python
def visualize(): """Trigger a visualization via the REST API Takes a single image and generates the visualization data, returning the output exactly as given by the target visualization. """ session['settings'] = {} image_uid = request.args.get('image') vis_name = request.args.get('visual...
[ "def", "visualize", "(", ")", ":", "session", "[", "'settings'", "]", "=", "{", "}", "image_uid", "=", "request", ".", "args", ".", "get", "(", "'image'", ")", "vis_name", "=", "request", ".", "args", ".", "get", "(", "'visualizer'", ")", "vis", "=",...
Trigger a visualization via the REST API Takes a single image and generates the visualization data, returning the output exactly as given by the target visualization.
[ "Trigger", "a", "visualization", "via", "the", "REST", "API" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L133-L166
merantix/picasso
picasso/interfaces/rest.py
reset
def reset(): """Delete the session and clear temporary directories """ shutil.rmtree(session['img_input_dir']) shutil.rmtree(session['img_output_dir']) session.clear() return jsonify(ok='true')
python
def reset(): """Delete the session and clear temporary directories """ shutil.rmtree(session['img_input_dir']) shutil.rmtree(session['img_output_dir']) session.clear() return jsonify(ok='true')
[ "def", "reset", "(", ")", ":", "shutil", ".", "rmtree", "(", "session", "[", "'img_input_dir'", "]", ")", "shutil", ".", "rmtree", "(", "session", "[", "'img_output_dir'", "]", ")", "session", ".", "clear", "(", ")", "return", "jsonify", "(", "ok", "="...
Delete the session and clear temporary directories
[ "Delete", "the", "session", "and", "clear", "temporary", "directories" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/interfaces/rest.py#L170-L177
merantix/picasso
picasso/visualizations/base.py
BaseVisualization.update_settings
def update_settings(self, settings): """Update the settings If a derived class has an ALLOWED_SETTINGS dict, we check here that incoming settings from the web app are allowed, and set the child properties as appropriate. """ def error_string(setting, setting_val): ...
python
def update_settings(self, settings): """Update the settings If a derived class has an ALLOWED_SETTINGS dict, we check here that incoming settings from the web app are allowed, and set the child properties as appropriate. """ def error_string(setting, setting_val): ...
[ "def", "update_settings", "(", "self", ",", "settings", ")", ":", "def", "error_string", "(", "setting", ",", "setting_val", ")", ":", "return", "(", "'{val} is not an acceptable value for '", "'parameter {param} for visualization'", "'{vis}.'", ")", ".", "format", "(...
Update the settings If a derived class has an ALLOWED_SETTINGS dict, we check here that incoming settings from the web app are allowed, and set the child properties as appropriate.
[ "Update", "the", "settings" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/visualizations/base.py#L60-L87
merantix/picasso
picasso/examples/keras-vgg16/model.py
KerasVGG16Model.preprocess
def preprocess(self, raw_inputs): """ Args: raw_inputs (list of Images): a list of PIL Image objects Returns: array (float32): num images * height * width * num channels """ image_arrays = [] for raw_im in raw_inputs: im = raw_im.resize...
python
def preprocess(self, raw_inputs): """ Args: raw_inputs (list of Images): a list of PIL Image objects Returns: array (float32): num images * height * width * num channels """ image_arrays = [] for raw_im in raw_inputs: im = raw_im.resize...
[ "def", "preprocess", "(", "self", ",", "raw_inputs", ")", ":", "image_arrays", "=", "[", "]", "for", "raw_im", "in", "raw_inputs", ":", "im", "=", "raw_im", ".", "resize", "(", "VGG16_DIM", "[", ":", "2", "]", ",", "Image", ".", "ANTIALIAS", ")", "im...
Args: raw_inputs (list of Images): a list of PIL Image objects Returns: array (float32): num images * height * width * num channels
[ "Args", ":", "raw_inputs", "(", "list", "of", "Images", ")", ":", "a", "list", "of", "PIL", "Image", "objects", "Returns", ":", "array", "(", "float32", ")", ":", "num", "images", "*", "height", "*", "width", "*", "num", "channels" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/examples/keras-vgg16/model.py#L24-L39
merantix/picasso
picasso/models/keras.py
KerasModel.load
def load(self, data_dir): """Load graph and weight data. Args: data_dir (:obj:`str`): location of Keras checkpoint (`.hdf5`) files and model (in `.json`) structure. The default behavior is to take the latest of each, by OS timestamp. """ # fo...
python
def load(self, data_dir): """Load graph and weight data. Args: data_dir (:obj:`str`): location of Keras checkpoint (`.hdf5`) files and model (in `.json`) structure. The default behavior is to take the latest of each, by OS timestamp. """ # fo...
[ "def", "load", "(", "self", ",", "data_dir", ")", ":", "# for tensorflow compatibility", "K", ".", "set_learning_phase", "(", "0", ")", "# find newest ckpt and graph files", "try", ":", "latest_ckpt", "=", "max", "(", "glob", ".", "iglob", "(", "os", ".", "pat...
Load graph and weight data. Args: data_dir (:obj:`str`): location of Keras checkpoint (`.hdf5`) files and model (in `.json`) structure. The default behavior is to take the latest of each, by OS timestamp.
[ "Load", "graph", "and", "weight", "data", "." ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/models/keras.py#L32-L75
merantix/picasso
picasso/models/tensorflow.py
TFModel.load
def load(self, data_dir, tf_input_var=None, tf_predict_var=None): """Load graph and weight data. Args: data_dir (:obj:`str`): location of tensorflow checkpoint data. We'll need the .meta file to reconstruct the graph and the data (checkpoint) files to fill in...
python
def load(self, data_dir, tf_input_var=None, tf_predict_var=None): """Load graph and weight data. Args: data_dir (:obj:`str`): location of tensorflow checkpoint data. We'll need the .meta file to reconstruct the graph and the data (checkpoint) files to fill in...
[ "def", "load", "(", "self", ",", "data_dir", ",", "tf_input_var", "=", "None", ",", "tf_predict_var", "=", "None", ")", ":", "# find newest ckpt and meta files", "try", ":", "latest_ckpt_fn", "=", "max", "(", "filter", "(", "# exclude index and meta files which may ...
Load graph and weight data. Args: data_dir (:obj:`str`): location of tensorflow checkpoint data. We'll need the .meta file to reconstruct the graph and the data (checkpoint) files to fill in the weights of the model. The default behavior is take the ...
[ "Load", "graph", "and", "weight", "data", "." ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/models/tensorflow.py#L27-L84
merantix/picasso
picasso/models/base.py
load_model
def load_model(model_cls_path, model_cls_name, model_load_args): """Get an instance of the described model. Args: model_cls_path: Path to the module in which the model class is defined. model_cls_name: Name of the model class. model_load_args: Dictionary of args to pass to t...
python
def load_model(model_cls_path, model_cls_name, model_load_args): """Get an instance of the described model. Args: model_cls_path: Path to the module in which the model class is defined. model_cls_name: Name of the model class. model_load_args: Dictionary of args to pass to t...
[ "def", "load_model", "(", "model_cls_path", ",", "model_cls_name", ",", "model_load_args", ")", ":", "spec", "=", "importlib", ".", "util", ".", "spec_from_file_location", "(", "'active_model'", ",", "model_cls_path", ")", "model_module", "=", "importlib", ".", "u...
Get an instance of the described model. Args: model_cls_path: Path to the module in which the model class is defined. model_cls_name: Name of the model class. model_load_args: Dictionary of args to pass to the `load` method of the model instance. Returns: ...
[ "Get", "an", "instance", "of", "the", "described", "model", "." ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/models/base.py#L18-L42
merantix/picasso
picasso/models/base.py
BaseModel.decode_prob
def decode_prob(self, class_probabilities): """Given predicted class probabilites for a set of examples, annotate each logit with a class name. By default, we name each class using its index in the logits array. Args: class_probabilities (array): Class probabilities as outp...
python
def decode_prob(self, class_probabilities): """Given predicted class probabilites for a set of examples, annotate each logit with a class name. By default, we name each class using its index in the logits array. Args: class_probabilities (array): Class probabilities as outp...
[ "def", "decode_prob", "(", "self", ",", "class_probabilities", ")", ":", "results", "=", "[", "]", "for", "row", "in", "class_probabilities", ":", "entries", "=", "[", "]", "for", "i", ",", "prob", "in", "enumerate", "(", "row", ")", ":", "entries", "....
Given predicted class probabilites for a set of examples, annotate each logit with a class name. By default, we name each class using its index in the logits array. Args: class_probabilities (array): Class probabilities as output by `self.predict`, i.e., a numpy arr...
[ "Given", "predicted", "class", "probabilites", "for", "a", "set", "of", "examples", "annotate", "each", "logit", "with", "a", "class", "name", "." ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/models/base.py#L174-L210
merantix/picasso
picasso/utils.py
_get_visualization_classes
def _get_visualization_classes(): """Import visualizations classes dynamically """ visualization_attr = vars(import_module('picasso.visualizations')) visualization_submodules = [ visualization_attr[x] for x in visualization_attr if isinstance(visualization_attr[x], ModuleType)] ...
python
def _get_visualization_classes(): """Import visualizations classes dynamically """ visualization_attr = vars(import_module('picasso.visualizations')) visualization_submodules = [ visualization_attr[x] for x in visualization_attr if isinstance(visualization_attr[x], ModuleType)] ...
[ "def", "_get_visualization_classes", "(", ")", ":", "visualization_attr", "=", "vars", "(", "import_module", "(", "'picasso.visualizations'", ")", ")", "visualization_submodules", "=", "[", "visualization_attr", "[", "x", "]", "for", "x", "in", "visualization_attr", ...
Import visualizations classes dynamically
[ "Import", "visualizations", "classes", "dynamically" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/utils.py#L32-L49
merantix/picasso
picasso/utils.py
get_model
def get_model(): """Get the NN model that's being analyzed from the request context. Put the model in the request context if it is not yet there. Returns: instance of :class:`.models.model.Model` or derived class """ if not hasattr(g, 'model'): g.model = load_model(current_...
python
def get_model(): """Get the NN model that's being analyzed from the request context. Put the model in the request context if it is not yet there. Returns: instance of :class:`.models.model.Model` or derived class """ if not hasattr(g, 'model'): g.model = load_model(current_...
[ "def", "get_model", "(", ")", ":", "if", "not", "hasattr", "(", "g", ",", "'model'", ")", ":", "g", ".", "model", "=", "load_model", "(", "current_app", ".", "config", "[", "'MODEL_CLS_PATH'", "]", ",", "current_app", ".", "config", "[", "'MODEL_CLS_NAME...
Get the NN model that's being analyzed from the request context. Put the model in the request context if it is not yet there. Returns: instance of :class:`.models.model.Model` or derived class
[ "Get", "the", "NN", "model", "that", "s", "being", "analyzed", "from", "the", "request", "context", ".", "Put", "the", "model", "in", "the", "request", "context", "if", "it", "is", "not", "yet", "there", "." ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/utils.py#L52-L64
merantix/picasso
picasso/utils.py
get_visualizations
def get_visualizations(): """Get the available visualizations from the request context. Put the visualizations in the request context if they are not yet there. Returns: :obj:`list` of instances of :class:`.BaseVisualization` or derived class """ if not hasattr(g, 'visualizations'...
python
def get_visualizations(): """Get the available visualizations from the request context. Put the visualizations in the request context if they are not yet there. Returns: :obj:`list` of instances of :class:`.BaseVisualization` or derived class """ if not hasattr(g, 'visualizations'...
[ "def", "get_visualizations", "(", ")", ":", "if", "not", "hasattr", "(", "g", ",", "'visualizations'", ")", ":", "g", ".", "visualizations", "=", "{", "}", "for", "VisClass", "in", "_get_visualization_classes", "(", ")", ":", "vis", "=", "VisClass", "(", ...
Get the available visualizations from the request context. Put the visualizations in the request context if they are not yet there. Returns: :obj:`list` of instances of :class:`.BaseVisualization` or derived class
[ "Get", "the", "available", "visualizations", "from", "the", "request", "context", ".", "Put", "the", "visualizations", "in", "the", "request", "context", "if", "they", "are", "not", "yet", "there", "." ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/utils.py#L67-L81
merantix/picasso
picasso/utils.py
get_app_state
def get_app_state(): """Get current status of application in context Returns: :obj:`dict` of application status """ if not hasattr(g, 'app_state'): model = get_model() g.app_state = { 'app_title': APP_TITLE, 'model_name': type(model).__name__, ...
python
def get_app_state(): """Get current status of application in context Returns: :obj:`dict` of application status """ if not hasattr(g, 'app_state'): model = get_model() g.app_state = { 'app_title': APP_TITLE, 'model_name': type(model).__name__, ...
[ "def", "get_app_state", "(", ")", ":", "if", "not", "hasattr", "(", "g", ",", "'app_state'", ")", ":", "model", "=", "get_model", "(", ")", "g", ".", "app_state", "=", "{", "'app_title'", ":", "APP_TITLE", ",", "'model_name'", ":", "type", "(", "model"...
Get current status of application in context Returns: :obj:`dict` of application status
[ "Get", "current", "status", "of", "application", "in", "context" ]
train
https://github.com/merantix/picasso/blob/d276b9b7408dd1032fe0ccb84ea9b6604a32915e/picasso/utils.py#L84-L99
arraylabs/pymyq
pymyq/api.py
login
async def login( username: str, password: str, brand: str, websession: ClientSession = None) -> API: """Log in to the API.""" api = API(brand, websession) await api.authenticate(username, password) return api
python
async def login( username: str, password: str, brand: str, websession: ClientSession = None) -> API: """Log in to the API.""" api = API(brand, websession) await api.authenticate(username, password) return api
[ "async", "def", "login", "(", "username", ":", "str", ",", "password", ":", "str", ",", "brand", ":", "str", ",", "websession", ":", "ClientSession", "=", "None", ")", "->", "API", ":", "api", "=", "API", "(", "brand", ",", "websession", ")", "await"...
Log in to the API.
[ "Log", "in", "to", "the", "API", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L286-L292
arraylabs/pymyq
pymyq/api.py
API._create_websession
def _create_websession(self): """Create a web session.""" from socket import AF_INET from aiohttp import ClientTimeout, TCPConnector _LOGGER.debug('Creating web session') conn = TCPConnector( family=AF_INET, limit_per_host=5, enable_cleanup_cl...
python
def _create_websession(self): """Create a web session.""" from socket import AF_INET from aiohttp import ClientTimeout, TCPConnector _LOGGER.debug('Creating web session') conn = TCPConnector( family=AF_INET, limit_per_host=5, enable_cleanup_cl...
[ "def", "_create_websession", "(", "self", ")", ":", "from", "socket", "import", "AF_INET", "from", "aiohttp", "import", "ClientTimeout", ",", "TCPConnector", "_LOGGER", ".", "debug", "(", "'Creating web session'", ")", "conn", "=", "TCPConnector", "(", "family", ...
Create a web session.
[ "Create", "a", "web", "session", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L73-L89
arraylabs/pymyq
pymyq/api.py
API.close_websession
async def close_websession(self): """Close web session if not already closed and created by us.""" # We do not close the web session if it was provided. if self._supplied_websession or self._websession is None: return _LOGGER.debug('Closing connections') # Need to se...
python
async def close_websession(self): """Close web session if not already closed and created by us.""" # We do not close the web session if it was provided. if self._supplied_websession or self._websession is None: return _LOGGER.debug('Closing connections') # Need to se...
[ "async", "def", "close_websession", "(", "self", ")", ":", "# We do not close the web session if it was provided.", "if", "self", ".", "_supplied_websession", "or", "self", ".", "_websession", "is", "None", ":", "return", "_LOGGER", ".", "debug", "(", "'Closing connec...
Close web session if not already closed and created by us.
[ "Close", "web", "session", "if", "not", "already", "closed", "and", "created", "by", "us", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L91-L104
arraylabs/pymyq
pymyq/api.py
API.authenticate
async def authenticate(self, username: str, password: str) -> None: """Authenticate against the API.""" self._credentials = { 'username': username, 'password': password, } await self._get_security_token()
python
async def authenticate(self, username: str, password: str) -> None: """Authenticate against the API.""" self._credentials = { 'username': username, 'password': password, } await self._get_security_token()
[ "async", "def", "authenticate", "(", "self", ",", "username", ":", "str", ",", "password", ":", "str", ")", "->", "None", ":", "self", ".", "_credentials", "=", "{", "'username'", ":", "username", ",", "'password'", ":", "password", ",", "}", "await", ...
Authenticate against the API.
[ "Authenticate", "against", "the", "API", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L219-L226
arraylabs/pymyq
pymyq/api.py
API._get_security_token
async def _get_security_token(self) -> None: """Request a security token.""" _LOGGER.debug('Requesting security token.') if self._credentials is None: return # Make sure only 1 request can be sent at a time. async with self._security_token_lock: # Confirm...
python
async def _get_security_token(self) -> None: """Request a security token.""" _LOGGER.debug('Requesting security token.') if self._credentials is None: return # Make sure only 1 request can be sent at a time. async with self._security_token_lock: # Confirm...
[ "async", "def", "_get_security_token", "(", "self", ")", "->", "None", ":", "_LOGGER", ".", "debug", "(", "'Requesting security token.'", ")", "if", "self", ".", "_credentials", "is", "None", ":", "return", "# Make sure only 1 request can be sent at a time.", "async",...
Request a security token.
[ "Request", "a", "security", "token", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L228-L253
arraylabs/pymyq
pymyq/api.py
API.get_devices
async def get_devices(self, covers_only: bool = True) -> list: """Get a list of all devices associated with the account.""" from .device import MyQDevice _LOGGER.debug('Retrieving list of devices') devices_resp = await self._request('get', DEVICE_LIST_ENDPOINT) # print(json.dump...
python
async def get_devices(self, covers_only: bool = True) -> list: """Get a list of all devices associated with the account.""" from .device import MyQDevice _LOGGER.debug('Retrieving list of devices') devices_resp = await self._request('get', DEVICE_LIST_ENDPOINT) # print(json.dump...
[ "async", "def", "get_devices", "(", "self", ",", "covers_only", ":", "bool", "=", "True", ")", "->", "list", ":", "from", ".", "device", "import", "MyQDevice", "_LOGGER", ".", "debug", "(", "'Retrieving list of devices'", ")", "devices_resp", "=", "await", "...
Get a list of all devices associated with the account.
[ "Get", "a", "list", "of", "all", "devices", "associated", "with", "the", "account", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L255-L283
arraylabs/pymyq
example.py
main
async def main() -> None: """Create the aiohttp session and run the example.""" loglevels = dict((logging.getLevelName(level), level) for level in [10, 20, 30, 40, 50]) logging.basicConfig( level=loglevels[LOGLEVEL], format='%(asctime)s:%(levelname)s:\t%(name)s\t%(mess...
python
async def main() -> None: """Create the aiohttp session and run the example.""" loglevels = dict((logging.getLevelName(level), level) for level in [10, 20, 30, 40, 50]) logging.basicConfig( level=loglevels[LOGLEVEL], format='%(asctime)s:%(levelname)s:\t%(name)s\t%(mess...
[ "async", "def", "main", "(", ")", "->", "None", ":", "loglevels", "=", "dict", "(", "(", "logging", ".", "getLevelName", "(", "level", ")", ",", "level", ")", "for", "level", "in", "[", "10", ",", "20", ",", "30", ",", "40", ",", "50", "]", ")"...
Create the aiohttp session and run the example.
[ "Create", "the", "aiohttp", "session", "and", "run", "the", "example", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/example.py#L31-L97
arraylabs/pymyq
pymyq/device.py
MyQDevice.name
def name(self) -> str: """Return the device name.""" return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'desc')
python
def name(self) -> str: """Return the device name.""" return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'desc')
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "next", "(", "attr", "[", "'Value'", "]", "for", "attr", "in", "self", ".", "_device_json", ".", "get", "(", "'Attributes'", ",", "[", "]", ")", "if", "attr", ".", "get", "(", "'Attribute...
Return the device name.
[ "Return", "the", "device", "name", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L64-L68
arraylabs/pymyq
pymyq/device.py
MyQDevice.available
def available(self) -> bool: """Return if device is online or not.""" # Both ability to retrieve state from MyQ cloud AND device itself has # to be online. is_available = self.api.online and \ next( attr['Value'] for attr in self._device_json.g...
python
def available(self) -> bool: """Return if device is online or not.""" # Both ability to retrieve state from MyQ cloud AND device itself has # to be online. is_available = self.api.online and \ next( attr['Value'] for attr in self._device_json.g...
[ "def", "available", "(", "self", ")", "->", "bool", ":", "# Both ability to retrieve state from MyQ cloud AND device itself has", "# to be online.", "is_available", "=", "self", ".", "api", ".", "online", "and", "next", "(", "attr", "[", "'Value'", "]", "for", "attr...
Return if device is online or not.
[ "Return", "if", "device", "is", "online", "or", "not", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L71-L81
arraylabs/pymyq
pymyq/device.py
MyQDevice.open_allowed
def open_allowed(self) -> bool: """Door can be opened unattended.""" return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'isunattendedopenallowed')\ == "1"
python
def open_allowed(self) -> bool: """Door can be opened unattended.""" return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'isunattendedopenallowed')\ == "1"
[ "def", "open_allowed", "(", "self", ")", "->", "bool", ":", "return", "next", "(", "attr", "[", "'Value'", "]", "for", "attr", "in", "self", ".", "_device_json", ".", "get", "(", "'Attributes'", ",", "[", "]", ")", "if", "attr", ".", "get", "(", "'...
Door can be opened unattended.
[ "Door", "can", "be", "opened", "unattended", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L89-L94
arraylabs/pymyq
pymyq/device.py
MyQDevice.close_allowed
def close_allowed(self) -> bool: """Door can be closed unattended.""" return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'isunattendedcloseallowed')\ == "1"
python
def close_allowed(self) -> bool: """Door can be closed unattended.""" return next( attr['Value'] for attr in self._device_json.get('Attributes', []) if attr.get('AttributeDisplayName') == 'isunattendedcloseallowed')\ == "1"
[ "def", "close_allowed", "(", "self", ")", "->", "bool", ":", "return", "next", "(", "attr", "[", "'Value'", "]", "for", "attr", "in", "self", ".", "_device_json", ".", "get", "(", "'Attributes'", ",", "[", "]", ")", "if", "attr", ".", "get", "(", "...
Door can be closed unattended.
[ "Door", "can", "be", "closed", "unattended", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L97-L102
arraylabs/pymyq
pymyq/device.py
MyQDevice.state
def state(self) -> str: """Return the current state of the device (if it exists).""" return self._coerce_state_from_string( next( attr['Value'] for attr in self._device_json.get( 'Attributes', []) if attr.get('AttributeDisplayName') == 'doo...
python
def state(self) -> str: """Return the current state of the device (if it exists).""" return self._coerce_state_from_string( next( attr['Value'] for attr in self._device_json.get( 'Attributes', []) if attr.get('AttributeDisplayName') == 'doo...
[ "def", "state", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_coerce_state_from_string", "(", "next", "(", "attr", "[", "'Value'", "]", "for", "attr", "in", "self", ".", "_device_json", ".", "get", "(", "'Attributes'", ",", "[", "]", ")"...
Return the current state of the device (if it exists).
[ "Return", "the", "current", "state", "of", "the", "device", "(", "if", "it", "exists", ")", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L105-L111
arraylabs/pymyq
pymyq/device.py
MyQDevice._update_state
def _update_state(self, value: str) -> None: """Update state temporary during open or close.""" attribute = next(attr for attr in self._device['device_info'].get( 'Attributes', []) if attr.get( 'AttributeDisplayName') == 'doorstate') if attribute is not None: ...
python
def _update_state(self, value: str) -> None: """Update state temporary during open or close.""" attribute = next(attr for attr in self._device['device_info'].get( 'Attributes', []) if attr.get( 'AttributeDisplayName') == 'doorstate') if attribute is not None: ...
[ "def", "_update_state", "(", "self", ",", "value", ":", "str", ")", "->", "None", ":", "attribute", "=", "next", "(", "attr", "for", "attr", "in", "self", ".", "_device", "[", "'device_info'", "]", ".", "get", "(", "'Attributes'", ",", "[", "]", ")",...
Update state temporary during open or close.
[ "Update", "state", "temporary", "during", "open", "or", "close", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L113-L119
arraylabs/pymyq
pymyq/device.py
MyQDevice._coerce_state_from_string
def _coerce_state_from_string(value: Union[int, str]) -> str: """Return a proper state from a string input.""" try: return STATE_MAP[int(value)] except KeyError: _LOGGER.error('Unknown state: %s', value) return STATE_UNKNOWN
python
def _coerce_state_from_string(value: Union[int, str]) -> str: """Return a proper state from a string input.""" try: return STATE_MAP[int(value)] except KeyError: _LOGGER.error('Unknown state: %s', value) return STATE_UNKNOWN
[ "def", "_coerce_state_from_string", "(", "value", ":", "Union", "[", "int", ",", "str", "]", ")", "->", "str", ":", "try", ":", "return", "STATE_MAP", "[", "int", "(", "value", ")", "]", "except", "KeyError", ":", "_LOGGER", ".", "error", "(", "'Unknow...
Return a proper state from a string input.
[ "Return", "a", "proper", "state", "from", "a", "string", "input", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L127-L133
arraylabs/pymyq
pymyq/device.py
MyQDevice._set_state
async def _set_state(self, state: int) -> bool: """Set the state of the device.""" try: set_state_resp = await self.api._request( 'put', DEVICE_SET_ENDPOINT, json={ 'attributeName': 'desireddoorstate', 'm...
python
async def _set_state(self, state: int) -> bool: """Set the state of the device.""" try: set_state_resp = await self.api._request( 'put', DEVICE_SET_ENDPOINT, json={ 'attributeName': 'desireddoorstate', 'm...
[ "async", "def", "_set_state", "(", "self", ",", "state", ":", "int", ")", "->", "bool", ":", "try", ":", "set_state_resp", "=", "await", "self", ".", "api", ".", "_request", "(", "'put'", ",", "DEVICE_SET_ENDPOINT", ",", "json", "=", "{", "'attributeName...
Set the state of the device.
[ "Set", "the", "state", "of", "the", "device", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L136-L161
arraylabs/pymyq
pymyq/device.py
MyQDevice.close
async def close(self) -> bool: """Close the device.""" _LOGGER.debug('%s: Sending close command', self.name) if not await self._set_state(0): return False # Do not allow update of this device's state for 10 seconds. self.next_allowed_update = datetime.utcnow() + time...
python
async def close(self) -> bool: """Close the device.""" _LOGGER.debug('%s: Sending close command', self.name) if not await self._set_state(0): return False # Do not allow update of this device's state for 10 seconds. self.next_allowed_update = datetime.utcnow() + time...
[ "async", "def", "close", "(", "self", ")", "->", "bool", ":", "_LOGGER", ".", "debug", "(", "'%s: Sending close command'", ",", "self", ".", "name", ")", "if", "not", "await", "self", ".", "_set_state", "(", "0", ")", ":", "return", "False", "# Do not al...
Close the device.
[ "Close", "the", "device", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L163-L179
arraylabs/pymyq
pymyq/device.py
MyQDevice.open
async def open(self) -> bool: """Open the device.""" _LOGGER.debug('%s: Sending open command', self.name) if not await self._set_state(1): return False # Do not allow update of this device's state for 5 seconds. self.next_allowed_update = datetime.utcnow() + timedelt...
python
async def open(self) -> bool: """Open the device.""" _LOGGER.debug('%s: Sending open command', self.name) if not await self._set_state(1): return False # Do not allow update of this device's state for 5 seconds. self.next_allowed_update = datetime.utcnow() + timedelt...
[ "async", "def", "open", "(", "self", ")", "->", "bool", ":", "_LOGGER", ".", "debug", "(", "'%s: Sending open command'", ",", "self", ".", "name", ")", "if", "not", "await", "self", ".", "_set_state", "(", "1", ")", ":", "return", "False", "# Do not allo...
Open the device.
[ "Open", "the", "device", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L181-L197
arraylabs/pymyq
pymyq/device.py
MyQDevice.update
async def update(self) -> None: """Retrieve updated device state.""" if self.next_allowed_update is not None and \ datetime.utcnow() < self.next_allowed_update: return self.next_allowed_update = None await self.api._update_device_state() self._device_...
python
async def update(self) -> None: """Retrieve updated device state.""" if self.next_allowed_update is not None and \ datetime.utcnow() < self.next_allowed_update: return self.next_allowed_update = None await self.api._update_device_state() self._device_...
[ "async", "def", "update", "(", "self", ")", "->", "None", ":", "if", "self", ".", "next_allowed_update", "is", "not", "None", "and", "datetime", ".", "utcnow", "(", ")", "<", "self", ".", "next_allowed_update", ":", "return", "self", ".", "next_allowed_upd...
Retrieve updated device state.
[ "Retrieve", "updated", "device", "state", "." ]
train
https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L200-L208
sporestack/bitcash
bitcash/network/services.py
NetworkAPI.get_transaction
def get_transaction(cls, txid): """Gets the full transaction details. :param txid: The transaction id in question. :type txid: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``Transaction`` """ for api_call in cls.GET_TX_MAIN: try...
python
def get_transaction(cls, txid): """Gets the full transaction details. :param txid: The transaction id in question. :type txid: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``Transaction`` """ for api_call in cls.GET_TX_MAIN: try...
[ "def", "get_transaction", "(", "cls", ",", "txid", ")", ":", "for", "api_call", "in", "cls", ".", "GET_TX_MAIN", ":", "try", ":", "return", "api_call", "(", "txid", ")", "except", "cls", ".", "IGNORED_ERRORS", ":", "pass", "raise", "ConnectionError", "(", ...
Gets the full transaction details. :param txid: The transaction id in question. :type txid: ``str`` :raises ConnectionError: If all API services fail. :rtype: ``Transaction``
[ "Gets", "the", "full", "transaction", "details", "." ]
train
https://github.com/sporestack/bitcash/blob/c7a18b9d82af98f1000c456dd06131524c260b7f/bitcash/network/services.py#L346-L361
sporestack/bitcash
bitcash/network/services.py
NetworkAPI.get_tx_amount
def get_tx_amount(cls, txid, txindex): """Gets the amount of a given transaction output. :param txid: The transaction id in question. :type txid: ``str`` :param txindex: The transaction index in question. :type txindex: ``int`` :raises ConnectionError: If all API service...
python
def get_tx_amount(cls, txid, txindex): """Gets the amount of a given transaction output. :param txid: The transaction id in question. :type txid: ``str`` :param txindex: The transaction index in question. :type txindex: ``int`` :raises ConnectionError: If all API service...
[ "def", "get_tx_amount", "(", "cls", ",", "txid", ",", "txindex", ")", ":", "for", "api_call", "in", "cls", ".", "GET_TX_AMOUNT_MAIN", ":", "try", ":", "return", "api_call", "(", "txid", ",", "txindex", ")", "except", "cls", ".", "IGNORED_ERRORS", ":", "p...
Gets the amount of a given transaction output. :param txid: The transaction id in question. :type txid: ``str`` :param txindex: The transaction index in question. :type txindex: ``int`` :raises ConnectionError: If all API services fail. :rtype: ``Decimal``
[ "Gets", "the", "amount", "of", "a", "given", "transaction", "output", "." ]
train
https://github.com/sporestack/bitcash/blob/c7a18b9d82af98f1000c456dd06131524c260b7f/bitcash/network/services.py#L383-L400
sporestack/bitcash
bitcash/network/fees.py
get_fee
def get_fee(speed=FEE_SPEED_MEDIUM): """Gets the recommended satoshi per byte fee. :param speed: One of: 'fast', 'medium', 'slow'. :type speed: ``string`` :rtype: ``int`` """ if speed == FEE_SPEED_FAST: return DEFAULT_FEE_FAST elif speed == FEE_SPEED_MEDIUM: return DEFAULT_F...
python
def get_fee(speed=FEE_SPEED_MEDIUM): """Gets the recommended satoshi per byte fee. :param speed: One of: 'fast', 'medium', 'slow'. :type speed: ``string`` :rtype: ``int`` """ if speed == FEE_SPEED_FAST: return DEFAULT_FEE_FAST elif speed == FEE_SPEED_MEDIUM: return DEFAULT_F...
[ "def", "get_fee", "(", "speed", "=", "FEE_SPEED_MEDIUM", ")", ":", "if", "speed", "==", "FEE_SPEED_FAST", ":", "return", "DEFAULT_FEE_FAST", "elif", "speed", "==", "FEE_SPEED_MEDIUM", ":", "return", "DEFAULT_FEE_MEDIUM", "elif", "speed", "==", "FEE_SPEED_SLOW", ":...
Gets the recommended satoshi per byte fee. :param speed: One of: 'fast', 'medium', 'slow'. :type speed: ``string`` :rtype: ``int``
[ "Gets", "the", "recommended", "satoshi", "per", "byte", "fee", "." ]
train
https://github.com/sporestack/bitcash/blob/c7a18b9d82af98f1000c456dd06131524c260b7f/bitcash/network/fees.py#L15-L29
sporestack/bitcash
bitcash/wallet.py
PrivateKey.get_unspents
def get_unspents(self): """Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent` """ self.unspents[:] = NetworkAPI.get_unspent(self.address) self.balance = sum(unspent.amount for unspent in self.unspents) return sel...
python
def get_unspents(self): """Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent` """ self.unspents[:] = NetworkAPI.get_unspent(self.address) self.balance = sum(unspent.amount for unspent in self.unspents) return sel...
[ "def", "get_unspents", "(", "self", ")", ":", "self", ".", "unspents", "[", ":", "]", "=", "NetworkAPI", ".", "get_unspent", "(", "self", ".", "address", ")", "self", ".", "balance", "=", "sum", "(", "unspent", ".", "amount", "for", "unspent", "in", ...
Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent`
[ "Fetches", "all", "available", "unspent", "transaction", "outputs", "." ]
train
https://github.com/sporestack/bitcash/blob/c7a18b9d82af98f1000c456dd06131524c260b7f/bitcash/wallet.py#L191-L198
sporestack/bitcash
bitcash/wallet.py
PrivateKey.create_transaction
def create_transaction(self, outputs, fee=None, leftover=None, combine=True, message=None, unspents=None, custom_pushdata=False): # pragma: no cover """Creates a signed P2PKH transaction. :param outputs: A sequence of outputs you wish to send in the form ...
python
def create_transaction(self, outputs, fee=None, leftover=None, combine=True, message=None, unspents=None, custom_pushdata=False): # pragma: no cover """Creates a signed P2PKH transaction. :param outputs: A sequence of outputs you wish to send in the form ...
[ "def", "create_transaction", "(", "self", ",", "outputs", ",", "fee", "=", "None", ",", "leftover", "=", "None", ",", "combine", "=", "True", ",", "message", "=", "None", ",", "unspents", "=", "None", ",", "custom_pushdata", "=", "False", ")", ":", "# ...
Creates a signed P2PKH transaction. :param outputs: A sequence of outputs you wish to send in the form ``(destination, amount, currency)``. The amount can be either an int, float, or string as long as it is a valid input to ``decimal.Decim...
[ "Creates", "a", "signed", "P2PKH", "transaction", "." ]
train
https://github.com/sporestack/bitcash/blob/c7a18b9d82af98f1000c456dd06131524c260b7f/bitcash/wallet.py#L208-L253
sporestack/bitcash
bitcash/wallet.py
PrivateKey.sign_transaction
def sign_transaction(self, tx_data): # pragma: no cover """Creates a signed P2PKH transaction using previously prepared transaction data. :param tx_data: Output of :func:`~bitcash.PrivateKey.prepare_transaction`. :type tx_data: ``str`` :returns: The signed transaction as hex. ...
python
def sign_transaction(self, tx_data): # pragma: no cover """Creates a signed P2PKH transaction using previously prepared transaction data. :param tx_data: Output of :func:`~bitcash.PrivateKey.prepare_transaction`. :type tx_data: ``str`` :returns: The signed transaction as hex. ...
[ "def", "sign_transaction", "(", "self", ",", "tx_data", ")", ":", "# pragma: no cover", "data", "=", "json", ".", "loads", "(", "tx_data", ")", "unspents", "=", "[", "Unspent", ".", "from_dict", "(", "unspent", ")", "for", "unspent", "in", "data", "[", "...
Creates a signed P2PKH transaction using previously prepared transaction data. :param tx_data: Output of :func:`~bitcash.PrivateKey.prepare_transaction`. :type tx_data: ``str`` :returns: The signed transaction as hex. :rtype: ``str``
[ "Creates", "a", "signed", "P2PKH", "transaction", "using", "previously", "prepared", "transaction", "data", "." ]
train
https://github.com/sporestack/bitcash/blob/c7a18b9d82af98f1000c456dd06131524c260b7f/bitcash/wallet.py#L355-L369
sporestack/bitcash
bitcash/transaction.py
sanitize_tx_data
def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True, message=None, compressed=True, custom_pushdata=False): """ sanitize_tx_data() fee is in satoshis per byte. """ outputs = outputs.copy() for i, output in enumerate(outputs): dest, amount, currency = output # L...
python
def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True, message=None, compressed=True, custom_pushdata=False): """ sanitize_tx_data() fee is in satoshis per byte. """ outputs = outputs.copy() for i, output in enumerate(outputs): dest, amount, currency = output # L...
[ "def", "sanitize_tx_data", "(", "unspents", ",", "outputs", ",", "fee", ",", "leftover", ",", "combine", "=", "True", ",", "message", "=", "None", ",", "compressed", "=", "True", ",", "custom_pushdata", "=", "False", ")", ":", "outputs", "=", "outputs", ...
sanitize_tx_data() fee is in satoshis per byte.
[ "sanitize_tx_data", "()" ]
train
https://github.com/sporestack/bitcash/blob/c7a18b9d82af98f1000c456dd06131524c260b7f/bitcash/transaction.py#L132-L213
Groundworkstech/pybfd
setup.py
CustomBuildExtension.find_binutils_libs
def find_binutils_libs(self, libdir, lib_ext): """Find Binutils libraries.""" bfd_expr = re.compile("(lib(?:bfd)|(?:opcodes))(.*?)\%s" % lib_ext ) libs = {} for root, dirs, files in os.walk(libdir): for f in files: m = bfd_expr.search(f) if m: ...
python
def find_binutils_libs(self, libdir, lib_ext): """Find Binutils libraries.""" bfd_expr = re.compile("(lib(?:bfd)|(?:opcodes))(.*?)\%s" % lib_ext ) libs = {} for root, dirs, files in os.walk(libdir): for f in files: m = bfd_expr.search(f) if m: ...
[ "def", "find_binutils_libs", "(", "self", ",", "libdir", ",", "lib_ext", ")", ":", "bfd_expr", "=", "re", ".", "compile", "(", "\"(lib(?:bfd)|(?:opcodes))(.*?)\\%s\"", "%", "lib_ext", ")", "libs", "=", "{", "}", "for", "root", ",", "dirs", ",", "files", "i...
Find Binutils libraries.
[ "Find", "Binutils", "libraries", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/setup.py#L117-L142
Groundworkstech/pybfd
setup.py
CustomBuildExtension.generate_source_files
def generate_source_files( self ): """ Genertate source files to be used during the compile process of the extension module. This is better than just hardcoding the values on python files because header definitions might change along differente Binutils versions and we'll...
python
def generate_source_files( self ): """ Genertate source files to be used during the compile process of the extension module. This is better than just hardcoding the values on python files because header definitions might change along differente Binutils versions and we'll...
[ "def", "generate_source_files", "(", "self", ")", ":", "from", "pybfd", ".", "gen_supported_disasm", "import", "get_supported_architectures", ",", "get_supported_machines", ",", "generate_supported_architectures_source", ",", "generate_supported_disassembler_header", ",", "gen_...
Genertate source files to be used during the compile process of the extension module. This is better than just hardcoding the values on python files because header definitions might change along differente Binutils versions and we'll be able to catch the changes and keep the correct valu...
[ "Genertate", "source", "files", "to", "be", "used", "during", "the", "compile", "process", "of", "the", "extension", "module", ".", "This", "is", "better", "than", "just", "hardcoding", "the", "values", "on", "python", "files", "because", "header", "definition...
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/setup.py#L152-L265
Groundworkstech/pybfd
setup.py
CustomBuildExtension._darwin_current_arch
def _darwin_current_arch(self): """Add Mac OS X support.""" if sys.platform == "darwin": if sys.maxsize > 2 ** 32: # 64bits. return platform.mac_ver()[2] # Both Darwin and Python are 64bits. else: # Python 32 bits return platform.processor()
python
def _darwin_current_arch(self): """Add Mac OS X support.""" if sys.platform == "darwin": if sys.maxsize > 2 ** 32: # 64bits. return platform.mac_ver()[2] # Both Darwin and Python are 64bits. else: # Python 32 bits return platform.processor()
[ "def", "_darwin_current_arch", "(", "self", ")", ":", "if", "sys", ".", "platform", "==", "\"darwin\"", ":", "if", "sys", ".", "maxsize", ">", "2", "**", "32", ":", "# 64bits.", "return", "platform", ".", "mac_ver", "(", ")", "[", "2", "]", "# Both Dar...
Add Mac OS X support.
[ "Add", "Mac", "OS", "X", "support", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/setup.py#L267-L273
Groundworkstech/pybfd
setup.py
CustomBuildExtension.build_extensions
def build_extensions(self): """Compile the python extension module for further installation.""" global final_supported_archs ext_extra_objects = [] ext_libs = [] ext_libs_dir = [] ext_includes = [] self.platform = CustomBuildExtension.PLATFORMS.get( sys.platform...
python
def build_extensions(self): """Compile the python extension module for further installation.""" global final_supported_archs ext_extra_objects = [] ext_libs = [] ext_libs_dir = [] ext_includes = [] self.platform = CustomBuildExtension.PLATFORMS.get( sys.platform...
[ "def", "build_extensions", "(", "self", ")", ":", "global", "final_supported_archs", "ext_extra_objects", "=", "[", "]", "ext_libs", "=", "[", "]", "ext_libs_dir", "=", "[", "]", "ext_includes", "=", "[", "]", "self", ".", "platform", "=", "CustomBuildExtensio...
Compile the python extension module for further installation.
[ "Compile", "the", "python", "extension", "module", "for", "further", "installation", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/setup.py#L275-L383
Groundworkstech/pybfd
pybfd/objdump.py
init_parser
def init_parser(): """Initialize option parser.""" usage = "Usage: %(prog)s <option(s)> <file(s)>" description = " Display information from object <file(s)>.\n" description += " At least one of the following switches must be given:" # # Create an argument parser and an exclusive group. # ...
python
def init_parser(): """Initialize option parser.""" usage = "Usage: %(prog)s <option(s)> <file(s)>" description = " Display information from object <file(s)>.\n" description += " At least one of the following switches must be given:" # # Create an argument parser and an exclusive group. # ...
[ "def", "init_parser", "(", ")", ":", "usage", "=", "\"Usage: %(prog)s <option(s)> <file(s)>\"", "description", "=", "\" Display information from object <file(s)>.\\n\"", "description", "+=", "\" At least one of the following switches must be given:\"", "#", "# Create an argument parser...
Initialize option parser.
[ "Initialize", "option", "parser", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/objdump.py#L254-L341
Groundworkstech/pybfd
pybfd/objdump.py
DumpSectionContentAction.dump
def dump(self, src, length=16, start=0, preffix=""): """Dump the specified buffer in hex + ASCII format.""" FILTER = \ "".join([(len(repr(chr(x)))==3) and chr(x) or '.' \ for x in xrange(256)]) result = list() for i in xrange(0, len(src), length): ...
python
def dump(self, src, length=16, start=0, preffix=""): """Dump the specified buffer in hex + ASCII format.""" FILTER = \ "".join([(len(repr(chr(x)))==3) and chr(x) or '.' \ for x in xrange(256)]) result = list() for i in xrange(0, len(src), length): ...
[ "def", "dump", "(", "self", ",", "src", ",", "length", "=", "16", ",", "start", "=", "0", ",", "preffix", "=", "\"\"", ")", ":", "FILTER", "=", "\"\"", ".", "join", "(", "[", "(", "len", "(", "repr", "(", "chr", "(", "x", ")", ")", ")", "==...
Dump the specified buffer in hex + ASCII format.
[ "Dump", "the", "specified", "buffer", "in", "hex", "+", "ASCII", "format", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/objdump.py#L208-L224
Groundworkstech/pybfd
pybfd/section.py
BfdSection.content
def content(self): """Return the entire section content.""" return _bfd.section_get_content(self.bfd, self._ptr, 0, self.size)
python
def content(self): """Return the entire section content.""" return _bfd.section_get_content(self.bfd, self._ptr, 0, self.size)
[ "def", "content", "(", "self", ")", ":", "return", "_bfd", ".", "section_get_content", "(", "self", ".", "bfd", ",", "self", ".", "_ptr", ",", "0", ",", "self", ".", "size", ")" ]
Return the entire section content.
[ "Return", "the", "entire", "section", "content", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/section.py#L473-L475
Groundworkstech/pybfd
pybfd/section.py
BfdSection.get_content
def get_content(self, offset, size): """Return the specified number of bytes from the current section.""" return _bfd.section_get_content(self.bfd, self._ptr, offset, size)
python
def get_content(self, offset, size): """Return the specified number of bytes from the current section.""" return _bfd.section_get_content(self.bfd, self._ptr, offset, size)
[ "def", "get_content", "(", "self", ",", "offset", ",", "size", ")", ":", "return", "_bfd", ".", "section_get_content", "(", "self", ".", "bfd", ",", "self", ".", "_ptr", ",", "offset", ",", "size", ")" ]
Return the specified number of bytes from the current section.
[ "Return", "the", "specified", "number", "of", "bytes", "from", "the", "current", "section", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/section.py#L477-L479
Groundworkstech/pybfd
pybfd/opcodes.py
main
def main(): """Test case for simple opcode disassembly.""" test_targets = ( [ARCH_I386, MACH_I386_I386_INTEL_SYNTAX, ENDIAN_MONO, "\x55\x89\xe5\xE8\xB8\xFF\xFF\xFF", 0x1000], [ARCH_I386, MACH_X86_64_INTEL_SYNTAX, ENDIAN_MONO, "\x55\x48\x89\xe5\xE8\xA3\xFF\xFF\xFF", 0x1000], [ARCH_ARM...
python
def main(): """Test case for simple opcode disassembly.""" test_targets = ( [ARCH_I386, MACH_I386_I386_INTEL_SYNTAX, ENDIAN_MONO, "\x55\x89\xe5\xE8\xB8\xFF\xFF\xFF", 0x1000], [ARCH_I386, MACH_X86_64_INTEL_SYNTAX, ENDIAN_MONO, "\x55\x48\x89\xe5\xE8\xA3\xFF\xFF\xFF", 0x1000], [ARCH_ARM...
[ "def", "main", "(", ")", ":", "test_targets", "=", "(", "[", "ARCH_I386", ",", "MACH_I386_I386_INTEL_SYNTAX", ",", "ENDIAN_MONO", ",", "\"\\x55\\x89\\xe5\\xE8\\xB8\\xFF\\xFF\\xFF\"", ",", "0x1000", "]", ",", "[", "ARCH_I386", ",", "MACH_X86_64_INTEL_SYNTAX", ",", "E...
Test case for simple opcode disassembly.
[ "Test", "case", "for", "simple", "opcode", "disassembly", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/opcodes.py#L186-L211
Groundworkstech/pybfd
pybfd/opcodes.py
Opcodes.initialize_bfd
def initialize_bfd(self, abfd): """Initialize underlying libOpcodes library using BFD.""" self._ptr = _opcodes.initialize_bfd(abfd._ptr) # Already done inside opcodes.c #self.architecture = abfd.architecture #self.machine = abfd.machine #self.endian = abfd....
python
def initialize_bfd(self, abfd): """Initialize underlying libOpcodes library using BFD.""" self._ptr = _opcodes.initialize_bfd(abfd._ptr) # Already done inside opcodes.c #self.architecture = abfd.architecture #self.machine = abfd.machine #self.endian = abfd....
[ "def", "initialize_bfd", "(", "self", ",", "abfd", ")", ":", "self", ".", "_ptr", "=", "_opcodes", ".", "initialize_bfd", "(", "abfd", ".", "_ptr", ")", "# Already done inside opcodes.c", "#self.architecture = abfd.architecture", "#self.machine = abfd.machine", "#self.e...
Initialize underlying libOpcodes library using BFD.
[ "Initialize", "underlying", "libOpcodes", "library", "using", "BFD", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/opcodes.py#L84-L99
Groundworkstech/pybfd
pybfd/opcodes.py
Opcodes.initialize_non_bfd
def initialize_non_bfd(self, architecture=None, machine=None, endian=ENDIAN_UNKNOWN): """Initialize underlying libOpcodes library not using BFD.""" if None in [architecture, machine, endian]: return self.architecture = architecture self.machine = machine sel...
python
def initialize_non_bfd(self, architecture=None, machine=None, endian=ENDIAN_UNKNOWN): """Initialize underlying libOpcodes library not using BFD.""" if None in [architecture, machine, endian]: return self.architecture = architecture self.machine = machine sel...
[ "def", "initialize_non_bfd", "(", "self", ",", "architecture", "=", "None", ",", "machine", "=", "None", ",", "endian", "=", "ENDIAN_UNKNOWN", ")", ":", "if", "None", "in", "[", "architecture", ",", "machine", ",", "endian", "]", ":", "return", "self", "...
Initialize underlying libOpcodes library not using BFD.
[ "Initialize", "underlying", "libOpcodes", "library", "not", "using", "BFD", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/opcodes.py#L102-L111
Groundworkstech/pybfd
pybfd/opcodes.py
Opcodes.initialize_smart_disassemble
def initialize_smart_disassemble(self, data, start_address=0): """ Set the binary buffer to disassemble with other related information ready for an instruction by instruction disassembly session. """ _opcodes.initialize_smart_disassemble( self._ptr, data, sta...
python
def initialize_smart_disassemble(self, data, start_address=0): """ Set the binary buffer to disassemble with other related information ready for an instruction by instruction disassembly session. """ _opcodes.initialize_smart_disassemble( self._ptr, data, sta...
[ "def", "initialize_smart_disassemble", "(", "self", ",", "data", ",", "start_address", "=", "0", ")", ":", "_opcodes", ".", "initialize_smart_disassemble", "(", "self", ".", "_ptr", ",", "data", ",", "start_address", ")" ]
Set the binary buffer to disassemble with other related information ready for an instruction by instruction disassembly session.
[ "Set", "the", "binary", "buffer", "to", "disassemble", "with", "other", "related", "information", "ready", "for", "an", "instruction", "by", "instruction", "disassembly", "session", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/opcodes.py#L113-L120
Groundworkstech/pybfd
pybfd/opcodes.py
Opcodes.start_smart_disassemble
def start_smart_disassemble(self, start_address, callback): """ Invok the callback function for every instruction disassembled at the previously initialized smart session with the given offset from the start address supplied (also in the initialization). """ _opcodes.sta...
python
def start_smart_disassemble(self, start_address, callback): """ Invok the callback function for every instruction disassembled at the previously initialized smart session with the given offset from the start address supplied (also in the initialization). """ _opcodes.sta...
[ "def", "start_smart_disassemble", "(", "self", ",", "start_address", ",", "callback", ")", ":", "_opcodes", ".", "start_smart_disassemble", "(", "self", ".", "_ptr", ",", "start_address", ",", "callback", ")" ]
Invok the callback function for every instruction disassembled at the previously initialized smart session with the given offset from the start address supplied (also in the initialization).
[ "Invok", "the", "callback", "function", "for", "every", "instruction", "disassembled", "at", "the", "previously", "initialized", "smart", "session", "with", "the", "given", "offset", "from", "the", "start", "address", "supplied", "(", "also", "in", "the", "initi...
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/opcodes.py#L122-L129
Groundworkstech/pybfd
pybfd/opcodes.py
Opcodes.print_single_instruction_callback
def print_single_instruction_callback(self, address, size, branch_delay_insn, insn_type, target, target2, disassembly): """ Callack on each disassembled instruction to print its information. """ print "0x%X SZ=%d BD=%d IT=%d\t%s" % \ (address, size, branch_de...
python
def print_single_instruction_callback(self, address, size, branch_delay_insn, insn_type, target, target2, disassembly): """ Callack on each disassembled instruction to print its information. """ print "0x%X SZ=%d BD=%d IT=%d\t%s" % \ (address, size, branch_de...
[ "def", "print_single_instruction_callback", "(", "self", ",", "address", ",", "size", ",", "branch_delay_insn", ",", "insn_type", ",", "target", ",", "target2", ",", "disassembly", ")", ":", "print", "\"0x%X SZ=%d BD=%d IT=%d\\t%s\"", "%", "(", "address", ",", "si...
Callack on each disassembled instruction to print its information.
[ "Callack", "on", "each", "disassembled", "instruction", "to", "print", "its", "information", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/opcodes.py#L131-L140
Groundworkstech/pybfd
pybfd/opcodes.py
Opcodes.disassemble
def disassemble(self, data, start_address=0): """ Return a list containing the virtual memory address, instruction length and disassembly code for the given binary buffer. """ return _opcodes.disassemble(self._ptr, data, start_address)
python
def disassemble(self, data, start_address=0): """ Return a list containing the virtual memory address, instruction length and disassembly code for the given binary buffer. """ return _opcodes.disassemble(self._ptr, data, start_address)
[ "def", "disassemble", "(", "self", ",", "data", ",", "start_address", "=", "0", ")", ":", "return", "_opcodes", ".", "disassemble", "(", "self", ".", "_ptr", ",", "data", ",", "start_address", ")" ]
Return a list containing the virtual memory address, instruction length and disassembly code for the given binary buffer.
[ "Return", "a", "list", "containing", "the", "virtual", "memory", "address", "instruction", "length", "and", "disassembly", "code", "for", "the", "given", "binary", "buffer", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/opcodes.py#L142-L148
Groundworkstech/pybfd
pybfd/gen_supported_disasm.py
generate_supported_disassembler_header
def generate_supported_disassembler_header(supported_archs): """Extract export symbols using binutils's nm utility from Binutils and generate a current header for PyBFD. """ arch_entries = [] for arch, little, big, comment in supported_archs: arch_entries.append( header_arch_entry % (arch,...
python
def generate_supported_disassembler_header(supported_archs): """Extract export symbols using binutils's nm utility from Binutils and generate a current header for PyBFD. """ arch_entries = [] for arch, little, big, comment in supported_archs: arch_entries.append( header_arch_entry % (arch,...
[ "def", "generate_supported_disassembler_header", "(", "supported_archs", ")", ":", "arch_entries", "=", "[", "]", "for", "arch", ",", "little", ",", "big", ",", "comment", "in", "supported_archs", ":", "arch_entries", ".", "append", "(", "header_arch_entry", "%", ...
Extract export symbols using binutils's nm utility from Binutils and generate a current header for PyBFD.
[ "Extract", "export", "symbols", "using", "binutils", "s", "nm", "utility", "from", "Binutils", "and", "generate", "a", "current", "header", "for", "PyBFD", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/gen_supported_disasm.py#L215-L225
Groundworkstech/pybfd
pybfd/gen_supported_disasm.py
generate_supported_architectures_source
def generate_supported_architectures_source(supported_archs, supported_machines): """Extract export symbols using binutils's nm utility from Binutils and generate a current header for PyBFD. """ arch_entries = [] mach_entries = [] for arch, little, big, comment in supported_archs: arch...
python
def generate_supported_architectures_source(supported_archs, supported_machines): """Extract export symbols using binutils's nm utility from Binutils and generate a current header for PyBFD. """ arch_entries = [] mach_entries = [] for arch, little, big, comment in supported_archs: arch...
[ "def", "generate_supported_architectures_source", "(", "supported_archs", ",", "supported_machines", ")", ":", "arch_entries", "=", "[", "]", "mach_entries", "=", "[", "]", "for", "arch", ",", "little", ",", "big", ",", "comment", "in", "supported_archs", ":", "...
Extract export symbols using binutils's nm utility from Binutils and generate a current header for PyBFD.
[ "Extract", "export", "symbols", "using", "binutils", "s", "nm", "utility", "from", "Binutils", "and", "generate", "a", "current", "header", "for", "PyBFD", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/gen_supported_disasm.py#L227-L243
Groundworkstech/pybfd
pybfd/bfd.py
Bfd.open
def open(self, _file, target=DEFAULT_TARGET): """ Open the existing file for reading. @param _file : A filename of file descriptor. @param target: A user-specific BFD target name. @return : None """ # Close any existing BFD structure instance. self.clos...
python
def open(self, _file, target=DEFAULT_TARGET): """ Open the existing file for reading. @param _file : A filename of file descriptor. @param target: A user-specific BFD target name. @return : None """ # Close any existing BFD structure instance. self.clos...
[ "def", "open", "(", "self", ",", "_file", ",", "target", "=", "DEFAULT_TARGET", ")", ":", "# Close any existing BFD structure instance. ", "self", ".", "close", "(", ")", "#", "# STEP 1. Open the BFD pointer.", "#", "# Determine if the user passed a file-descriptor or a _fi...
Open the existing file for reading. @param _file : A filename of file descriptor. @param target: A user-specific BFD target name. @return : None
[ "Open", "the", "existing", "file", "for", "reading", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L118-L215
Groundworkstech/pybfd
pybfd/bfd.py
Bfd.__populate_archive_files
def __populate_archive_files(self): """Store the list of files inside an archive file.""" self.archive_files = [] for _ptr in _bfd.archive_list_files(self._ptr): try: self.archive_files.append(Bfd(_ptr)) except BfdException, err: #print "Er...
python
def __populate_archive_files(self): """Store the list of files inside an archive file.""" self.archive_files = [] for _ptr in _bfd.archive_list_files(self._ptr): try: self.archive_files.append(Bfd(_ptr)) except BfdException, err: #print "Er...
[ "def", "__populate_archive_files", "(", "self", ")", ":", "self", ".", "archive_files", "=", "[", "]", "for", "_ptr", "in", "_bfd", ".", "archive_list_files", "(", "self", ".", "_ptr", ")", ":", "try", ":", "self", ".", "archive_files", ".", "append", "(...
Store the list of files inside an archive file.
[ "Store", "the", "list", "of", "files", "inside", "an", "archive", "file", "." ]
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L217-L226