_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q30700
add_inspection
train
def add_inspection(name): """ Add a Jishaku object inspection """ # create the real decorator def inspection_inner(func): """ Jishaku inspection decorator """ # pylint: disable=inconsistent-return-statements # create
python
{ "resource": "" }
q30701
all_inspections
train
def all_inspections(obj): """ Generator to iterate all current Jishaku inspections. """ for name, callback in INSPECTIONS:
python
{ "resource": "" }
q30702
class_name
train
def class_name(obj): """ Get the name of an object, including the module name if available. """ name = obj.__name__ module
python
{ "resource": "" }
q30703
PaginatorInterface.pages
train
def pages(self): """ Returns the paginator's pages without prematurely closing the active page. """ # protected access has to be permitted here to not close the paginator's pages # pylint: disable=protected-access paginator_pages = list(self.paginator._pages) if ...
python
{ "resource": "" }
q30704
PaginatorInterface.display_page
train
def display_page(self): """ Returns the current page the paginator interface is on. """
python
{ "resource": "" }
q30705
PaginatorInterface.display_page
train
def display_page(self, value): """ Sets the current page the paginator is on. Automatically pushes values inbounds. """
python
{ "resource": "" }
q30706
PaginatorInterface.page_size
train
def page_size(self) -> int: """ A property that returns how large a page is, calculated from the paginator properties. If this exceeds `max_page_size`, an exception is raised upon instantiation.
python
{ "resource": "" }
q30707
PaginatorInterface.add_line
train
async def add_line(self, *args, **kwargs): """ A proxy function that allows this PaginatorInterface to remain locked to the last page if it is already on it. """ display_page = self.display_page page_count = self.page_count self.paginator.add_line(*args, **kwarg...
python
{ "resource": "" }
q30708
PaginatorInterface.send_to
train
async def send_to(self, destination: discord.abc.Messageable): """ Sends a message to the given destination with this interface. This automatically creates the response task for you. """ self.message = await destination.send(**self.send_kwargs) # add the close reaction...
python
{ "resource": "" }
q30709
PaginatorInterface.send_all_reactions
train
async def send_all_reactions(self): """ Sends all reactions for this paginator, if any are missing. This method is generally for internal use only. """
python
{ "resource": "" }
q30710
PaginatorInterface.wait_loop
train
async def wait_loop(self): """ Waits on a loop for reactions to the message. This should not be called manually - it is handled by `send_to`. """ start, back, forward, end, close = self.emojis def check(payload: discord.RawReactionActionEvent): """ Check...
python
{ "resource": "" }
q30711
PaginatorInterface.update
train
async def update(self): """ Updates this interface's messages with the latest data. """ if self.update_lock.locked(): return async with self.update_lock: if self.update_lock.locked(): # if this engagement has caused the semaphore to exhau...
python
{ "resource": "" }
q30712
Jishaku.submit
train
def submit(self, ctx: commands.Context): """ A context-manager that submits the current task to jishaku's task list and removes it afterwards. Arguments --------- ctx: commands.Context A Context object used to derive information about this command task. ...
python
{ "resource": "" }
q30713
Jishaku.cog_check
train
async def cog_check(self, ctx: commands.Context): """ Local check, makes all commands in this cog owner-only
python
{ "resource": "" }
q30714
Jishaku.jsk
train
async def jsk(self, ctx: commands.Context): """ The Jishaku debug and diagnostic commands. This command on its own gives a status brief. All other functionality is within its subcommands. """ summary = [ f"Jishaku v{__version__}, discord.py `{package_version...
python
{ "resource": "" }
q30715
Jishaku.jsk_hide
train
async def jsk_hide(self, ctx: commands.Context): """ Hides Jishaku from the help command. """ if self.jsk.hidden:
python
{ "resource": "" }
q30716
Jishaku.jsk_show
train
async def jsk_show(self, ctx: commands.Context): """ Shows Jishaku in the help command. """ if not self.jsk.hidden:
python
{ "resource": "" }
q30717
Jishaku.jsk_tasks
train
async def jsk_tasks(self, ctx: commands.Context): """ Shows the currently running jishaku tasks. """ if not self.tasks: return await ctx.send("No currently running tasks.") paginator = commands.Paginator(max_size=1985) for task in self.tasks: pa...
python
{ "resource": "" }
q30718
Jishaku.jsk_cancel
train
async def jsk_cancel(self, ctx: commands.Context, *, index: int): """ Cancels a task with the given index. If the index passed is -1, will cancel the last task instead. """ if not self.tasks: return await ctx.send("No tasks to cancel.") if index == -1: ...
python
{ "resource": "" }
q30719
Jishaku.jsk_load
train
async def jsk_load(self, ctx: commands.Context, *extensions: ExtensionConverter): """ Loads or reloads the given extension names. Reports any extensions that failed to load. """ paginator = commands.Paginator(prefix='', suffix='') for extension in itertools.chain(*exte...
python
{ "resource": "" }
q30720
Jishaku.jsk_shutdown
train
async def jsk_shutdown(self, ctx: commands.Context): """ Logs this bot out. """
python
{ "resource": "" }
q30721
Jishaku.jsk_su
train
async def jsk_su(self, ctx: commands.Context, target: discord.User, *, command_string: str): """ Run a command as someone else. This will try to resolve to a Member, but will use a User if it can't find one. """ if ctx.guild: # Try to upgrade to a Member instance ...
python
{ "resource": "" }
q30722
Jishaku.jsk_in
train
async def jsk_in(self, ctx: commands.Context, channel: discord.TextChannel, *, command_string: str): """ Run a command as if it were in a different channel. """ alt_ctx = await copy_context_with(ctx, channel=channel, content=ctx.prefix + command_string)
python
{ "resource": "" }
q30723
Jishaku.jsk_sudo
train
async def jsk_sudo(self, ctx: commands.Context, *, command_string: str): """ Run a command bypassing all checks and cooldowns. This also bypasses permission checks so this has a high possibility of making a command raise. """ alt_ctx = await copy_context_with(ctx, content=ctx.p...
python
{ "resource": "" }
q30724
Jishaku.jsk_repeat
train
async def jsk_repeat(self, ctx: commands.Context, times: int, *, command_string: str): """ Runs a command multiple times in a row. This acts like the command was invoked several times manually, so it obeys cooldowns. """ with self.submit(ctx): # allow repeats to be cancelled ...
python
{ "resource": "" }
q30725
Jishaku.jsk_debug
train
async def jsk_debug(self, ctx: commands.Context, *, command_string: str): """ Run a command timing execution and catching exceptions. """ alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string) if alt_ctx.command is None: return await ctx.send(f'...
python
{ "resource": "" }
q30726
Jishaku.jsk_cat
train
async def jsk_cat(self, ctx: commands.Context, argument: str): """ Read out a file, using syntax highlighting if detected. Lines and linespans are supported by adding '#L12' or '#L12-14' etc to the end of the filename. """ match = self.__cat_line_regex.search(argument) ...
python
{ "resource": "" }
q30727
Jishaku.jsk_curl
train
async def jsk_curl(self, ctx: commands.Context, url: str): """ Download and display a text file from the internet. This command is similar to jsk cat, but accepts a URL. """ # remove embed maskers if present url = url.lstrip("<").rstrip(">") async with ReplResp...
python
{ "resource": "" }
q30728
Jishaku.jsk_source
train
async def jsk_source(self, ctx: commands.Context, *, command_name: str): """ Displays the source code for a command. """ command = self.bot.get_command(command_name) if not command: return await ctx.send(f"Couldn't find command `{command_name}`.") try: ...
python
{ "resource": "" }
q30729
Jishaku.jsk_retain
train
async def jsk_retain(self, ctx: commands.Context, *, toggle: bool = None): """ Turn variable retention for REPL on or off. Provide no argument for current status. """ if toggle is None: if self.retain: return await ctx.send("Variable retention is set...
python
{ "resource": "" }
q30730
Jishaku.jsk_python
train
async def jsk_python(self, ctx: commands.Context, *, argument: CodeblockConverter): """ Direct evaluation of Python code. """ arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX) arg_dict["_"] = self.last_result scope = self.scope try: async with Rep...
python
{ "resource": "" }
q30731
Jishaku.jsk_python_inspect
train
async def jsk_python_inspect(self, ctx: commands.Context, *, argument: CodeblockConverter): """ Evaluation of Python code with inspect information. """ arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX) arg_dict["_"] = self.last_result scope = self.scope try: ...
python
{ "resource": "" }
q30732
Jishaku.jsk_shell
train
async def jsk_shell(self, ctx: commands.Context, *, argument: CodeblockConverter): """ Executes statements in the system shell. This uses the bash shell. Execution can be cancelled by closing the paginator. """ async with ReplResponseReactor(ctx.message): with self....
python
{ "resource": "" }
q30733
Jishaku.jsk_git
train
async def jsk_git(self, ctx: commands.Context, *, argument: CodeblockConverter): """ Shortcut for 'jsk sh git'. Invokes the system shell. """
python
{ "resource": "" }
q30734
Jishaku.jsk_voice
train
async def jsk_voice(self, ctx: commands.Context): """ Voice-related commands. If invoked without subcommand, relays current voice state. """ # if using a subcommand, short out if ctx.invoked_subcommand is not None and ctx.invoked_subcommand is not self.jsk_voice:
python
{ "resource": "" }
q30735
Jishaku.jsk_vc_join
train
async def jsk_vc_join(self, ctx: commands.Context, *, destination: typing.Union[discord.VoiceChannel, discord.Member] = None): """ Joins a voice channel, or moves to it if already connected. Passing a voice channel uses that voice channel. Passing a member will...
python
{ "resource": "" }
q30736
Jishaku.jsk_vc_disconnect
train
async def jsk_vc_disconnect(self, ctx: commands.Context): """ Disconnects from the voice channel in this guild, if
python
{ "resource": "" }
q30737
Jishaku.jsk_vc_stop
train
async def jsk_vc_stop(self, ctx: commands.Context): """ Stops running an audio source, if there is one.
python
{ "resource": "" }
q30738
Jishaku.jsk_vc_pause
train
async def jsk_vc_pause(self, ctx: commands.Context): """ Pauses a running audio source, if there is one. """ voice = ctx.guild.voice_client if voice.is_paused():
python
{ "resource": "" }
q30739
Jishaku.jsk_vc_resume
train
async def jsk_vc_resume(self, ctx: commands.Context): """ Resumes a running audio source, if there is one. """ voice = ctx.guild.voice_client if not voice.is_paused():
python
{ "resource": "" }
q30740
Jishaku.jsk_vc_volume
train
async def jsk_vc_volume(self, ctx: commands.Context, *, percentage: float): """ Adjusts the volume of an audio source if it is supported. """ volume = max(0.0, min(1.0, percentage / 100)) source = ctx.guild.voice_client.source
python
{ "resource": "" }
q30741
Jishaku.jsk_vc_play
train
async def jsk_vc_play(self, ctx: commands.Context, *, uri: str): """ Plays audio direct from a URI. Can be either a local file or an audio resource on the internet. """ voice = ctx.guild.voice_client if voice.is_playing(): voice.stop()
python
{ "resource": "" }
q30742
Jishaku.jsk_vc_youtube_dl
train
async def jsk_vc_youtube_dl(self, ctx: commands.Context, *, url: str): """ Plays audio from youtube_dl-compatible sources. """ if not youtube_dl: return await ctx.send("youtube_dl is not installed.") voice = ctx.guild.voice_client if voice.is_playing(): ...
python
{ "resource": "" }
q30743
get_language
train
def get_language(query: str) -> str: """Tries to work out the highlight.js language of a given file name or shebang. Returns an empty string if none match. """ query =
python
{ "resource": "" }
q30744
find_extensions_in
train
def find_extensions_in(path: typing.Union[str, pathlib.Path]) -> list: """ Tries to find things that look like bot extensions in a directory. """ if not isinstance(path, pathlib.Path): path = pathlib.Path(path) if not path.is_dir(): return [] extension_names = [] # Find e...
python
{ "resource": "" }
q30745
resolve_extensions
train
def resolve_extensions(bot: commands.Bot, name: str) -> list: """ Tries to resolve extension queries into a list of extension names. """ if name.endswith('.*'): module_parts = name[:-2].split('.') path = pathlib.Path(module_parts.pop(0)) for part in module_parts:
python
{ "resource": "" }
q30746
package_version
train
def package_version(package_name: str) -> typing.Optional[str]: """ Returns package version as a string, or None if it couldn't be found. """ try:
python
{ "resource": "" }
q30747
vc_check
train
async def vc_check(ctx: commands.Context): # pylint: disable=unused-argument """ Check for whether VC is available in this bot. """ if not discord.voice_client.has_nacl: raise commands.CheckFailure("voice cannot be used because PyNaCl is not loaded")
python
{ "resource": "" }
q30748
connected_check
train
async def connected_check(ctx: commands.Context): """ Check whether we are connected to VC in this guild. """ voice = ctx.guild.voice_client if not voice or
python
{ "resource": "" }
q30749
playing_check
train
async def playing_check(ctx: commands.Context): """ Checks whether we are playing audio in VC in this guild. This doubles up as a connection check. """ if await connected_check(ctx) and not ctx.guild.voice_client.is_playing():
python
{ "resource": "" }
q30750
executor_function
train
def executor_function(sync_function: typing.Callable): """A decorator that wraps a sync function in an executor, changing it into an async function. This allows processing functions to be wrapped and used immediately as an async function. Examples --------- Pushing processing with the Python Imag...
python
{ "resource": "" }
q30751
features
train
def features(sender=''): '''Returns a list of signature features.''' return [ # This one isn't from paper. # Meant to match companies names, sender's names, address. many_capitalized_words, # This one is not from paper. # Line is too long. # This one is less aggre...
python
{ "resource": "" }
q30752
apply_features
train
def apply_features(body, features): '''Applies features to message body lines. Returns list of lists. Each of the lists corresponds to the body line and is constituted by the numbers of features occurrences (0 or 1). E.g. if element j of list i equals 1 this means that feature j occurred in line i ...
python
{ "resource": "" }
q30753
build_pattern
train
def build_pattern(body, features): '''Converts body into a pattern i.e. a point in the features space. Applies features to the body lines and sums up the results.
python
{ "resource": "" }
q30754
get_signature_candidate
train
def get_signature_candidate(lines): """Return lines that could hold signature The lines should: * be among last SIGNATURE_MAX_LINES non-empty lines. * not include first line * be shorter than TOO_LONG_SIGNATURE_LINE * not include more than one line that starts with dashes """ # non emp...
python
{ "resource": "" }
q30755
_mark_candidate_indexes
train
def _mark_candidate_indexes(lines, candidate): """Mark candidate indexes with markers Markers: * c - line that could be a signature line * l - long line * d - line that starts with dashes but has other chars as well >>> _mark_candidate_lines(['Some text', '', '-', 'Bob'], [0, 2, 3]) 'cdc'...
python
{ "resource": "" }
q30756
_process_marked_candidate_indexes
train
def _process_marked_candidate_indexes(candidate, markers): """ Run regexes against candidate's marked indexes to strip signature candidate. >>> _process_marked_candidate_indexes([9, 12, 14, 15, 17], 'clddc') [15, 17]
python
{ "resource": "" }
q30757
contains_sender_names
train
def contains_sender_names(sender): '''Returns a functions to search sender\'s name or it\'s part. >>> feature = contains_sender_names("Sergey N. Obukhov <xxx@example.com>") >>> feature("Sergey Obukhov") 1 >>> feature("BR, Sergey N.") 1 >>> feature("Sergey") 1 >>> contains_sender_na...
python
{ "resource": "" }
q30758
categories_percent
train
def categories_percent(s, categories): '''Returns category characters percent. >>> categories_percent("qqq ggg hhh", ["Po"]) 0.0 >>> categories_percent("q,w.", ["Po"]) 50.0 >>> categories_percent("qqq ggg hhh", ["Nd"]) 0.0 >>> categories_percent("q5", ["Nd"]) 50.0 >>> categories...
python
{ "resource": "" }
q30759
capitalized_words_percent
train
def capitalized_words_percent(s): '''Returns capitalized words percent.''' s = to_unicode(s, precise=True) words = re.split('\s', s) words = [w for w in words if w.strip()] words = [w for w in words if len(w) > 2] capitalized_words_counter = 0 valid_words_counter = 0 for word in word...
python
{ "resource": "" }
q30760
has_signature
train
def has_signature(body, sender): '''Checks if the body has signature. Returns True or False.''' non_empty = [line for line in body.splitlines() if line.strip()] candidate = non_empty[-SIGNATURE_MAX_LINES:] upvotes = 0 for line in candidate: # we check lines for sender's name, phone, email an...
python
{ "resource": "" }
q30761
remove_initial_spaces_and_mark_message_lines
train
def remove_initial_spaces_and_mark_message_lines(lines): """ Removes the initial spaces in each line before marking message lines.
python
{ "resource": "" }
q30762
mark_message_lines
train
def mark_message_lines(lines): """Mark message lines with markers to distinguish quotation lines. Markers: * e - empty line * m - line that starts with quotation marker '>' * s - splitter line * t - presumably lines from the last message in the conversation >>> mark_message_lines(['answer...
python
{ "resource": "" }
q30763
process_marked_lines
train
def process_marked_lines(lines, markers, return_flags=[False, -1, -1]): """Run regexes against message's marked lines to strip quotations. Return only last message lines. >>> mark_message_lines(['Hello', 'From: foo@bar.com', '', '> Hi', 'tsem']) ['Hello'] Also returns return_flags. return_flag...
python
{ "resource": "" }
q30764
preprocess
train
def preprocess(msg_body, delimiter, content_type='text/plain'): """Prepares msg_body for being stripped. Replaces link brackets so that they couldn't be taken for quotation marker. Splits line in two if splitter
python
{ "resource": "" }
q30765
extract_from_plain
train
def extract_from_plain(msg_body): """Extracts a non quoted message from provided plain text.""" stripped_text = msg_body delimiter = get_delimiter(msg_body) msg_body = preprocess(msg_body, delimiter) # don't process too long messages lines = msg_body.splitlines()[:MAX_LINES_COUNT] markers
python
{ "resource": "" }
q30766
_mark_quoted_email_splitlines
train
def _mark_quoted_email_splitlines(markers, lines): """ When there are headers indented with '>' characters, this method will attempt to identify if the header is a splitline header. If it is, then we mark it with 's' instead of leaving it as 'm' and return the new markers. """ # Create a list of...
python
{ "resource": "" }
q30767
_correct_splitlines_in_headers
train
def _correct_splitlines_in_headers(markers, lines): """ Corrects markers by removing splitlines deemed to be inside header blocks. """ updated_markers = "" i = 0 in_header_block = False for m in markers: # Only set in_header_block flag when we hit an 's' and line is a header ...
python
{ "resource": "" }
q30768
is_splitter
train
def is_splitter(line): ''' Returns Matcher object if provided string is a splitter and None otherwise. ''' for pattern in SPLITTER_PATTERNS:
python
{ "resource": "" }
q30769
is_signature_line
train
def is_signature_line(line, sender, classifier): '''Checks if the line belongs to signature. Returns True or False.''' data
python
{ "resource": "" }
q30770
extract
train
def extract(body, sender): """Strips signature from the body of the message. Returns stripped body and signature as a tuple. If no signature is found the corresponding returned value is None. """ try: delimiter = get_delimiter(body) body = body.strip() if has_signature(bod...
python
{ "resource": "" }
q30771
_mark_lines
train
def _mark_lines(lines, sender): """Mark message lines with markers to distinguish signature lines. Markers: * e - empty line * s - line identified as signature * t - other i.e. ordinary text line >>> mark_message_lines(['Some text', '', 'Bob'], 'Bob') 'tes' """ global EXTRACTOR ...
python
{ "resource": "" }
q30772
_process_marked_lines
train
def _process_marked_lines(lines, markers): """Run regexes against message's marked lines to strip signature. >>> _process_marked_lines(['Some text', '', 'Bob'], 'tes') (['Some text', ''], ['Bob']) """ # reverse lines and match signature
python
{ "resource": "" }
q30773
train
train
def train(classifier, train_data_filename, save_classifier_filename=None): """Trains and saves classifier so that it could be easily loaded later.""" file_data = genfromtxt(train_data_filename, delimiter=",")
python
{ "resource": "" }
q30774
load
train
def load(saved_classifier_filename, train_data_filename): """Loads saved classifier. """ try: return joblib.load(saved_classifier_filename) except Exception: import sys
python
{ "resource": "" }
q30775
parse_msg_sender
train
def parse_msg_sender(filename, sender_known=True): """Given a filename returns the sender and the message. Here the message is assumed to be a whole MIME message or just message body. >>> sender, msg = parse_msg_sender('msg.eml') >>> sender, msg = parse_msg_sender('msg_body') If you don't wan...
python
{ "resource": "" }
q30776
build_detection_class
train
def build_detection_class(folder, dataset_filename, label, sender_known=True): """Builds signature detection class. Signature detection dataset includes patterns for two classes: * class for positive patterns (goes with label 1) * class for negative patterns (goes with label -...
python
{ "resource": "" }
q30777
build_detection_dataset
train
def build_detection_dataset(folder, dataset_filename, sender_known=True): """Builds signature detection dataset using emails from folder. folder should have the following structure: x-- folder | x-- P | | | -- positive sample email 1 | | | -- positive ...
python
{ "resource": "" }
q30778
build_extraction_dataset
train
def build_extraction_dataset(folder, dataset_filename, sender_known=True): """Builds signature extraction dataset using emails in the `folder`. The emails in the `folder` should be annotated i.e. signature lines should be marked with `#sig#`. """ if os.path.exists(datas...
python
{ "resource": "" }
q30779
add_checkpoint
train
def add_checkpoint(html_note, counter): """Recursively adds checkpoints to html tree. """ if html_note.text: html_note.text = (html_note.text + CHECKPOINT_PREFIX + str(counter) + CHECKPOINT_SUFFIX) else: html_note.text = (CHECKPOINT_PREFIX + str(counter) + ...
python
{ "resource": "" }
q30780
delete_quotation_tags
train
def delete_quotation_tags(html_note, counter, quotation_checkpoints): """Deletes tags with quotation checkpoints from html tree. """ tag_in_quotation = True if quotation_checkpoints[counter]: html_note.text = '' else: tag_in_quotation = False counter += 1 quotation_children...
python
{ "resource": "" }
q30781
cut_gmail_quote
train
def cut_gmail_quote(html_message): ''' Cuts the outermost block element with class gmail_quote. ''' gmail_quote = cssselect('div.gmail_quote', html_message) if gmail_quote and (gmail_quote[0].text
python
{ "resource": "" }
q30782
cut_microsoft_quote
train
def cut_microsoft_quote(html_message): ''' Cuts splitter block and all following blocks. ''' #use EXSLT extensions to have a regex match() function with lxml ns = {"re": "http://exslt.org/regular-expressions"} #general pattern: @style='border:none;border-top:solid <color> 1.0pt;padding:3.0pt 0<unit> 0<...
python
{ "resource": "" }
q30783
cut_blockquote
train
def cut_blockquote(html_message): ''' Cuts the last non-nested blockquote with wrapping elements.''' quote = html_message.xpath( '(.//blockquote)' '[not(@class="gmail_quote") and not(ancestor::blockquote)]'
python
{ "resource": "" }
q30784
make_commkey
train
def make_commkey(key, session_id, ticks=50): """ take a password and session_id and scramble them to send to the machine. copied from commpro.c - MakeKey """ key = int(key) session_id = int(session_id) k = 0 for i in range(32): if (key & (1 << i)): k = (k << 1 | 1) ...
python
{ "resource": "" }
q30785
ZK.__create_tcp_top
train
def __create_tcp_top(self, packet): """ witch the complete packet set top header """ length = len(packet)
python
{ "resource": "" }
q30786
ZK.__create_header
train
def __create_header(self, command, command_string, session_id, reply_id): """ Puts a the parts that make up a packet together and packs them into a byte string """ buf = pack('<4H', command, 0, session_id, reply_id) + command_string buf = unpack('8B' + '%sB' % len(command_string)...
python
{ "resource": "" }
q30787
ZK.__create_checksum
train
def __create_checksum(self, p): """ Calculates the checksum of the packet to be sent to the time clock Copied from zkemsdk.c """ l = len(p) checksum = 0 while l > 1: checksum += unpack('H', pack('BB', p[0], p[1]))[0] p = p[2:] i...
python
{ "resource": "" }
q30788
ZK.__send_command
train
def __send_command(self, command, command_string=b'', response_size=8): """ send command to the terminal """ if command not in [const.CMD_CONNECT, const.CMD_AUTH] and not self.is_connect: raise ZKErrorConnection("instance are not connected.") buf = self.__create_head...
python
{ "resource": "" }
q30789
ZK.__ack_ok
train
def __ack_ok(self): """ event ack ok """ buf = self.__create_header(const.CMD_ACK_OK, b'', self.__session_id, const.USHRT_MAX - 1) try: if self.tcp: top = self.__create_tcp_top(buf)
python
{ "resource": "" }
q30790
ZK.__get_data_size
train
def __get_data_size(self): """ Checks a returned packet to see if it returned CMD_PREPARE_DATA, indicating that data packets are to be sent Returns the amount of bytes that are going to be sent """ response = self.__response
python
{ "resource": "" }
q30791
ZK.__decode_time
train
def __decode_time(self, t): """ Decode a timestamp retrieved from the timeclock copied from zkemsdk.c - DecodeTime """ t = unpack("<I", t)[0] second = t % 60 t = t // 60 minute = t % 60 t = t // 60 hour = t % 24 t = t // 24 ...
python
{ "resource": "" }
q30792
ZK.__decode_timehex
train
def __decode_timehex(self, timehex): """ timehex string of six bytes """ year, month, day, hour, minute, second = unpack("6B", timehex) year +=
python
{ "resource": "" }
q30793
ZK.__encode_time
train
def __encode_time(self, t): """ Encode a timestamp so that it can be read on the timeclock """ # formula taken from zkemsdk.c - EncodeTime # can also be found in the technical manual d = (
python
{ "resource": "" }
q30794
ZK.connect
train
def connect(self): """ connect to the device :return: bool """ self.end_live_capture = False if not self.ommit_ping and not self.helper.test_ping(): raise ZKNetworkError("can't reach device (ping %s)" % self.__address[0]) if not self.force_udp and sel...
python
{ "resource": "" }
q30795
ZK.disconnect
train
def disconnect(self): """ diconnect from the connected device :return: bool """ cmd_response = self.__send_command(const.CMD_EXIT) if cmd_response.get('status'): self.is_connect = False
python
{ "resource": "" }
q30796
ZK.enable_device
train
def enable_device(self): """ re-enable the connected device and allow user activity in device again :return: bool """ cmd_response = self.__send_command(const.CMD_ENABLEDEVICE) if cmd_response.get('status'):
python
{ "resource": "" }
q30797
ZK.get_device_name
train
def get_device_name(self): """ return the device name :return: str """ command = const.CMD_OPTIONS_RRQ command_string = b'~DeviceName\x00' response_size = 1024 cmd_response = self.__send_command(command,
python
{ "resource": "" }
q30798
ZK.get_network_params
train
def get_network_params(self): """ get network params """ ip = self.__address[0] mask = b'' gate = b'' cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'IPAddress\x00', 1024) if cmd_response.get('status'): ip = (self.__data.split(b'=',...
python
{ "resource": "" }
q30799
ZK.read_sizes
train
def read_sizes(self): """ read the memory ussage """ command = const.CMD_GET_FREE_SIZES response_size = 1024 cmd_response = self.__send_command(command,b'', response_size) if cmd_response.get('status'): if self.verbose: print(codecs.encode(self.__data,...
python
{ "resource": "" }