repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
learningequality/iceqube | src/iceqube/worker/backends/base.py | BaseWorkerBackend.start_message_processing | def start_message_processing(self):
"""
Starts up the message processor thread, that continuously reads
messages sent to self.incoming_message_mailbox, and starts or cancels jobs based on the message received.
Returns: the Thread object.
"""
t = InfiniteLoopThread(self.p... | python | def start_message_processing(self):
"""
Starts up the message processor thread, that continuously reads
messages sent to self.incoming_message_mailbox, and starts or cancels jobs based on the message received.
Returns: the Thread object.
"""
t = InfiniteLoopThread(self.p... | [
"def",
"start_message_processing",
"(",
"self",
")",
":",
"t",
"=",
"InfiniteLoopThread",
"(",
"self",
".",
"process_messages",
",",
"thread_name",
"=",
"\"MESSAGEPROCESSOR\"",
",",
"wait_between_runs",
"=",
"0.5",
")",
"t",
".",
"start",
"(",
")",
"return",
"... | Starts up the message processor thread, that continuously reads
messages sent to self.incoming_message_mailbox, and starts or cancels jobs based on the message received.
Returns: the Thread object. | [
"Starts",
"up",
"the",
"message",
"processor",
"thread",
"that",
"continuously",
"reads",
"messages",
"sent",
"to",
"self",
".",
"incoming_message_mailbox",
"and",
"starts",
"or",
"cancels",
"jobs",
"based",
"on",
"the",
"message",
"received",
".",
"Returns",
":... | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/worker/backends/base.py#L47-L56 |
learningequality/iceqube | src/iceqube/worker/backends/base.py | BaseWorkerBackend.process_messages | def process_messages(self):
"""
Read from the incoming_message_mailbox and report to the storage backend
based on the first message found there.
Returns: None
"""
try:
msg = self.msgbackend.pop(self.incoming_message_mailbox)
self.handle_incoming_me... | python | def process_messages(self):
"""
Read from the incoming_message_mailbox and report to the storage backend
based on the first message found there.
Returns: None
"""
try:
msg = self.msgbackend.pop(self.incoming_message_mailbox)
self.handle_incoming_me... | [
"def",
"process_messages",
"(",
"self",
")",
":",
"try",
":",
"msg",
"=",
"self",
".",
"msgbackend",
".",
"pop",
"(",
"self",
".",
"incoming_message_mailbox",
")",
"self",
".",
"handle_incoming_message",
"(",
"msg",
")",
"except",
"queue",
".",
"Empty",
":... | Read from the incoming_message_mailbox and report to the storage backend
based on the first message found there.
Returns: None | [
"Read",
"from",
"the",
"incoming_message_mailbox",
"and",
"report",
"to",
"the",
"storage",
"backend",
"based",
"on",
"the",
"first",
"message",
"found",
"there",
".",
"Returns",
":",
"None"
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/worker/backends/base.py#L58-L68 |
learningequality/iceqube | src/iceqube/worker/backends/base.py | BaseWorkerBackend.handle_incoming_message | def handle_incoming_message(self, msg):
"""
Start or cancel a job, based on the msg.
If msg.type == MessageType.START_JOB, then start the job given by msg.job.
If msg.type == MessageType.CANCEL_JOB, then try to cancel the job given by msg.job.job_id.
Args:
msg (bar... | python | def handle_incoming_message(self, msg):
"""
Start or cancel a job, based on the msg.
If msg.type == MessageType.START_JOB, then start the job given by msg.job.
If msg.type == MessageType.CANCEL_JOB, then try to cancel the job given by msg.job.job_id.
Args:
msg (bar... | [
"def",
"handle_incoming_message",
"(",
"self",
",",
"msg",
")",
":",
"if",
"msg",
".",
"type",
"==",
"MessageType",
".",
"START_JOB",
":",
"job",
"=",
"msg",
".",
"message",
"[",
"'job'",
"]",
"self",
".",
"schedule_job",
"(",
"job",
")",
"elif",
"msg"... | Start or cancel a job, based on the msg.
If msg.type == MessageType.START_JOB, then start the job given by msg.job.
If msg.type == MessageType.CANCEL_JOB, then try to cancel the job given by msg.job.job_id.
Args:
msg (barbequeue.messaging.classes.Message):
Returns: None | [
"Start",
"or",
"cancel",
"a",
"job",
"based",
"on",
"the",
"msg",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/worker/backends/base.py#L70-L89 |
learningequality/iceqube | src/iceqube/worker/backends/inmem.py | _reraise_with_traceback | def _reraise_with_traceback(f):
"""
Call the function normally. But if the function raises an error, attach the str(traceback)
into the function.traceback attribute, then reraise the error.
Args:
f: The function to run.
Returns: A function that wraps f, attaching the traceback if an error o... | python | def _reraise_with_traceback(f):
"""
Call the function normally. But if the function raises an error, attach the str(traceback)
into the function.traceback attribute, then reraise the error.
Args:
f: The function to run.
Returns: A function that wraps f, attaching the traceback if an error o... | [
"def",
"_reraise_with_traceback",
"(",
"f",
")",
":",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"traceback_s... | Call the function normally. But if the function raises an error, attach the str(traceback)
into the function.traceback attribute, then reraise the error.
Args:
f: The function to run.
Returns: A function that wraps f, attaching the traceback if an error occurred. | [
"Call",
"the",
"function",
"normally",
".",
"But",
"if",
"the",
"function",
"raises",
"an",
"error",
"attach",
"the",
"str",
"(",
"traceback",
")",
"into",
"the",
"function",
".",
"traceback",
"attribute",
"then",
"reraise",
"the",
"error",
".",
"Args",
":... | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/worker/backends/inmem.py#L132-L151 |
learningequality/iceqube | src/iceqube/worker/backends/inmem.py | WorkerBackend.schedule_job | def schedule_job(self, job):
"""
schedule a job to the type of workers spawned by self.start_workers.
:param job: the job to schedule for running.
:return:
"""
l = _reraise_with_traceback(job.get_lambda_to_execute())
future = self.workers.submit(l, update_progr... | python | def schedule_job(self, job):
"""
schedule a job to the type of workers spawned by self.start_workers.
:param job: the job to schedule for running.
:return:
"""
l = _reraise_with_traceback(job.get_lambda_to_execute())
future = self.workers.submit(l, update_progr... | [
"def",
"schedule_job",
"(",
"self",
",",
"job",
")",
":",
"l",
"=",
"_reraise_with_traceback",
"(",
"job",
".",
"get_lambda_to_execute",
"(",
")",
")",
"future",
"=",
"self",
".",
"workers",
".",
"submit",
"(",
"l",
",",
"update_progress_func",
"=",
"self"... | schedule a job to the type of workers spawned by self.start_workers.
:param job: the job to schedule for running.
:return: | [
"schedule",
"a",
"job",
"to",
"the",
"type",
"of",
"workers",
"spawned",
"by",
"self",
".",
"start_workers",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/worker/backends/inmem.py#L29-L50 |
learningequality/iceqube | src/iceqube/worker/backends/inmem.py | WorkerBackend.cancel | def cancel(self, job_id):
"""
Request a cancellation from the futures executor pool.
If that didn't work (because it's already running), then mark
a special variable inside the future that we can check
inside a special check_for_cancel function passed to the
job.
... | python | def cancel(self, job_id):
"""
Request a cancellation from the futures executor pool.
If that didn't work (because it's already running), then mark
a special variable inside the future that we can check
inside a special check_for_cancel function passed to the
job.
... | [
"def",
"cancel",
"(",
"self",
",",
"job_id",
")",
":",
"future",
"=",
"self",
".",
"future_job_mapping",
"[",
"job_id",
"]",
"is_future_cancelled",
"=",
"future",
".",
"cancel",
"(",
")",
"if",
"is_future_cancelled",
":",
"# success!",
"return",
"True",
"els... | Request a cancellation from the futures executor pool.
If that didn't work (because it's already running), then mark
a special variable inside the future that we can check
inside a special check_for_cancel function passed to the
job.
:param job_id:
:return: | [
"Request",
"a",
"cancellation",
"from",
"the",
"futures",
"executor",
"pool",
".",
"If",
"that",
"didn",
"t",
"work",
"(",
"because",
"it",
"s",
"already",
"running",
")",
"then",
"mark",
"a",
"special",
"variable",
"inside",
"the",
"future",
"that",
"we",... | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/worker/backends/inmem.py#L86-L111 |
learningequality/iceqube | src/iceqube/worker/backends/inmem.py | WorkerBackend._check_for_cancel | def _check_for_cancel(self, job_id, current_stage=""):
"""
Check if a job has been requested to be cancelled. When called, the calling function can
optionally give the stage it is currently in, so the user has information on where the job
was before it was cancelled.
:param job_... | python | def _check_for_cancel(self, job_id, current_stage=""):
"""
Check if a job has been requested to be cancelled. When called, the calling function can
optionally give the stage it is currently in, so the user has information on where the job
was before it was cancelled.
:param job_... | [
"def",
"_check_for_cancel",
"(",
"self",
",",
"job_id",
",",
"current_stage",
"=",
"\"\"",
")",
":",
"future",
"=",
"self",
".",
"future_job_mapping",
"[",
"job_id",
"]",
"is_cancelled",
"=",
"future",
".",
"_state",
"in",
"[",
"CANCELLED",
",",
"CANCELLED_A... | Check if a job has been requested to be cancelled. When called, the calling function can
optionally give the stage it is currently in, so the user has information on where the job
was before it was cancelled.
:param job_id: The job_id to check
:param current_stage: Where the job current... | [
"Check",
"if",
"a",
"job",
"has",
"been",
"requested",
"to",
"be",
"cancelled",
".",
"When",
"called",
"the",
"calling",
"function",
"can",
"optionally",
"give",
"the",
"stage",
"it",
"is",
"currently",
"in",
"so",
"the",
"user",
"has",
"information",
"on"... | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/worker/backends/inmem.py#L113-L129 |
learningequality/iceqube | src/iceqube/scheduler/classes.py | Scheduler.start_scheduler | def start_scheduler(self):
"""
Start the scheduler thread. This thread reads the queue of jobs to be
scheduled and sends them to the workers.
Returns: None
"""
t = InfiniteLoopThread(
func=self.schedule_next_job,
thread_name="SCHEDULER",
... | python | def start_scheduler(self):
"""
Start the scheduler thread. This thread reads the queue of jobs to be
scheduled and sends them to the workers.
Returns: None
"""
t = InfiniteLoopThread(
func=self.schedule_next_job,
thread_name="SCHEDULER",
... | [
"def",
"start_scheduler",
"(",
"self",
")",
":",
"t",
"=",
"InfiniteLoopThread",
"(",
"func",
"=",
"self",
".",
"schedule_next_job",
",",
"thread_name",
"=",
"\"SCHEDULER\"",
",",
"wait_between_runs",
"=",
"0.5",
")",
"t",
".",
"start",
"(",
")",
"return",
... | Start the scheduler thread. This thread reads the queue of jobs to be
scheduled and sends them to the workers.
Returns: None | [
"Start",
"the",
"scheduler",
"thread",
".",
"This",
"thread",
"reads",
"the",
"queue",
"of",
"jobs",
"to",
"be",
"scheduled",
"and",
"sends",
"them",
"to",
"the",
"workers",
".",
"Returns",
":",
"None"
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/scheduler/classes.py#L25-L37 |
learningequality/iceqube | src/iceqube/scheduler/classes.py | Scheduler.start_worker_message_handler | def start_worker_message_handler(self):
"""
Start the worker message handler thread, that loops over messages from workers
(job progress updates, failures and successes etc.) and then updates the job's status.
Returns: None
"""
t = InfiniteLoopThread(
func=la... | python | def start_worker_message_handler(self):
"""
Start the worker message handler thread, that loops over messages from workers
(job progress updates, failures and successes etc.) and then updates the job's status.
Returns: None
"""
t = InfiniteLoopThread(
func=la... | [
"def",
"start_worker_message_handler",
"(",
"self",
")",
":",
"t",
"=",
"InfiniteLoopThread",
"(",
"func",
"=",
"lambda",
":",
"self",
".",
"handle_worker_messages",
"(",
"timeout",
"=",
"2",
")",
",",
"thread_name",
"=",
"\"WORKERMESSAGEHANDLER\"",
",",
"wait_b... | Start the worker message handler thread, that loops over messages from workers
(job progress updates, failures and successes etc.) and then updates the job's status.
Returns: None | [
"Start",
"the",
"worker",
"message",
"handler",
"thread",
"that",
"loops",
"over",
"messages",
"from",
"workers",
"(",
"job",
"progress",
"updates",
"failures",
"and",
"successes",
"etc",
".",
")",
"and",
"then",
"updates",
"the",
"job",
"s",
"status",
".",
... | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/scheduler/classes.py#L39-L51 |
learningequality/iceqube | src/iceqube/scheduler/classes.py | Scheduler.shutdown | def shutdown(self, wait=True):
"""
Shut down the worker message handler and scheduler threads.
Args:
wait: If true, block until both threads have successfully shut down. If False, return immediately.
Returns: None
"""
self.scheduler_thread.stop()
sel... | python | def shutdown(self, wait=True):
"""
Shut down the worker message handler and scheduler threads.
Args:
wait: If true, block until both threads have successfully shut down. If False, return immediately.
Returns: None
"""
self.scheduler_thread.stop()
sel... | [
"def",
"shutdown",
"(",
"self",
",",
"wait",
"=",
"True",
")",
":",
"self",
".",
"scheduler_thread",
".",
"stop",
"(",
")",
"self",
".",
"worker_message_handler_thread",
".",
"stop",
"(",
")",
"if",
"wait",
":",
"self",
".",
"scheduler_thread",
".",
"joi... | Shut down the worker message handler and scheduler threads.
Args:
wait: If true, block until both threads have successfully shut down. If False, return immediately.
Returns: None | [
"Shut",
"down",
"the",
"worker",
"message",
"handler",
"and",
"scheduler",
"threads",
".",
"Args",
":",
"wait",
":",
"If",
"true",
"block",
"until",
"both",
"threads",
"have",
"successfully",
"shut",
"down",
".",
"If",
"False",
"return",
"immediately",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/scheduler/classes.py#L53-L67 |
learningequality/iceqube | src/iceqube/scheduler/classes.py | Scheduler.request_job_cancel | def request_job_cancel(self, job_id):
"""
Send a message to the workers to cancel the job with job_id. We then mark the job in the storage
as being canceled.
:param job_id: the job to cancel
:return: None
"""
msg = CancelMessage(job_id)
self.messaging_bac... | python | def request_job_cancel(self, job_id):
"""
Send a message to the workers to cancel the job with job_id. We then mark the job in the storage
as being canceled.
:param job_id: the job to cancel
:return: None
"""
msg = CancelMessage(job_id)
self.messaging_bac... | [
"def",
"request_job_cancel",
"(",
"self",
",",
"job_id",
")",
":",
"msg",
"=",
"CancelMessage",
"(",
"job_id",
")",
"self",
".",
"messaging_backend",
".",
"send",
"(",
"self",
".",
"worker_mailbox",
",",
"msg",
")",
"self",
".",
"storage_backend",
".",
"ma... | Send a message to the workers to cancel the job with job_id. We then mark the job in the storage
as being canceled.
:param job_id: the job to cancel
:return: None | [
"Send",
"a",
"message",
"to",
"the",
"workers",
"to",
"cancel",
"the",
"job",
"with",
"job_id",
".",
"We",
"then",
"mark",
"the",
"job",
"in",
"the",
"storage",
"as",
"being",
"canceled",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/scheduler/classes.py#L69-L79 |
learningequality/iceqube | src/iceqube/scheduler/classes.py | Scheduler.schedule_next_job | def schedule_next_job(self):
"""
Get the next job in the queue to be scheduled, and send a message
to the workers to start the job.
Returns: None
"""
next_job = self.storage_backend.get_next_scheduled_job()
# TODO: don't loop over if workers are already all runni... | python | def schedule_next_job(self):
"""
Get the next job in the queue to be scheduled, and send a message
to the workers to start the job.
Returns: None
"""
next_job = self.storage_backend.get_next_scheduled_job()
# TODO: don't loop over if workers are already all runni... | [
"def",
"schedule_next_job",
"(",
"self",
")",
":",
"next_job",
"=",
"self",
".",
"storage_backend",
".",
"get_next_scheduled_job",
"(",
")",
"# TODO: don't loop over if workers are already all running",
"if",
"not",
"next_job",
":",
"logging",
".",
"debug",
"(",
"\"No... | Get the next job in the queue to be scheduled, and send a message
to the workers to start the job.
Returns: None | [
"Get",
"the",
"next",
"job",
"in",
"the",
"queue",
"to",
"be",
"scheduled",
"and",
"send",
"a",
"message",
"to",
"the",
"workers",
"to",
"start",
"the",
"job",
".",
"Returns",
":",
"None"
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/scheduler/classes.py#L81-L105 |
learningequality/iceqube | src/iceqube/scheduler/classes.py | Scheduler.handle_worker_messages | def handle_worker_messages(self, timeout):
"""
Read messages that are placed in self.incoming_mailbox,
and then update the job states corresponding to each message.
Args:
timeout: How long to wait for an incoming message, if the mailbox is empty right now.
Returns: ... | python | def handle_worker_messages(self, timeout):
"""
Read messages that are placed in self.incoming_mailbox,
and then update the job states corresponding to each message.
Args:
timeout: How long to wait for an incoming message, if the mailbox is empty right now.
Returns: ... | [
"def",
"handle_worker_messages",
"(",
"self",
",",
"timeout",
")",
":",
"msgs",
"=",
"self",
".",
"messaging_backend",
".",
"popn",
"(",
"self",
".",
"incoming_mailbox",
",",
"n",
"=",
"20",
")",
"for",
"msg",
"in",
"msgs",
":",
"self",
".",
"handle_sing... | Read messages that are placed in self.incoming_mailbox,
and then update the job states corresponding to each message.
Args:
timeout: How long to wait for an incoming message, if the mailbox is empty right now.
Returns: None | [
"Read",
"messages",
"that",
"are",
"placed",
"in",
"self",
".",
"incoming_mailbox",
"and",
"then",
"update",
"the",
"job",
"states",
"corresponding",
"to",
"each",
"message",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/scheduler/classes.py#L107-L121 |
learningequality/iceqube | src/iceqube/scheduler/classes.py | Scheduler.handle_single_message | def handle_single_message(self, msg):
"""
Handle one message and modify the job storage appropriately.
:param msg: the message to handle
:return: None
"""
job_id = msg.message['job_id']
actual_msg = msg.message
if msg.type == MessageType.JOB_UPDATED:
... | python | def handle_single_message(self, msg):
"""
Handle one message and modify the job storage appropriately.
:param msg: the message to handle
:return: None
"""
job_id = msg.message['job_id']
actual_msg = msg.message
if msg.type == MessageType.JOB_UPDATED:
... | [
"def",
"handle_single_message",
"(",
"self",
",",
"msg",
")",
":",
"job_id",
"=",
"msg",
".",
"message",
"[",
"'job_id'",
"]",
"actual_msg",
"=",
"msg",
".",
"message",
"if",
"msg",
".",
"type",
"==",
"MessageType",
".",
"JOB_UPDATED",
":",
"progress",
"... | Handle one message and modify the job storage appropriately.
:param msg: the message to handle
:return: None | [
"Handle",
"one",
"message",
"and",
"modify",
"the",
"job",
"storage",
"appropriately",
".",
":",
"param",
"msg",
":",
"the",
"message",
"to",
"handle",
":",
"return",
":",
"None"
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/scheduler/classes.py#L123-L145 |
learningequality/iceqube | src/iceqube/common/classes.py | Job.get_lambda_to_execute | def get_lambda_to_execute(self):
"""
return a function that executes the function assigned to this job.
If job.track_progress is None (the default), the returned function accepts no argument
and simply needs to be called. If job.track_progress is True, an update_progress function
... | python | def get_lambda_to_execute(self):
"""
return a function that executes the function assigned to this job.
If job.track_progress is None (the default), the returned function accepts no argument
and simply needs to be called. If job.track_progress is True, an update_progress function
... | [
"def",
"get_lambda_to_execute",
"(",
"self",
")",
":",
"def",
"y",
"(",
"update_progress_func",
",",
"cancel_job_func",
")",
":",
"\"\"\"\n Call the function stored in self.func, and passing in update_progress_func\n or cancel_job_func depending if self.track_progre... | return a function that executes the function assigned to this job.
If job.track_progress is None (the default), the returned function accepts no argument
and simply needs to be called. If job.track_progress is True, an update_progress function
is passed in that can be used by the function to pr... | [
"return",
"a",
"function",
"that",
"executes",
"the",
"function",
"assigned",
"to",
"this",
"job",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/common/classes.py#L85-L122 |
learningequality/iceqube | src/iceqube/common/classes.py | Job.percentage_progress | def percentage_progress(self):
"""
Returns a float between 0 and 1, representing the current job's progress in its task.
If total_progress is not given or 0, just return self.progress.
:return: float corresponding to the total percentage progress of the job.
"""
if self... | python | def percentage_progress(self):
"""
Returns a float between 0 and 1, representing the current job's progress in its task.
If total_progress is not given or 0, just return self.progress.
:return: float corresponding to the total percentage progress of the job.
"""
if self... | [
"def",
"percentage_progress",
"(",
"self",
")",
":",
"if",
"self",
".",
"total_progress",
"!=",
"0",
":",
"return",
"float",
"(",
"self",
".",
"progress",
")",
"/",
"self",
".",
"total_progress",
"else",
":",
"return",
"self",
".",
"progress"
] | Returns a float between 0 and 1, representing the current job's progress in its task.
If total_progress is not given or 0, just return self.progress.
:return: float corresponding to the total percentage progress of the job. | [
"Returns",
"a",
"float",
"between",
"0",
"and",
"1",
"representing",
"the",
"current",
"job",
"s",
"progress",
"in",
"its",
"task",
".",
"If",
"total_progress",
"is",
"not",
"given",
"or",
"0",
"just",
"return",
"self",
".",
"progress",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/common/classes.py#L125-L136 |
learningequality/iceqube | src/iceqube/client.py | Client.schedule | def schedule(self, func, *args, **kwargs):
"""
Schedules a function func for execution.
One special parameter is track_progress. If passed in and not None, the func will be passed in a
keyword parameter called update_progress:
def update_progress(progress, total_progress, stage... | python | def schedule(self, func, *args, **kwargs):
"""
Schedules a function func for execution.
One special parameter is track_progress. If passed in and not None, the func will be passed in a
keyword parameter called update_progress:
def update_progress(progress, total_progress, stage... | [
"def",
"schedule",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# if the func is already a job object, just schedule that directly.",
"if",
"isinstance",
"(",
"func",
",",
"Job",
")",
":",
"job",
"=",
"func",
"# else, turn it i... | Schedules a function func for execution.
One special parameter is track_progress. If passed in and not None, the func will be passed in a
keyword parameter called update_progress:
def update_progress(progress, total_progress, stage=""):
The running function can call the update_progres... | [
"Schedules",
"a",
"function",
"func",
"for",
"execution",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/client.py#L15-L52 |
learningequality/iceqube | src/iceqube/client.py | Client.wait | def wait(self, job_id, timeout=None):
"""
Wait until the job given by job_id has a new update.
:param job_id: the id of the job to wait for.
:param timeout: how long to wait for a job state change before timing out.
:return: Job object corresponding to job_id
"""
... | python | def wait(self, job_id, timeout=None):
"""
Wait until the job given by job_id has a new update.
:param job_id: the id of the job to wait for.
:param timeout: how long to wait for a job state change before timing out.
:return: Job object corresponding to job_id
"""
... | [
"def",
"wait",
"(",
"self",
",",
"job_id",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"storage",
".",
"wait_for_job_update",
"(",
"job_id",
",",
"timeout",
"=",
"timeout",
")"
] | Wait until the job given by job_id has a new update.
:param job_id: the id of the job to wait for.
:param timeout: how long to wait for a job state change before timing out.
:return: Job object corresponding to job_id | [
"Wait",
"until",
"the",
"job",
"given",
"by",
"job_id",
"has",
"a",
"new",
"update",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/client.py#L86-L94 |
learningequality/iceqube | src/iceqube/client.py | Client.wait_for_completion | def wait_for_completion(self, job_id, timeout=None):
"""
Wait for the job given by job_id to change to COMPLETED or CANCELED. Raises a
iceqube.exceptions.TimeoutError if timeout is exceeded before each job change.
:param job_id: the id of the job to wait for.
:param timeout: how... | python | def wait_for_completion(self, job_id, timeout=None):
"""
Wait for the job given by job_id to change to COMPLETED or CANCELED. Raises a
iceqube.exceptions.TimeoutError if timeout is exceeded before each job change.
:param job_id: the id of the job to wait for.
:param timeout: how... | [
"def",
"wait_for_completion",
"(",
"self",
",",
"job_id",
",",
"timeout",
"=",
"None",
")",
":",
"while",
"1",
":",
"job",
"=",
"self",
".",
"wait",
"(",
"job_id",
",",
"timeout",
"=",
"timeout",
")",
"if",
"job",
".",
"state",
"in",
"[",
"State",
... | Wait for the job given by job_id to change to COMPLETED or CANCELED. Raises a
iceqube.exceptions.TimeoutError if timeout is exceeded before each job change.
:param job_id: the id of the job to wait for.
:param timeout: how long to wait for a job state change before timing out. | [
"Wait",
"for",
"the",
"job",
"given",
"by",
"job_id",
"to",
"change",
"to",
"COMPLETED",
"or",
"CANCELED",
".",
"Raises",
"a",
"iceqube",
".",
"exceptions",
".",
"TimeoutError",
"if",
"timeout",
"is",
"exceeded",
"before",
"each",
"job",
"change",
"."
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/client.py#L96-L109 |
learningequality/iceqube | src/iceqube/client.py | SimpleClient.shutdown | def shutdown(self):
"""
Shutdown the client and all of its managed resources:
- the workers
- the scheduler threads
:return: None
"""
self._storage.clear()
self._scheduler.shutdown(wait=False)
self._workers.shutdown(wait=False) | python | def shutdown(self):
"""
Shutdown the client and all of its managed resources:
- the workers
- the scheduler threads
:return: None
"""
self._storage.clear()
self._scheduler.shutdown(wait=False)
self._workers.shutdown(wait=False) | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"_storage",
".",
"clear",
"(",
")",
"self",
".",
"_scheduler",
".",
"shutdown",
"(",
"wait",
"=",
"False",
")",
"self",
".",
"_workers",
".",
"shutdown",
"(",
"wait",
"=",
"False",
")"
] | Shutdown the client and all of its managed resources:
- the workers
- the scheduler threads
:return: None | [
"Shutdown",
"the",
"client",
"and",
"all",
"of",
"its",
"managed",
"resources",
":"
] | train | https://github.com/learningequality/iceqube/blob/97ac9e0f65bfedb0efa9f94638bcb57c7926dea2/src/iceqube/client.py#L151-L162 |
gusdan/django-elasticache | django_elasticache/cluster_utils.py | get_cluster_info | def get_cluster_info(host, port, ignore_cluster_errors=False):
"""
return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
}
"""
client = Telnet(host, int(port))
client.write(b'v... | python | def get_cluster_info(host, port, ignore_cluster_errors=False):
"""
return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
}
"""
client = Telnet(host, int(port))
client.write(b'v... | [
"def",
"get_cluster_info",
"(",
"host",
",",
"port",
",",
"ignore_cluster_errors",
"=",
"False",
")",
":",
"client",
"=",
"Telnet",
"(",
"host",
",",
"int",
"(",
"port",
")",
")",
"client",
".",
"write",
"(",
"b'version\\n'",
")",
"res",
"=",
"client",
... | return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
} | [
"return",
"dict",
"with",
"info",
"about",
"nodes",
"in",
"cluster",
"and",
"current",
"version",
"{",
"nodes",
":",
"[",
"IP",
":",
"port",
"IP",
":",
"port",
"]",
"version",
":",
"1",
".",
"4",
".",
"4",
"}"
] | train | https://github.com/gusdan/django-elasticache/blob/5f93c06ca8f264e3bd85b5f7044fd07733282e42/django_elasticache/cluster_utils.py#L20-L77 |
gusdan/django-elasticache | django_elasticache/memcached.py | invalidate_cache_after_error | def invalidate_cache_after_error(f):
"""
catch any exception and invalidate internal cache with list of nodes
"""
@wraps(f)
def wrapper(self, *args, **kwds):
try:
return f(self, *args, **kwds)
except Exception:
self.clear_cluster_nodes_cache()
rais... | python | def invalidate_cache_after_error(f):
"""
catch any exception and invalidate internal cache with list of nodes
"""
@wraps(f)
def wrapper(self, *args, **kwds):
try:
return f(self, *args, **kwds)
except Exception:
self.clear_cluster_nodes_cache()
rais... | [
"def",
"invalidate_cache_after_error",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"... | catch any exception and invalidate internal cache with list of nodes | [
"catch",
"any",
"exception",
"and",
"invalidate",
"internal",
"cache",
"with",
"list",
"of",
"nodes"
] | train | https://github.com/gusdan/django-elasticache/blob/5f93c06ca8f264e3bd85b5f7044fd07733282e42/django_elasticache/memcached.py#L11-L22 |
gusdan/django-elasticache | django_elasticache/memcached.py | ElastiCache.update_params | def update_params(self, params):
"""
update connection params to maximize performance
"""
if not params.get('BINARY', True):
raise Warning('To increase performance please use ElastiCache'
' in binary mode')
else:
params['BINARY'] ... | python | def update_params(self, params):
"""
update connection params to maximize performance
"""
if not params.get('BINARY', True):
raise Warning('To increase performance please use ElastiCache'
' in binary mode')
else:
params['BINARY'] ... | [
"def",
"update_params",
"(",
"self",
",",
"params",
")",
":",
"if",
"not",
"params",
".",
"get",
"(",
"'BINARY'",
",",
"True",
")",
":",
"raise",
"Warning",
"(",
"'To increase performance please use ElastiCache'",
"' in binary mode'",
")",
"else",
":",
"params",... | update connection params to maximize performance | [
"update",
"connection",
"params",
"to",
"maximize",
"performance"
] | train | https://github.com/gusdan/django-elasticache/blob/5f93c06ca8f264e3bd85b5f7044fd07733282e42/django_elasticache/memcached.py#L44-L58 |
gusdan/django-elasticache | django_elasticache/memcached.py | ElastiCache.get_cluster_nodes | def get_cluster_nodes(self):
"""
return list with all nodes in cluster
"""
if not hasattr(self, '_cluster_nodes_cache'):
server, port = self._servers[0].split(':')
try:
self._cluster_nodes_cache = (
get_cluster_info(server, port... | python | def get_cluster_nodes(self):
"""
return list with all nodes in cluster
"""
if not hasattr(self, '_cluster_nodes_cache'):
server, port = self._servers[0].split(':')
try:
self._cluster_nodes_cache = (
get_cluster_info(server, port... | [
"def",
"get_cluster_nodes",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_cluster_nodes_cache'",
")",
":",
"server",
",",
"port",
"=",
"self",
".",
"_servers",
"[",
"0",
"]",
".",
"split",
"(",
"':'",
")",
"try",
":",
"self",
".... | return list with all nodes in cluster | [
"return",
"list",
"with",
"all",
"nodes",
"in",
"cluster"
] | train | https://github.com/gusdan/django-elasticache/blob/5f93c06ca8f264e3bd85b5f7044fd07733282e42/django_elasticache/memcached.py#L65-L79 |
ankitpopli1891/django-autotranslate | autotranslate/management/commands/translate_messages.py | humanize_placeholders | def humanize_placeholders(msgid):
"""Convert placeholders to the (google translate) service friendly form.
%(name)s -> __name__
%s -> __item__
%d -> __number__
"""
return re.sub(
r'%(?:\((\w+)\))?([sd])',
lambda match: r'__{0}__'.format(
match.group(1).lo... | python | def humanize_placeholders(msgid):
"""Convert placeholders to the (google translate) service friendly form.
%(name)s -> __name__
%s -> __item__
%d -> __number__
"""
return re.sub(
r'%(?:\((\w+)\))?([sd])',
lambda match: r'__{0}__'.format(
match.group(1).lo... | [
"def",
"humanize_placeholders",
"(",
"msgid",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'%(?:\\((\\w+)\\))?([sd])'",
",",
"lambda",
"match",
":",
"r'__{0}__'",
".",
"format",
"(",
"match",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
"if",
"ma... | Convert placeholders to the (google translate) service friendly form.
%(name)s -> __name__
%s -> __item__
%d -> __number__ | [
"Convert",
"placeholders",
"to",
"the",
"(",
"google",
"translate",
")",
"service",
"friendly",
"form",
"."
] | train | https://github.com/ankitpopli1891/django-autotranslate/blob/ffdf120fa023b3e399cd37bc23e661a7be7b1718/autotranslate/management/commands/translate_messages.py#L157-L168 |
ankitpopli1891/django-autotranslate | autotranslate/management/commands/translate_messages.py | restore_placeholders | def restore_placeholders(msgid, translation):
"""Restore placeholders in the translated message."""
placehoders = re.findall(r'(\s*)(%(?:\(\w+\))?[sd])(\s*)', msgid)
return re.sub(
r'(\s*)(__[\w]+?__)(\s*)',
lambda matches: '{0}{1}{2}'.format(placehoders[0][0], placehoders[0][1], placehoders... | python | def restore_placeholders(msgid, translation):
"""Restore placeholders in the translated message."""
placehoders = re.findall(r'(\s*)(%(?:\(\w+\))?[sd])(\s*)', msgid)
return re.sub(
r'(\s*)(__[\w]+?__)(\s*)',
lambda matches: '{0}{1}{2}'.format(placehoders[0][0], placehoders[0][1], placehoders... | [
"def",
"restore_placeholders",
"(",
"msgid",
",",
"translation",
")",
":",
"placehoders",
"=",
"re",
".",
"findall",
"(",
"r'(\\s*)(%(?:\\(\\w+\\))?[sd])(\\s*)'",
",",
"msgid",
")",
"return",
"re",
".",
"sub",
"(",
"r'(\\s*)(__[\\w]+?__)(\\s*)'",
",",
"lambda",
"m... | Restore placeholders in the translated message. | [
"Restore",
"placeholders",
"in",
"the",
"translated",
"message",
"."
] | train | https://github.com/ankitpopli1891/django-autotranslate/blob/ffdf120fa023b3e399cd37bc23e661a7be7b1718/autotranslate/management/commands/translate_messages.py#L171-L177 |
ankitpopli1891/django-autotranslate | autotranslate/management/commands/translate_messages.py | Command.translate_file | def translate_file(self, root, file_name, target_language):
"""
convenience method for translating a pot file
:param root: the absolute path of folder where the file is present
:param file_name: name of the file to be translated (it should be a pot file)
:param ... | python | def translate_file(self, root, file_name, target_language):
"""
convenience method for translating a pot file
:param root: the absolute path of folder where the file is present
:param file_name: name of the file to be translated (it should be a pot file)
:param ... | [
"def",
"translate_file",
"(",
"self",
",",
"root",
",",
"file_name",
",",
"target_language",
")",
":",
"logger",
".",
"info",
"(",
"'filling up translations for locale `{}`'",
".",
"format",
"(",
"target_language",
")",
")",
"po",
"=",
"polib",
".",
"pofile",
... | convenience method for translating a pot file
:param root: the absolute path of folder where the file is present
:param file_name: name of the file to be translated (it should be a pot file)
:param target_language: language in which the file needs to be translated | [
"convenience",
"method",
"for",
"translating",
"a",
"pot",
"file"
] | train | https://github.com/ankitpopli1891/django-autotranslate/blob/ffdf120fa023b3e399cd37bc23e661a7be7b1718/autotranslate/management/commands/translate_messages.py#L78-L98 |
ankitpopli1891/django-autotranslate | autotranslate/management/commands/translate_messages.py | Command.get_strings_to_translate | def get_strings_to_translate(self, po):
"""Return list of string to translate from po file.
:param po: POFile object to translate
:type po: polib.POFile
:return: list of string to translate
:rtype: collections.Iterable[six.text_type]
"""
strings = []
for ... | python | def get_strings_to_translate(self, po):
"""Return list of string to translate from po file.
:param po: POFile object to translate
:type po: polib.POFile
:return: list of string to translate
:rtype: collections.Iterable[six.text_type]
"""
strings = []
for ... | [
"def",
"get_strings_to_translate",
"(",
"self",
",",
"po",
")",
":",
"strings",
"=",
"[",
"]",
"for",
"index",
",",
"entry",
"in",
"enumerate",
"(",
"po",
")",
":",
"if",
"not",
"self",
".",
"need_translate",
"(",
"entry",
")",
":",
"continue",
"string... | Return list of string to translate from po file.
:param po: POFile object to translate
:type po: polib.POFile
:return: list of string to translate
:rtype: collections.Iterable[six.text_type] | [
"Return",
"list",
"of",
"string",
"to",
"translate",
"from",
"po",
"file",
"."
] | train | https://github.com/ankitpopli1891/django-autotranslate/blob/ffdf120fa023b3e399cd37bc23e661a7be7b1718/autotranslate/management/commands/translate_messages.py#L103-L118 |
ankitpopli1891/django-autotranslate | autotranslate/management/commands/translate_messages.py | Command.update_translations | def update_translations(self, entries, translated_strings):
"""Update translations in entries.
The order and number of translations should match to get_strings_to_translate() result.
:param entries: list of entries to translate
:type entries: collections.Iterable[polib.POEntry] | polib... | python | def update_translations(self, entries, translated_strings):
"""Update translations in entries.
The order and number of translations should match to get_strings_to_translate() result.
:param entries: list of entries to translate
:type entries: collections.Iterable[polib.POEntry] | polib... | [
"def",
"update_translations",
"(",
"self",
",",
"entries",
",",
"translated_strings",
")",
":",
"translations",
"=",
"iter",
"(",
"translated_strings",
")",
"for",
"entry",
"in",
"entries",
":",
"if",
"not",
"self",
".",
"need_translate",
"(",
"entry",
")",
... | Update translations in entries.
The order and number of translations should match to get_strings_to_translate() result.
:param entries: list of entries to translate
:type entries: collections.Iterable[polib.POEntry] | polib.POFile
:param translated_strings: list of translations
... | [
"Update",
"translations",
"in",
"entries",
"."
] | train | https://github.com/ankitpopli1891/django-autotranslate/blob/ffdf120fa023b3e399cd37bc23e661a7be7b1718/autotranslate/management/commands/translate_messages.py#L120-L154 |
julienr/meshcut | examples/ply.py | load_ply | def load_ply(fileobj):
"""Same as load_ply, but takes a file-like object"""
def nextline():
"""Read next line, skip comments"""
while True:
line = fileobj.readline()
assert line != '' # eof
if not line.startswith('comment'):
return line.strip(... | python | def load_ply(fileobj):
"""Same as load_ply, but takes a file-like object"""
def nextline():
"""Read next line, skip comments"""
while True:
line = fileobj.readline()
assert line != '' # eof
if not line.startswith('comment'):
return line.strip(... | [
"def",
"load_ply",
"(",
"fileobj",
")",
":",
"def",
"nextline",
"(",
")",
":",
"\"\"\"Read next line, skip comments\"\"\"",
"while",
"True",
":",
"line",
"=",
"fileobj",
".",
"readline",
"(",
")",
"assert",
"line",
"!=",
"''",
"# eof",
"if",
"not",
"line",
... | Same as load_ply, but takes a file-like object | [
"Same",
"as",
"load_ply",
"but",
"takes",
"a",
"file",
"-",
"like",
"object"
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/examples/ply.py#L4-L57 |
sorend/sshconf | sshconf.py | read_ssh_config | def read_ssh_config(path):
"""
Read ssh config file and return parsed SshConfig
"""
with open(path, "r") as fh_:
lines = fh_.read().splitlines()
return SshConfig(lines) | python | def read_ssh_config(path):
"""
Read ssh config file and return parsed SshConfig
"""
with open(path, "r") as fh_:
lines = fh_.read().splitlines()
return SshConfig(lines) | [
"def",
"read_ssh_config",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"r\"",
")",
"as",
"fh_",
":",
"lines",
"=",
"fh_",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"return",
"SshConfig",
"(",
"lines",
")"
] | Read ssh config file and return parsed SshConfig | [
"Read",
"ssh",
"config",
"file",
"and",
"return",
"parsed",
"SshConfig"
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L112-L118 |
sorend/sshconf | sshconf.py | _remap_key | def _remap_key(key):
""" Change key into correct casing if we know the parameter """
if key in KNOWN_PARAMS:
return key
if key.lower() in known_params:
return KNOWN_PARAMS[known_params.index(key.lower())]
return key | python | def _remap_key(key):
""" Change key into correct casing if we know the parameter """
if key in KNOWN_PARAMS:
return key
if key.lower() in known_params:
return KNOWN_PARAMS[known_params.index(key.lower())]
return key | [
"def",
"_remap_key",
"(",
"key",
")",
":",
"if",
"key",
"in",
"KNOWN_PARAMS",
":",
"return",
"key",
"if",
"key",
".",
"lower",
"(",
")",
"in",
"known_params",
":",
"return",
"KNOWN_PARAMS",
"[",
"known_params",
".",
"index",
"(",
"key",
".",
"lower",
"... | Change key into correct casing if we know the parameter | [
"Change",
"key",
"into",
"correct",
"casing",
"if",
"we",
"know",
"the",
"parameter"
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L130-L136 |
sorend/sshconf | sshconf.py | SshConfig.parse | def parse(self, lines):
"""Parse lines from ssh config file"""
cur_entry = None
for line in lines:
kv_ = _key_value(line)
if len(kv_) > 1:
key, value = kv_
if key.lower() == "host":
cur_entry = value
... | python | def parse(self, lines):
"""Parse lines from ssh config file"""
cur_entry = None
for line in lines:
kv_ = _key_value(line)
if len(kv_) > 1:
key, value = kv_
if key.lower() == "host":
cur_entry = value
... | [
"def",
"parse",
"(",
"self",
",",
"lines",
")",
":",
"cur_entry",
"=",
"None",
"for",
"line",
"in",
"lines",
":",
"kv_",
"=",
"_key_value",
"(",
"line",
")",
"if",
"len",
"(",
"kv_",
")",
">",
"1",
":",
"key",
",",
"value",
"=",
"kv_",
"if",
"k... | Parse lines from ssh config file | [
"Parse",
"lines",
"from",
"ssh",
"config",
"file"
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L147-L159 |
sorend/sshconf | sshconf.py | SshConfig.host | def host(self, host):
"""
Return the configuration of a specific host as a dictionary.
Dictionary always contains lowercase versions of the attribute names.
Parameters
----------
host : the host to return values for.
Returns
-------
dict of key ... | python | def host(self, host):
"""
Return the configuration of a specific host as a dictionary.
Dictionary always contains lowercase versions of the attribute names.
Parameters
----------
host : the host to return values for.
Returns
-------
dict of key ... | [
"def",
"host",
"(",
"self",
",",
"host",
")",
":",
"if",
"host",
"in",
"self",
".",
"hosts_",
":",
"vals",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"k",
",",
"value",
"in",
"[",
"(",
"x",
".",
"key",
".",
"lower",
"(",
")",
",",
"x",
".",... | Return the configuration of a specific host as a dictionary.
Dictionary always contains lowercase versions of the attribute names.
Parameters
----------
host : the host to return values for.
Returns
-------
dict of key value pairs, excluding "Host", empty map i... | [
"Return",
"the",
"configuration",
"of",
"a",
"specific",
"host",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L171-L192 |
sorend/sshconf | sshconf.py | SshConfig.set | def set(self, host, **kwargs):
"""
Set configuration values for an existing host.
Overwrites values for existing settings, or adds new settings.
Parameters
----------
host : the Host to modify.
**kwargs : The new configuration parameters
"""
self.... | python | def set(self, host, **kwargs):
"""
Set configuration values for an existing host.
Overwrites values for existing settings, or adds new settings.
Parameters
----------
host : the Host to modify.
**kwargs : The new configuration parameters
"""
self.... | [
"def",
"set",
"(",
"self",
",",
"host",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__check_host_args",
"(",
"host",
",",
"kwargs",
")",
"def",
"update_line",
"(",
"key",
",",
"value",
")",
":",
"\"\"\"Produce new config line\"\"\"",
"return",
"\" %s... | Set configuration values for an existing host.
Overwrites values for existing settings, or adds new settings.
Parameters
----------
host : the Host to modify.
**kwargs : The new configuration parameters | [
"Set",
"configuration",
"values",
"for",
"an",
"existing",
"host",
".",
"Overwrites",
"values",
"for",
"existing",
"settings",
"or",
"adds",
"new",
"settings",
"."
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L194-L235 |
sorend/sshconf | sshconf.py | SshConfig.unset | def unset(self, host, *args):
"""
Removes settings for a host.
Parameters
----------
host : the host to remove settings from.
*args : list of settings to removes.
"""
self.__check_host_args(host, args)
remove_idx = [idx for idx, x in enumerate(sel... | python | def unset(self, host, *args):
"""
Removes settings for a host.
Parameters
----------
host : the host to remove settings from.
*args : list of settings to removes.
"""
self.__check_host_args(host, args)
remove_idx = [idx for idx, x in enumerate(sel... | [
"def",
"unset",
"(",
"self",
",",
"host",
",",
"*",
"args",
")",
":",
"self",
".",
"__check_host_args",
"(",
"host",
",",
"args",
")",
"remove_idx",
"=",
"[",
"idx",
"for",
"idx",
",",
"x",
"in",
"enumerate",
"(",
"self",
".",
"lines_",
")",
"if",
... | Removes settings for a host.
Parameters
----------
host : the host to remove settings from.
*args : list of settings to removes. | [
"Removes",
"settings",
"for",
"a",
"host",
"."
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L237-L250 |
sorend/sshconf | sshconf.py | SshConfig.__check_host_args | def __check_host_args(self, host, keys):
"""Checks parameters"""
if host not in self.hosts_:
raise ValueError("Host %s: not found" % host)
if "host" in [x.lower() for x in keys]:
raise ValueError("Cannot modify Host value") | python | def __check_host_args(self, host, keys):
"""Checks parameters"""
if host not in self.hosts_:
raise ValueError("Host %s: not found" % host)
if "host" in [x.lower() for x in keys]:
raise ValueError("Cannot modify Host value") | [
"def",
"__check_host_args",
"(",
"self",
",",
"host",
",",
"keys",
")",
":",
"if",
"host",
"not",
"in",
"self",
".",
"hosts_",
":",
"raise",
"ValueError",
"(",
"\"Host %s: not found\"",
"%",
"host",
")",
"if",
"\"host\"",
"in",
"[",
"x",
".",
"lower",
... | Checks parameters | [
"Checks",
"parameters"
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L252-L258 |
sorend/sshconf | sshconf.py | SshConfig.rename | def rename(self, old_host, new_host):
"""
Renames a host configuration.
Parameters
----------
old_host : the host to rename.
new_host : the new host value
"""
if new_host in self.hosts_:
raise ValueError("Host %s: already exists." % new_host)
... | python | def rename(self, old_host, new_host):
"""
Renames a host configuration.
Parameters
----------
old_host : the host to rename.
new_host : the new host value
"""
if new_host in self.hosts_:
raise ValueError("Host %s: already exists." % new_host)
... | [
"def",
"rename",
"(",
"self",
",",
"old_host",
",",
"new_host",
")",
":",
"if",
"new_host",
"in",
"self",
".",
"hosts_",
":",
"raise",
"ValueError",
"(",
"\"Host %s: already exists.\"",
"%",
"new_host",
")",
"for",
"line",
"in",
"self",
".",
"lines_",
":",... | Renames a host configuration.
Parameters
----------
old_host : the host to rename.
new_host : the new host value | [
"Renames",
"a",
"host",
"configuration",
"."
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L260-L278 |
sorend/sshconf | sshconf.py | SshConfig.add | def add(self, host, **kwargs):
"""
Add another host to the SSH configuration.
Parameters
----------
host: The Host entry to add.
**kwargs: The parameters for the host (without "Host" parameter itself)
"""
if host in self.hosts_:
raise ValueErr... | python | def add(self, host, **kwargs):
"""
Add another host to the SSH configuration.
Parameters
----------
host: The Host entry to add.
**kwargs: The parameters for the host (without "Host" parameter itself)
"""
if host in self.hosts_:
raise ValueErr... | [
"def",
"add",
"(",
"self",
",",
"host",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"host",
"in",
"self",
".",
"hosts_",
":",
"raise",
"ValueError",
"(",
"\"Host %s: exists (use update).\"",
"%",
"host",
")",
"self",
".",
"hosts_",
".",
"add",
"(",
"host"... | Add another host to the SSH configuration.
Parameters
----------
host: The Host entry to add.
**kwargs: The parameters for the host (without "Host" parameter itself) | [
"Add",
"another",
"host",
"to",
"the",
"SSH",
"configuration",
"."
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L280-L300 |
sorend/sshconf | sshconf.py | SshConfig.remove | def remove(self, host):
"""
Removes a host from the SSH configuration.
Parameters
----------
host : The host to remove
"""
if host not in self.hosts_:
raise ValueError("Host %s: not found." % host)
self.hosts_.remove(host)
# remove lin... | python | def remove(self, host):
"""
Removes a host from the SSH configuration.
Parameters
----------
host : The host to remove
"""
if host not in self.hosts_:
raise ValueError("Host %s: not found." % host)
self.hosts_.remove(host)
# remove lin... | [
"def",
"remove",
"(",
"self",
",",
"host",
")",
":",
"if",
"host",
"not",
"in",
"self",
".",
"hosts_",
":",
"raise",
"ValueError",
"(",
"\"Host %s: not found.\"",
"%",
"host",
")",
"self",
".",
"hosts_",
".",
"remove",
"(",
"host",
")",
"# remove lines, ... | Removes a host from the SSH configuration.
Parameters
----------
host : The host to remove | [
"Removes",
"a",
"host",
"from",
"the",
"SSH",
"configuration",
"."
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L302-L317 |
sorend/sshconf | sshconf.py | SshConfig.write | def write(self, path):
"""
Writes ssh config file
Parameters
----------
path : The file to write to
"""
with open(path, "w") as fh_:
fh_.write(self.config()) | python | def write(self, path):
"""
Writes ssh config file
Parameters
----------
path : The file to write to
"""
with open(path, "w") as fh_:
fh_.write(self.config()) | [
"def",
"write",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
"fh_",
":",
"fh_",
".",
"write",
"(",
"self",
".",
"config",
"(",
")",
")"
] | Writes ssh config file
Parameters
----------
path : The file to write to | [
"Writes",
"ssh",
"config",
"file"
] | train | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L325-L334 |
julienr/meshcut | examples/utils.py | orthogonal_vector | def orthogonal_vector(v):
"""Return an arbitrary vector that is orthogonal to v"""
if v[1] != 0 or v[2] != 0:
c = (1, 0, 0)
else:
c = (0, 1, 0)
return np.cross(v, c) | python | def orthogonal_vector(v):
"""Return an arbitrary vector that is orthogonal to v"""
if v[1] != 0 or v[2] != 0:
c = (1, 0, 0)
else:
c = (0, 1, 0)
return np.cross(v, c) | [
"def",
"orthogonal_vector",
"(",
"v",
")",
":",
"if",
"v",
"[",
"1",
"]",
"!=",
"0",
"or",
"v",
"[",
"2",
"]",
"!=",
"0",
":",
"c",
"=",
"(",
"1",
",",
"0",
",",
"0",
")",
"else",
":",
"c",
"=",
"(",
"0",
",",
"1",
",",
"0",
")",
"ret... | Return an arbitrary vector that is orthogonal to v | [
"Return",
"an",
"arbitrary",
"vector",
"that",
"is",
"orthogonal",
"to",
"v"
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/examples/utils.py#L18-L24 |
julienr/meshcut | examples/utils.py | show_plane | def show_plane(orig, n, scale=1.0, **kwargs):
"""
Show the plane with the given origin and normal. scale give its size
"""
b1 = orthogonal_vector(n)
b1 /= la.norm(b1)
b2 = np.cross(b1, n)
b2 /= la.norm(b2)
verts = [orig + scale*(-b1 - b2),
orig + scale*(b1 - b2),
... | python | def show_plane(orig, n, scale=1.0, **kwargs):
"""
Show the plane with the given origin and normal. scale give its size
"""
b1 = orthogonal_vector(n)
b1 /= la.norm(b1)
b2 = np.cross(b1, n)
b2 /= la.norm(b2)
verts = [orig + scale*(-b1 - b2),
orig + scale*(b1 - b2),
... | [
"def",
"show_plane",
"(",
"orig",
",",
"n",
",",
"scale",
"=",
"1.0",
",",
"*",
"*",
"kwargs",
")",
":",
"b1",
"=",
"orthogonal_vector",
"(",
"n",
")",
"b1",
"/=",
"la",
".",
"norm",
"(",
"b1",
")",
"b2",
"=",
"np",
".",
"cross",
"(",
"b1",
"... | Show the plane with the given origin and normal. scale give its size | [
"Show",
"the",
"plane",
"with",
"the",
"given",
"origin",
"and",
"normal",
".",
"scale",
"give",
"its",
"size"
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/examples/utils.py#L27-L40 |
julienr/meshcut | misc/experiments.py | slice_triangle_plane | def slice_triangle_plane(verts, tri, plane_orig, plane_norm):
"""
Args:
verts : the vertices of the mesh
tri: the face to cut
plane_orig: origin of the plane
plane_norm: normal to the plane
"""
dists = [point_to_plane_dist(p, plane_orig, plane_norm)
for p in ... | python | def slice_triangle_plane(verts, tri, plane_orig, plane_norm):
"""
Args:
verts : the vertices of the mesh
tri: the face to cut
plane_orig: origin of the plane
plane_norm: normal to the plane
"""
dists = [point_to_plane_dist(p, plane_orig, plane_norm)
for p in ... | [
"def",
"slice_triangle_plane",
"(",
"verts",
",",
"tri",
",",
"plane_orig",
",",
"plane_norm",
")",
":",
"dists",
"=",
"[",
"point_to_plane_dist",
"(",
"p",
",",
"plane_orig",
",",
"plane_norm",
")",
"for",
"p",
"in",
"verts",
"[",
"tri",
"]",
"]",
"if",... | Args:
verts : the vertices of the mesh
tri: the face to cut
plane_orig: origin of the plane
plane_norm: normal to the plane | [
"Args",
":",
"verts",
":",
"the",
"vertices",
"of",
"the",
"mesh",
"tri",
":",
"the",
"face",
"to",
"cut",
"plane_orig",
":",
"origin",
"of",
"the",
"plane",
"plane_norm",
":",
"normal",
"to",
"the",
"plane"
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/misc/experiments.py#L57-L92 |
julienr/meshcut | meshcut.py | triangle_intersects_plane | def triangle_intersects_plane(mesh, tid, plane):
"""
Returns true if the given triangle is cut by the plane. This will return
false if a single vertex of the triangle lies on the plane
"""
dists = [point_to_plane_dist(mesh.verts[vid], plane)
for vid in mesh.tris[tid]]
side = np.sign... | python | def triangle_intersects_plane(mesh, tid, plane):
"""
Returns true if the given triangle is cut by the plane. This will return
false if a single vertex of the triangle lies on the plane
"""
dists = [point_to_plane_dist(mesh.verts[vid], plane)
for vid in mesh.tris[tid]]
side = np.sign... | [
"def",
"triangle_intersects_plane",
"(",
"mesh",
",",
"tid",
",",
"plane",
")",
":",
"dists",
"=",
"[",
"point_to_plane_dist",
"(",
"mesh",
".",
"verts",
"[",
"vid",
"]",
",",
"plane",
")",
"for",
"vid",
"in",
"mesh",
".",
"tris",
"[",
"tid",
"]",
"]... | Returns true if the given triangle is cut by the plane. This will return
false if a single vertex of the triangle lies on the plane | [
"Returns",
"true",
"if",
"the",
"given",
"triangle",
"is",
"cut",
"by",
"the",
"plane",
".",
"This",
"will",
"return",
"false",
"if",
"a",
"single",
"vertex",
"of",
"the",
"triangle",
"lies",
"on",
"the",
"plane"
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/meshcut.py#L83-L91 |
julienr/meshcut | meshcut.py | compute_triangle_plane_intersections | def compute_triangle_plane_intersections(mesh, tid, plane, dist_tol=1e-8):
"""
Compute the intersection between a triangle and a plane
Returns a list of intersections in the form
(INTERSECT_EDGE, <intersection point>, <edge>) for edges intersection
(INTERSECT_VERTEX, <intersection point>, <... | python | def compute_triangle_plane_intersections(mesh, tid, plane, dist_tol=1e-8):
"""
Compute the intersection between a triangle and a plane
Returns a list of intersections in the form
(INTERSECT_EDGE, <intersection point>, <edge>) for edges intersection
(INTERSECT_VERTEX, <intersection point>, <... | [
"def",
"compute_triangle_plane_intersections",
"(",
"mesh",
",",
"tid",
",",
"plane",
",",
"dist_tol",
"=",
"1e-8",
")",
":",
"# TODO: Use a distance cache",
"dists",
"=",
"{",
"vid",
":",
"point_to_plane_dist",
"(",
"mesh",
".",
"verts",
"[",
"vid",
"]",
",",... | Compute the intersection between a triangle and a plane
Returns a list of intersections in the form
(INTERSECT_EDGE, <intersection point>, <edge>) for edges intersection
(INTERSECT_VERTEX, <intersection point>, <vertex index>) for vertices
This return between 0 and 2 intersections :
- 0 :... | [
"Compute",
"the",
"intersection",
"between",
"a",
"triangle",
"and",
"a",
"plane"
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/meshcut.py#L100-L161 |
julienr/meshcut | meshcut.py | get_next_triangle | def get_next_triangle(mesh, T, plane, intersection, dist_tol):
"""
Returns the next triangle to visit given the intersection and
the list of unvisited triangles (T)
We look for a triangle that is cut by the plane (2 intersections) as
opposed to one that only touch the plane (1 vertex intersection)
... | python | def get_next_triangle(mesh, T, plane, intersection, dist_tol):
"""
Returns the next triangle to visit given the intersection and
the list of unvisited triangles (T)
We look for a triangle that is cut by the plane (2 intersections) as
opposed to one that only touch the plane (1 vertex intersection)
... | [
"def",
"get_next_triangle",
"(",
"mesh",
",",
"T",
",",
"plane",
",",
"intersection",
",",
"dist_tol",
")",
":",
"if",
"intersection",
"[",
"0",
"]",
"==",
"INTERSECT_EDGE",
":",
"tris",
"=",
"mesh",
".",
"triangles_for_edge",
"(",
"intersection",
"[",
"2"... | Returns the next triangle to visit given the intersection and
the list of unvisited triangles (T)
We look for a triangle that is cut by the plane (2 intersections) as
opposed to one that only touch the plane (1 vertex intersection) | [
"Returns",
"the",
"next",
"triangle",
"to",
"visit",
"given",
"the",
"intersection",
"and",
"the",
"list",
"of",
"unvisited",
"triangles",
"(",
"T",
")"
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/meshcut.py#L164-L202 |
julienr/meshcut | meshcut.py | _walk_polyline | def _walk_polyline(tid, intersect, T, mesh, plane, dist_tol):
"""
Given an intersection, walk through the mesh triangles, computing
intersection with the cut plane for each visited triangle and adding
those intersection to a polyline.
"""
T = set(T)
p = []
# Loop until we have explored a... | python | def _walk_polyline(tid, intersect, T, mesh, plane, dist_tol):
"""
Given an intersection, walk through the mesh triangles, computing
intersection with the cut plane for each visited triangle and adding
those intersection to a polyline.
"""
T = set(T)
p = []
# Loop until we have explored a... | [
"def",
"_walk_polyline",
"(",
"tid",
",",
"intersect",
",",
"T",
",",
"mesh",
",",
"plane",
",",
"dist_tol",
")",
":",
"T",
"=",
"set",
"(",
"T",
")",
"p",
"=",
"[",
"]",
"# Loop until we have explored all the triangles for the current",
"# polyline",
"while",... | Given an intersection, walk through the mesh triangles, computing
intersection with the cut plane for each visited triangle and adding
those intersection to a polyline. | [
"Given",
"an",
"intersection",
"walk",
"through",
"the",
"mesh",
"triangles",
"computing",
"intersection",
"with",
"the",
"cut",
"plane",
"for",
"each",
"visited",
"triangle",
"and",
"adding",
"those",
"intersection",
"to",
"a",
"polyline",
"."
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/meshcut.py#L205-L237 |
julienr/meshcut | meshcut.py | cross_section_mesh | def cross_section_mesh(mesh, plane, dist_tol=1e-8):
"""
Args:
mesh: A geom.TriangleMesh instance
plane: The cut plane : geom.Plane instance
dist_tol: If two points are closer than dist_tol, they are considered
the same
"""
# Set of all triangles
T = set(rang... | python | def cross_section_mesh(mesh, plane, dist_tol=1e-8):
"""
Args:
mesh: A geom.TriangleMesh instance
plane: The cut plane : geom.Plane instance
dist_tol: If two points are closer than dist_tol, they are considered
the same
"""
# Set of all triangles
T = set(rang... | [
"def",
"cross_section_mesh",
"(",
"mesh",
",",
"plane",
",",
"dist_tol",
"=",
"1e-8",
")",
":",
"# Set of all triangles",
"T",
"=",
"set",
"(",
"range",
"(",
"len",
"(",
"mesh",
".",
"tris",
")",
")",
")",
"# List of all cross-section polylines",
"P",
"=",
... | Args:
mesh: A geom.TriangleMesh instance
plane: The cut plane : geom.Plane instance
dist_tol: If two points are closer than dist_tol, they are considered
the same | [
"Args",
":",
"mesh",
":",
"A",
"geom",
".",
"TriangleMesh",
"instance",
"plane",
":",
"The",
"cut",
"plane",
":",
"geom",
".",
"Plane",
"instance",
"dist_tol",
":",
"If",
"two",
"points",
"are",
"closer",
"than",
"dist_tol",
"they",
"are",
"considered",
... | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/meshcut.py#L240-L265 |
julienr/meshcut | meshcut.py | cross_section | def cross_section(verts, tris, plane_orig, plane_normal, **kwargs):
"""
Compute the planar cross section of a mesh. This returns a set of
polylines.
Args:
verts: Nx3 array of the vertices position
faces: Nx3 array of the faces, containing vertex indices
plane_orig: 3-vector indi... | python | def cross_section(verts, tris, plane_orig, plane_normal, **kwargs):
"""
Compute the planar cross section of a mesh. This returns a set of
polylines.
Args:
verts: Nx3 array of the vertices position
faces: Nx3 array of the faces, containing vertex indices
plane_orig: 3-vector indi... | [
"def",
"cross_section",
"(",
"verts",
",",
"tris",
",",
"plane_orig",
",",
"plane_normal",
",",
"*",
"*",
"kwargs",
")",
":",
"mesh",
"=",
"TriangleMesh",
"(",
"verts",
",",
"tris",
")",
"plane",
"=",
"Plane",
"(",
"plane_orig",
",",
"plane_normal",
")",... | Compute the planar cross section of a mesh. This returns a set of
polylines.
Args:
verts: Nx3 array of the vertices position
faces: Nx3 array of the faces, containing vertex indices
plane_orig: 3-vector indicating the plane origin
plane_normal: 3-vector indicating the plane norm... | [
"Compute",
"the",
"planar",
"cross",
"section",
"of",
"a",
"mesh",
".",
"This",
"returns",
"a",
"set",
"of",
"polylines",
"."
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/meshcut.py#L268-L285 |
julienr/meshcut | meshcut.py | pdist_squareformed_numpy | def pdist_squareformed_numpy(a):
"""
Compute spatial distance using pure numpy
(similar to scipy.spatial.distance.cdist())
Thanks to Divakar Roy (@droyed) at stackoverflow.com
Note this needs at least np.float64 precision!
Returns: dist
"""
a = np.array(a, dtype=np.float64)
a_sumr... | python | def pdist_squareformed_numpy(a):
"""
Compute spatial distance using pure numpy
(similar to scipy.spatial.distance.cdist())
Thanks to Divakar Roy (@droyed) at stackoverflow.com
Note this needs at least np.float64 precision!
Returns: dist
"""
a = np.array(a, dtype=np.float64)
a_sumr... | [
"def",
"pdist_squareformed_numpy",
"(",
"a",
")",
":",
"a",
"=",
"np",
".",
"array",
"(",
"a",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"a_sumrows",
"=",
"np",
".",
"einsum",
"(",
"'ij,ij->i'",
",",
"a",
",",
"a",
")",
"dist",
"=",
"a_sumrows"... | Compute spatial distance using pure numpy
(similar to scipy.spatial.distance.cdist())
Thanks to Divakar Roy (@droyed) at stackoverflow.com
Note this needs at least np.float64 precision!
Returns: dist | [
"Compute",
"spatial",
"distance",
"using",
"pure",
"numpy",
"(",
"similar",
"to",
"scipy",
".",
"spatial",
".",
"distance",
".",
"cdist",
"()",
")"
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/meshcut.py#L288-L303 |
julienr/meshcut | meshcut.py | merge_close_vertices | def merge_close_vertices(verts, faces, close_epsilon=1e-5):
"""
Will merge vertices that are closer than close_epsilon.
Warning, this has a O(n^2) memory usage because we compute the full
vert-to-vert distance matrix. If you have a large mesh, might want
to use some kind of spatial search structure... | python | def merge_close_vertices(verts, faces, close_epsilon=1e-5):
"""
Will merge vertices that are closer than close_epsilon.
Warning, this has a O(n^2) memory usage because we compute the full
vert-to-vert distance matrix. If you have a large mesh, might want
to use some kind of spatial search structure... | [
"def",
"merge_close_vertices",
"(",
"verts",
",",
"faces",
",",
"close_epsilon",
"=",
"1e-5",
")",
":",
"# Pairwise distance between verts",
"if",
"USE_SCIPY",
":",
"D",
"=",
"spdist",
".",
"cdist",
"(",
"verts",
",",
"verts",
")",
"else",
":",
"D",
"=",
"... | Will merge vertices that are closer than close_epsilon.
Warning, this has a O(n^2) memory usage because we compute the full
vert-to-vert distance matrix. If you have a large mesh, might want
to use some kind of spatial search structure like an octree or some fancy
hashing scheme
Returns: new_verts... | [
"Will",
"merge",
"vertices",
"that",
"are",
"closer",
"than",
"close_epsilon",
"."
] | train | https://github.com/julienr/meshcut/blob/226c79d8da52b657d904f783940c258093c929a5/meshcut.py#L306-L347 |
aequitas/python-rflink | rflink/parser.py | signed_to_float | def signed_to_float(hex: str) -> float:
"""Convert signed hexadecimal to floating value."""
if int(hex, 16) & 0x8000:
return -(int(hex, 16) & 0x7FFF) / 10
else:
return int(hex, 16) / 10 | python | def signed_to_float(hex: str) -> float:
"""Convert signed hexadecimal to floating value."""
if int(hex, 16) & 0x8000:
return -(int(hex, 16) & 0x7FFF) / 10
else:
return int(hex, 16) / 10 | [
"def",
"signed_to_float",
"(",
"hex",
":",
"str",
")",
"->",
"float",
":",
"if",
"int",
"(",
"hex",
",",
"16",
")",
"&",
"0x8000",
":",
"return",
"-",
"(",
"int",
"(",
"hex",
",",
"16",
")",
"&",
"0x7FFF",
")",
"/",
"10",
"else",
":",
"return",... | Convert signed hexadecimal to floating value. | [
"Convert",
"signed",
"hexadecimal",
"to",
"floating",
"value",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/parser.py#L170-L175 |
aequitas/python-rflink | rflink/parser.py | decode_packet | def decode_packet(packet: str) -> dict:
"""Break packet down into primitives, and do basic interpretation.
>>> decode_packet('20;06;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on... | python | def decode_packet(packet: str) -> dict:
"""Break packet down into primitives, and do basic interpretation.
>>> decode_packet('20;06;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on... | [
"def",
"decode_packet",
"(",
"packet",
":",
"str",
")",
"->",
"dict",
":",
"node_id",
",",
"_",
",",
"protocol",
",",
"attrs",
"=",
"packet",
".",
"split",
"(",
"DELIM",
",",
"3",
")",
"data",
"=",
"cast",
"(",
"Dict",
"[",
"str",
",",
"Any",
"]"... | Break packet down into primitives, and do basic interpretation.
>>> decode_packet('20;06;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on',
... }
True | [
"Break",
"packet",
"down",
"into",
"primitives",
"and",
"do",
"basic",
"interpretation",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/parser.py#L225-L289 |
aequitas/python-rflink | rflink/parser.py | encode_packet | def encode_packet(packet: dict) -> str:
"""Construct packet string from packet dictionary.
>>> encode_packet({
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... 'command': 'on',
... })
'10;newkaku;000001;01;on;'
"""
if packet['protocol'] == '... | python | def encode_packet(packet: dict) -> str:
"""Construct packet string from packet dictionary.
>>> encode_packet({
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... 'command': 'on',
... })
'10;newkaku;000001;01;on;'
"""
if packet['protocol'] == '... | [
"def",
"encode_packet",
"(",
"packet",
":",
"dict",
")",
"->",
"str",
":",
"if",
"packet",
"[",
"'protocol'",
"]",
"==",
"'rfdebug'",
":",
"return",
"'10;RFDEBUG='",
"+",
"packet",
"[",
"'command'",
"]",
"+",
"';'",
"elif",
"packet",
"[",
"'protocol'",
"... | Construct packet string from packet dictionary.
>>> encode_packet({
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... 'command': 'on',
... })
'10;newkaku;000001;01;on;' | [
"Construct",
"packet",
"string",
"from",
"packet",
"dictionary",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/parser.py#L297-L316 |
aequitas/python-rflink | rflink/parser.py | serialize_packet_id | def serialize_packet_id(packet: dict) -> str:
"""Serialize packet identifiers into one reversable string.
>>> serialize_packet_id({
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... 'command': 'on',
... })
'newkaku_000001_01'
>>> serialize_packet... | python | def serialize_packet_id(packet: dict) -> str:
"""Serialize packet identifiers into one reversable string.
>>> serialize_packet_id({
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... 'command': 'on',
... })
'newkaku_000001_01'
>>> serialize_packet... | [
"def",
"serialize_packet_id",
"(",
"packet",
":",
"dict",
")",
"->",
"str",
":",
"# translate protocol in something reversable",
"protocol",
"=",
"protocol_translations",
"[",
"packet",
"[",
"'protocol'",
"]",
"]",
"if",
"protocol",
"==",
"UNKNOWN",
":",
"protocol",... | Serialize packet identifiers into one reversable string.
>>> serialize_packet_id({
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... 'command': 'on',
... })
'newkaku_000001_01'
>>> serialize_packet_id({
... 'protocol': 'ikea koppla',
... ... | [
"Serialize",
"packet",
"identifiers",
"into",
"one",
"reversable",
"string",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/parser.py#L353-L390 |
aequitas/python-rflink | rflink/parser.py | deserialize_packet_id | def deserialize_packet_id(packet_id: str) -> dict:
r"""Turn a packet id into individual packet components.
>>> deserialize_packet_id('newkaku_000001_01') == {
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... }
True
>>> deserialize_packet_id('ikeakoppla_... | python | def deserialize_packet_id(packet_id: str) -> dict:
r"""Turn a packet id into individual packet components.
>>> deserialize_packet_id('newkaku_000001_01') == {
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... }
True
>>> deserialize_packet_id('ikeakoppla_... | [
"def",
"deserialize_packet_id",
"(",
"packet_id",
":",
"str",
")",
"->",
"dict",
":",
"if",
"packet_id",
"==",
"'rflink'",
":",
"return",
"{",
"'protocol'",
":",
"UNKNOWN",
"}",
"protocol",
",",
"",
"*",
"id_switch",
"=",
"packet_id",
".",
"split",
"(",
... | r"""Turn a packet id into individual packet components.
>>> deserialize_packet_id('newkaku_000001_01') == {
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... }
True
>>> deserialize_packet_id('ikeakoppla_000080_0') == {
... 'protocol': 'ikea koppla',
... | [
"r",
"Turn",
"a",
"packet",
"id",
"into",
"individual",
"packet",
"components",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/parser.py#L393-L427 |
aequitas/python-rflink | rflink/parser.py | packet_events | def packet_events(packet: dict) -> Generator:
"""Return list of all events in the packet.
>>> x = list(packet_events({
... 'protocol': 'alecto v1',
... 'id': 'ec02',
... 'temperature': 1.0,
... 'temperature_unit': '°C',
... 'humidity': 10,
... 'humidity_unit': '%... | python | def packet_events(packet: dict) -> Generator:
"""Return list of all events in the packet.
>>> x = list(packet_events({
... 'protocol': 'alecto v1',
... 'id': 'ec02',
... 'temperature': 1.0,
... 'temperature_unit': '°C',
... 'humidity': 10,
... 'humidity_unit': '%... | [
"def",
"packet_events",
"(",
"packet",
":",
"dict",
")",
"->",
"Generator",
":",
"field_abbrev",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"PACKET_FIELDS",
".",
"items",
"(",
")",
"}",
"packet_id",
"=",
"serialize_packet_id",
"(",
"packet",
... | Return list of all events in the packet.
>>> x = list(packet_events({
... 'protocol': 'alecto v1',
... 'id': 'ec02',
... 'temperature': 1.0,
... 'temperature_unit': '°C',
... 'humidity': 10,
... 'humidity_unit': '%',
... }))
>>> assert {
... 'id': 'al... | [
"Return",
"list",
"of",
"all",
"events",
"in",
"the",
"packet",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/parser.py#L430-L493 |
aequitas/python-rflink | rflinkproxy/__main__.py | decode_tx_packet | def decode_tx_packet(packet: str) -> dict:
"""Break packet down into primitives, and do basic interpretation.
>>> decode_packet('10;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on... | python | def decode_tx_packet(packet: str) -> dict:
"""Break packet down into primitives, and do basic interpretation.
>>> decode_packet('10;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on... | [
"def",
"decode_tx_packet",
"(",
"packet",
":",
"str",
")",
"->",
"dict",
":",
"node_id",
",",
"protocol",
",",
"attrs",
"=",
"packet",
".",
"split",
"(",
"DELIM",
",",
"2",
")",
"data",
"=",
"cast",
"(",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
... | Break packet down into primitives, and do basic interpretation.
>>> decode_packet('10;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on',
... }
True | [
"Break",
"packet",
"down",
"into",
"primitives",
"and",
"do",
"basic",
"interpretation",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L82-L114 |
aequitas/python-rflink | rflinkproxy/__main__.py | main | def main(argv=sys.argv[1:], loop=None):
"""Parse argument and setup main program loop."""
args = docopt(__doc__, argv=argv,
version=pkg_resources.require('rflink')[0].version)
level = logging.ERROR
if args['-v']:
level = logging.INFO
if args['-v'] == 2:
level = log... | python | def main(argv=sys.argv[1:], loop=None):
"""Parse argument and setup main program loop."""
args = docopt(__doc__, argv=argv,
version=pkg_resources.require('rflink')[0].version)
level = logging.ERROR
if args['-v']:
level = logging.INFO
if args['-v'] == 2:
level = log... | [
"def",
"main",
"(",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"loop",
"=",
"None",
")",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
",",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"'rflink'",
"... | Parse argument and setup main program loop. | [
"Parse",
"argument",
"and",
"setup",
"main",
"program",
"loop",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L264-L321 |
aequitas/python-rflink | rflinkproxy/__main__.py | ProxyProtocol.handle_raw_packet | def handle_raw_packet(self, raw_packet):
"""Parse raw packet string into packet dict."""
log.debug('got packet: %s', raw_packet)
packet = None
try:
packet = decode_packet(raw_packet)
except:
log.exception('failed to parse packet: %s', packet)
log.... | python | def handle_raw_packet(self, raw_packet):
"""Parse raw packet string into packet dict."""
log.debug('got packet: %s', raw_packet)
packet = None
try:
packet = decode_packet(raw_packet)
except:
log.exception('failed to parse packet: %s', packet)
log.... | [
"def",
"handle_raw_packet",
"(",
"self",
",",
"raw_packet",
")",
":",
"log",
".",
"debug",
"(",
"'got packet: %s'",
",",
"raw_packet",
")",
"packet",
"=",
"None",
"try",
":",
"packet",
"=",
"decode_packet",
"(",
"raw_packet",
")",
"except",
":",
"log",
"."... | Parse raw packet string into packet dict. | [
"Parse",
"raw",
"packet",
"string",
"into",
"packet",
"dict",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L59-L79 |
aequitas/python-rflink | rflinkproxy/__main__.py | RFLinkProxy.handle_raw_tx_packet | def handle_raw_tx_packet(self, writer, raw_packet):
"""Parse raw packet string into packet dict."""
peer = writer.get_extra_info('peername')
log.debug(' %s:%s: processing data: %s', peer[0], peer[1], raw_packet)
packet = None
try:
packet = decode_tx_packet(raw_packet)... | python | def handle_raw_tx_packet(self, writer, raw_packet):
"""Parse raw packet string into packet dict."""
peer = writer.get_extra_info('peername')
log.debug(' %s:%s: processing data: %s', peer[0], peer[1], raw_packet)
packet = None
try:
packet = decode_tx_packet(raw_packet)... | [
"def",
"handle_raw_tx_packet",
"(",
"self",
",",
"writer",
",",
"raw_packet",
")",
":",
"peer",
"=",
"writer",
".",
"get_extra_info",
"(",
"'peername'",
")",
"log",
".",
"debug",
"(",
"' %s:%s: processing data: %s'",
",",
"peer",
"[",
"0",
"]",
",",
"peer",
... | Parse raw packet string into packet dict. | [
"Parse",
"raw",
"packet",
"string",
"into",
"packet",
"dict",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L131-L150 |
aequitas/python-rflink | rflinkproxy/__main__.py | RFLinkProxy.forward_packet | def forward_packet(self, writer, packet, raw_packet):
"""Forward packet from client to RFLink."""
peer = writer.get_extra_info('peername')
log.debug(' %s:%s: forwarding data: %s', peer[0], peer[1], packet)
if 'command' in packet:
packet_id = serialize_packet_id(packet)
... | python | def forward_packet(self, writer, packet, raw_packet):
"""Forward packet from client to RFLink."""
peer = writer.get_extra_info('peername')
log.debug(' %s:%s: forwarding data: %s', peer[0], peer[1], packet)
if 'command' in packet:
packet_id = serialize_packet_id(packet)
... | [
"def",
"forward_packet",
"(",
"self",
",",
"writer",
",",
"packet",
",",
"raw_packet",
")",
":",
"peer",
"=",
"writer",
".",
"get_extra_info",
"(",
"'peername'",
")",
"log",
".",
"debug",
"(",
"' %s:%s: forwarding data: %s'",
",",
"peer",
"[",
"0",
"]",
",... | Forward packet from client to RFLink. | [
"Forward",
"packet",
"from",
"client",
"to",
"RFLink",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L153-L168 |
aequitas/python-rflink | rflinkproxy/__main__.py | RFLinkProxy.client_connected_callback | def client_connected_callback(self, reader, writer):
"""Handle connected client."""
peer = writer.get_extra_info('peername')
clients.append((reader, writer, peer))
log.info("Incoming connection from: %s:%s", peer[0], peer[1])
try:
while True:
data = yi... | python | def client_connected_callback(self, reader, writer):
"""Handle connected client."""
peer = writer.get_extra_info('peername')
clients.append((reader, writer, peer))
log.info("Incoming connection from: %s:%s", peer[0], peer[1])
try:
while True:
data = yi... | [
"def",
"client_connected_callback",
"(",
"self",
",",
"reader",
",",
"writer",
")",
":",
"peer",
"=",
"writer",
".",
"get_extra_info",
"(",
"'peername'",
")",
"clients",
".",
"append",
"(",
"(",
"reader",
",",
"writer",
",",
"peer",
")",
")",
"log",
".",... | Handle connected client. | [
"Handle",
"connected",
"client",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L171-L202 |
aequitas/python-rflink | rflinkproxy/__main__.py | RFLinkProxy.raw_callback | def raw_callback(self, raw_packet):
"""Send data to all connected clients."""
if not ';PONG;' in raw_packet:
log.info('forwarding packet %s to clients', raw_packet)
else:
log.debug('forwarding packet %s to clients', raw_packet)
writers = [i[1] for i in list(client... | python | def raw_callback(self, raw_packet):
"""Send data to all connected clients."""
if not ';PONG;' in raw_packet:
log.info('forwarding packet %s to clients', raw_packet)
else:
log.debug('forwarding packet %s to clients', raw_packet)
writers = [i[1] for i in list(client... | [
"def",
"raw_callback",
"(",
"self",
",",
"raw_packet",
")",
":",
"if",
"not",
"';PONG;'",
"in",
"raw_packet",
":",
"log",
".",
"info",
"(",
"'forwarding packet %s to clients'",
",",
"raw_packet",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'forwarding packet ... | Send data to all connected clients. | [
"Send",
"data",
"to",
"all",
"connected",
"clients",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L204-L212 |
aequitas/python-rflink | rflinkproxy/__main__.py | RFLinkProxy.reconnect | def reconnect(self, exc=None):
"""Schedule reconnect after connection has been unexpectedly lost."""
# Reset protocol binding before starting reconnect
self.protocol = None
if not self.closing:
log.warning('disconnected from Rflink, reconnecting')
self.loop.creat... | python | def reconnect(self, exc=None):
"""Schedule reconnect after connection has been unexpectedly lost."""
# Reset protocol binding before starting reconnect
self.protocol = None
if not self.closing:
log.warning('disconnected from Rflink, reconnecting')
self.loop.creat... | [
"def",
"reconnect",
"(",
"self",
",",
"exc",
"=",
"None",
")",
":",
"# Reset protocol binding before starting reconnect",
"self",
".",
"protocol",
"=",
"None",
"if",
"not",
"self",
".",
"closing",
":",
"log",
".",
"warning",
"(",
"'disconnected from Rflink, reconn... | Schedule reconnect after connection has been unexpectedly lost. | [
"Schedule",
"reconnect",
"after",
"connection",
"has",
"been",
"unexpectedly",
"lost",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L214-L221 |
aequitas/python-rflink | rflinkproxy/__main__.py | RFLinkProxy.connect | async def connect(self):
"""Set up connection and hook it into HA for reconnect/shutdown."""
import serial
log.info('Initiating Rflink connection')
# Rflink create_rflink_connection decides based on the value of host
# (string or None) if serial or tcp mode should be used
... | python | async def connect(self):
"""Set up connection and hook it into HA for reconnect/shutdown."""
import serial
log.info('Initiating Rflink connection')
# Rflink create_rflink_connection decides based on the value of host
# (string or None) if serial or tcp mode should be used
... | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"import",
"serial",
"log",
".",
"info",
"(",
"'Initiating Rflink connection'",
")",
"# Rflink create_rflink_connection decides based on the value of host",
"# (string or None) if serial or tcp mode should be used",
"# Setup protocol... | Set up connection and hook it into HA for reconnect/shutdown. | [
"Set",
"up",
"connection",
"and",
"hook",
"it",
"into",
"HA",
"for",
"reconnect",
"/",
"shutdown",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflinkproxy/__main__.py#L223-L261 |
aequitas/python-rflink | rflink/protocol.py | create_rflink_connection | def create_rflink_connection(port=None, host=None, baud=57600, protocol=RflinkProtocol,
packet_callback=None, event_callback=None,
disconnect_callback=None, ignore=None, loop=None):
"""Create Rflink manager class, returns transport coroutine."""
# use de... | python | def create_rflink_connection(port=None, host=None, baud=57600, protocol=RflinkProtocol,
packet_callback=None, event_callback=None,
disconnect_callback=None, ignore=None, loop=None):
"""Create Rflink manager class, returns transport coroutine."""
# use de... | [
"def",
"create_rflink_connection",
"(",
"port",
"=",
"None",
",",
"host",
"=",
"None",
",",
"baud",
"=",
"57600",
",",
"protocol",
"=",
"RflinkProtocol",
",",
"packet_callback",
"=",
"None",
",",
"event_callback",
"=",
"None",
",",
"disconnect_callback",
"=",
... | Create Rflink manager class, returns transport coroutine. | [
"Create",
"Rflink",
"manager",
"class",
"returns",
"transport",
"coroutine",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L304-L325 |
aequitas/python-rflink | rflink/protocol.py | ProtocolBase.data_received | def data_received(self, data):
"""Add incoming data to buffer."""
data = data.decode()
log.debug('received data: %s', data.strip())
self.buffer += data
self.handle_lines() | python | def data_received(self, data):
"""Add incoming data to buffer."""
data = data.decode()
log.debug('received data: %s', data.strip())
self.buffer += data
self.handle_lines() | [
"def",
"data_received",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
")",
"log",
".",
"debug",
"(",
"'received data: %s'",
",",
"data",
".",
"strip",
"(",
")",
")",
"self",
".",
"buffer",
"+=",
"data",
"self",
".",
"... | Add incoming data to buffer. | [
"Add",
"incoming",
"data",
"to",
"buffer",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L49-L54 |
aequitas/python-rflink | rflink/protocol.py | ProtocolBase.handle_lines | def handle_lines(self):
"""Assemble incoming data into per-line packets."""
while "\r\n" in self.buffer:
line, self.buffer = self.buffer.split("\r\n", 1)
if valid_packet(line):
self.handle_raw_packet(line)
else:
log.warning('dropping in... | python | def handle_lines(self):
"""Assemble incoming data into per-line packets."""
while "\r\n" in self.buffer:
line, self.buffer = self.buffer.split("\r\n", 1)
if valid_packet(line):
self.handle_raw_packet(line)
else:
log.warning('dropping in... | [
"def",
"handle_lines",
"(",
"self",
")",
":",
"while",
"\"\\r\\n\"",
"in",
"self",
".",
"buffer",
":",
"line",
",",
"self",
".",
"buffer",
"=",
"self",
".",
"buffer",
".",
"split",
"(",
"\"\\r\\n\"",
",",
"1",
")",
"if",
"valid_packet",
"(",
"line",
... | Assemble incoming data into per-line packets. | [
"Assemble",
"incoming",
"data",
"into",
"per",
"-",
"line",
"packets",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L56-L63 |
aequitas/python-rflink | rflink/protocol.py | ProtocolBase.send_raw_packet | def send_raw_packet(self, packet: str):
"""Encode and put packet string onto write buffer."""
data = packet + '\r\n'
log.debug('writing data: %s', repr(data))
self.transport.write(data.encode()) | python | def send_raw_packet(self, packet: str):
"""Encode and put packet string onto write buffer."""
data = packet + '\r\n'
log.debug('writing data: %s', repr(data))
self.transport.write(data.encode()) | [
"def",
"send_raw_packet",
"(",
"self",
",",
"packet",
":",
"str",
")",
":",
"data",
"=",
"packet",
"+",
"'\\r\\n'",
"log",
".",
"debug",
"(",
"'writing data: %s'",
",",
"repr",
"(",
"data",
")",
")",
"self",
".",
"transport",
".",
"write",
"(",
"data",... | Encode and put packet string onto write buffer. | [
"Encode",
"and",
"put",
"packet",
"string",
"onto",
"write",
"buffer",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L69-L73 |
aequitas/python-rflink | rflink/protocol.py | ProtocolBase.log_all | def log_all(self, file):
"""Log all data received from RFLink to file."""
global rflink_log
if file == None:
rflink_log = None
else:
log.debug('logging to: %s', file)
rflink_log = open(file, 'a') | python | def log_all(self, file):
"""Log all data received from RFLink to file."""
global rflink_log
if file == None:
rflink_log = None
else:
log.debug('logging to: %s', file)
rflink_log = open(file, 'a') | [
"def",
"log_all",
"(",
"self",
",",
"file",
")",
":",
"global",
"rflink_log",
"if",
"file",
"==",
"None",
":",
"rflink_log",
"=",
"None",
"else",
":",
"log",
".",
"debug",
"(",
"'logging to: %s'",
",",
"file",
")",
"rflink_log",
"=",
"open",
"(",
"file... | Log all data received from RFLink to file. | [
"Log",
"all",
"data",
"received",
"from",
"RFLink",
"to",
"file",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L75-L82 |
aequitas/python-rflink | rflink/protocol.py | ProtocolBase.connection_lost | def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
log.exception('disconnected due to exception')
else:
log.info('disconnected because of close/abort.')
if self.disconnect_callback:
self.disconnect_cal... | python | def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
log.exception('disconnected due to exception')
else:
log.info('disconnected because of close/abort.')
if self.disconnect_callback:
self.disconnect_cal... | [
"def",
"connection_lost",
"(",
"self",
",",
"exc",
")",
":",
"if",
"exc",
":",
"log",
".",
"exception",
"(",
"'disconnected due to exception'",
")",
"else",
":",
"log",
".",
"info",
"(",
"'disconnected because of close/abort.'",
")",
"if",
"self",
".",
"discon... | Log when connection is closed, if needed call callback. | [
"Log",
"when",
"connection",
"is",
"closed",
"if",
"needed",
"call",
"callback",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L84-L91 |
aequitas/python-rflink | rflink/protocol.py | PacketHandling.handle_raw_packet | def handle_raw_packet(self, raw_packet):
"""Parse raw packet string into packet dict."""
log.debug('got packet: %s', raw_packet)
if rflink_log:
print(raw_packet, file=rflink_log)
rflink_log.flush()
packet = None
try:
packet = decode_packet(raw_... | python | def handle_raw_packet(self, raw_packet):
"""Parse raw packet string into packet dict."""
log.debug('got packet: %s', raw_packet)
if rflink_log:
print(raw_packet, file=rflink_log)
rflink_log.flush()
packet = None
try:
packet = decode_packet(raw_... | [
"def",
"handle_raw_packet",
"(",
"self",
",",
"raw_packet",
")",
":",
"log",
".",
"debug",
"(",
"'got packet: %s'",
",",
"raw_packet",
")",
"if",
"rflink_log",
":",
"print",
"(",
"raw_packet",
",",
"file",
"=",
"rflink_log",
")",
"rflink_log",
".",
"flush",
... | Parse raw packet string into packet dict. | [
"Parse",
"raw",
"packet",
"string",
"into",
"packet",
"dict",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L108-L131 |
aequitas/python-rflink | rflink/protocol.py | PacketHandling.handle_packet | def handle_packet(self, packet):
"""Process incoming packet dict and optionally call callback."""
if self.packet_callback:
# forward to callback
self.packet_callback(packet)
else:
print('packet', packet) | python | def handle_packet(self, packet):
"""Process incoming packet dict and optionally call callback."""
if self.packet_callback:
# forward to callback
self.packet_callback(packet)
else:
print('packet', packet) | [
"def",
"handle_packet",
"(",
"self",
",",
"packet",
")",
":",
"if",
"self",
".",
"packet_callback",
":",
"# forward to callback",
"self",
".",
"packet_callback",
"(",
"packet",
")",
"else",
":",
"print",
"(",
"'packet'",
",",
"packet",
")"
] | Process incoming packet dict and optionally call callback. | [
"Process",
"incoming",
"packet",
"dict",
"and",
"optionally",
"call",
"callback",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L133-L139 |
aequitas/python-rflink | rflink/protocol.py | PacketHandling.send_command | def send_command(self, device_id, action):
"""Send device command to rflink gateway."""
command = deserialize_packet_id(device_id)
command['command'] = action
log.debug('sending command: %s', command)
self.send_packet(command) | python | def send_command(self, device_id, action):
"""Send device command to rflink gateway."""
command = deserialize_packet_id(device_id)
command['command'] = action
log.debug('sending command: %s', command)
self.send_packet(command) | [
"def",
"send_command",
"(",
"self",
",",
"device_id",
",",
"action",
")",
":",
"command",
"=",
"deserialize_packet_id",
"(",
"device_id",
")",
"command",
"[",
"'command'",
"]",
"=",
"action",
"log",
".",
"debug",
"(",
"'sending command: %s'",
",",
"command",
... | Send device command to rflink gateway. | [
"Send",
"device",
"command",
"to",
"rflink",
"gateway",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L145-L150 |
aequitas/python-rflink | rflink/protocol.py | CommandSerialization.send_command_ack | def send_command_ack(self, device_id, action):
"""Send command, wait for gateway to repond with acknowledgment."""
# serialize commands
yield from self._ready_to_send.acquire()
acknowledgement = None
try:
self._command_ack.clear()
self.send_command(device_... | python | def send_command_ack(self, device_id, action):
"""Send command, wait for gateway to repond with acknowledgment."""
# serialize commands
yield from self._ready_to_send.acquire()
acknowledgement = None
try:
self._command_ack.clear()
self.send_command(device_... | [
"def",
"send_command_ack",
"(",
"self",
",",
"device_id",
",",
"action",
")",
":",
"# serialize commands",
"yield",
"from",
"self",
".",
"_ready_to_send",
".",
"acquire",
"(",
")",
"acknowledgement",
"=",
"None",
"try",
":",
"self",
".",
"_command_ack",
".",
... | Send command, wait for gateway to repond with acknowledgment. | [
"Send",
"command",
"wait",
"for",
"gateway",
"to",
"repond",
"with",
"acknowledgment",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L165-L188 |
aequitas/python-rflink | rflink/protocol.py | EventHandling._handle_packet | def _handle_packet(self, packet):
"""Event specific packet handling logic.
Break packet into events and fires configured event callback or
nicely prints events for console.
"""
events = packet_events(packet)
for event in events:
if self.ignore_event(event['i... | python | def _handle_packet(self, packet):
"""Event specific packet handling logic.
Break packet into events and fires configured event callback or
nicely prints events for console.
"""
events = packet_events(packet)
for event in events:
if self.ignore_event(event['i... | [
"def",
"_handle_packet",
"(",
"self",
",",
"packet",
")",
":",
"events",
"=",
"packet_events",
"(",
"packet",
")",
"for",
"event",
"in",
"events",
":",
"if",
"self",
".",
"ignore_event",
"(",
"event",
"[",
"'id'",
"]",
")",
":",
"log",
".",
"debug",
... | Event specific packet handling logic.
Break packet into events and fires configured event callback or
nicely prints events for console. | [
"Event",
"specific",
"packet",
"handling",
"logic",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L215-L231 |
aequitas/python-rflink | rflink/protocol.py | EventHandling.handle_event | def handle_event(self, event):
"""Default handling of incoming event (print)."""
string = '{id:<32} '
if 'command' in event:
string += '{command}'
elif 'version' in event:
if 'hardware' in event:
string += '{hardware} {firmware} '
strin... | python | def handle_event(self, event):
"""Default handling of incoming event (print)."""
string = '{id:<32} '
if 'command' in event:
string += '{command}'
elif 'version' in event:
if 'hardware' in event:
string += '{hardware} {firmware} '
strin... | [
"def",
"handle_event",
"(",
"self",
",",
"event",
")",
":",
"string",
"=",
"'{id:<32} '",
"if",
"'command'",
"in",
"event",
":",
"string",
"+=",
"'{command}'",
"elif",
"'version'",
"in",
"event",
":",
"if",
"'hardware'",
"in",
"event",
":",
"string",
"+=",... | Default handling of incoming event (print). | [
"Default",
"handling",
"of",
"incoming",
"event",
"(",
"print",
")",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L233-L247 |
aequitas/python-rflink | rflink/protocol.py | EventHandling.ignore_event | def ignore_event(self, event_id):
"""Verify event id against list of events to ignore.
>>> e = EventHandling(ignore=[
... 'test1_00',
... 'test2_*',
... ])
>>> e.ignore_event('test1_00')
True
>>> e.ignore_event('test2_00')
True
>>> e.i... | python | def ignore_event(self, event_id):
"""Verify event id against list of events to ignore.
>>> e = EventHandling(ignore=[
... 'test1_00',
... 'test2_*',
... ])
>>> e.ignore_event('test1_00')
True
>>> e.ignore_event('test2_00')
True
>>> e.i... | [
"def",
"ignore_event",
"(",
"self",
",",
"event_id",
")",
":",
"for",
"ignore",
"in",
"self",
".",
"ignore",
":",
"if",
"(",
"ignore",
"==",
"event_id",
"or",
"(",
"ignore",
".",
"endswith",
"(",
"'*'",
")",
"and",
"event_id",
".",
"startswith",
"(",
... | Verify event id against list of events to ignore.
>>> e = EventHandling(ignore=[
... 'test1_00',
... 'test2_*',
... ])
>>> e.ignore_event('test1_00')
True
>>> e.ignore_event('test2_00')
True
>>> e.ignore_event('test3_00')
False | [
"Verify",
"event",
"id",
"against",
"list",
"of",
"events",
"to",
"ignore",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L254-L272 |
aequitas/python-rflink | rflink/protocol.py | InverterProtocol.handle_event | def handle_event(self, event):
"""Handle incoming packet from rflink gateway."""
if event.get('command'):
if event['command'] == 'on':
cmd = 'off'
else:
cmd = 'on'
task = self.send_command_ack(event['id'], cmd)
self.loop.cr... | python | def handle_event(self, event):
"""Handle incoming packet from rflink gateway."""
if event.get('command'):
if event['command'] == 'on':
cmd = 'off'
else:
cmd = 'on'
task = self.send_command_ack(event['id'], cmd)
self.loop.cr... | [
"def",
"handle_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"get",
"(",
"'command'",
")",
":",
"if",
"event",
"[",
"'command'",
"]",
"==",
"'on'",
":",
"cmd",
"=",
"'off'",
"else",
":",
"cmd",
"=",
"'on'",
"task",
"=",
"self",
... | Handle incoming packet from rflink gateway. | [
"Handle",
"incoming",
"packet",
"from",
"rflink",
"gateway",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L282-L291 |
aequitas/python-rflink | rflink/protocol.py | RepeaterProtocol.handle_event | def handle_event(self, packet):
"""Handle incoming packet from rflink gateway."""
if packet.get('command'):
task = self.send_command_ack(packet['id'], packet['command'])
self.loop.create_task(task) | python | def handle_event(self, packet):
"""Handle incoming packet from rflink gateway."""
if packet.get('command'):
task = self.send_command_ack(packet['id'], packet['command'])
self.loop.create_task(task) | [
"def",
"handle_event",
"(",
"self",
",",
"packet",
")",
":",
"if",
"packet",
".",
"get",
"(",
"'command'",
")",
":",
"task",
"=",
"self",
".",
"send_command_ack",
"(",
"packet",
"[",
"'id'",
"]",
",",
"packet",
"[",
"'command'",
"]",
")",
"self",
"."... | Handle incoming packet from rflink gateway. | [
"Handle",
"incoming",
"packet",
"from",
"rflink",
"gateway",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L297-L301 |
aequitas/python-rflink | rflink/__main__.py | main | def main(argv=sys.argv[1:], loop=None):
"""Parse argument and setup main program loop."""
args = docopt(__doc__, argv=argv,
version=pkg_resources.require('rflink')[0].version)
level = logging.ERROR
if args['-v']:
level = logging.INFO
if args['-v'] == 2:
level = log... | python | def main(argv=sys.argv[1:], loop=None):
"""Parse argument and setup main program loop."""
args = docopt(__doc__, argv=argv,
version=pkg_resources.require('rflink')[0].version)
level = logging.ERROR
if args['-v']:
level = logging.INFO
if args['-v'] == 2:
level = log... | [
"def",
"main",
"(",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"loop",
"=",
"None",
")",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
",",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"'rflink'",
"... | Parse argument and setup main program loop. | [
"Parse",
"argument",
"and",
"setup",
"main",
"program",
"loop",
"."
] | train | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/__main__.py#L49-L100 |
JustinLovinger/optimal | optimal/algorithms/gsa.py | _initial_population_gsa | def _initial_population_gsa(population_size, solution_size, lower_bounds,
upper_bounds):
"""Create a random initial population of floating point values.
Args:
population_size: an integer representing the number of solutions in the population.
problem_size: the number... | python | def _initial_population_gsa(population_size, solution_size, lower_bounds,
upper_bounds):
"""Create a random initial population of floating point values.
Args:
population_size: an integer representing the number of solutions in the population.
problem_size: the number... | [
"def",
"_initial_population_gsa",
"(",
"population_size",
",",
"solution_size",
",",
"lower_bounds",
",",
"upper_bounds",
")",
":",
"if",
"len",
"(",
"lower_bounds",
")",
"!=",
"solution_size",
"or",
"len",
"(",
"upper_bounds",
")",
"!=",
"solution_size",
":",
"... | Create a random initial population of floating point values.
Args:
population_size: an integer representing the number of solutions in the population.
problem_size: the number of values in each solution.
lower_bounds: a list, each value is a lower bound for the corresponding
... | [
"Create",
"a",
"random",
"initial",
"population",
"of",
"floating",
"point",
"values",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L104-L125 |
JustinLovinger/optimal | optimal/algorithms/gsa.py | _new_population_gsa | def _new_population_gsa(population, fitnesses, velocities, lower_bounds,
upper_bounds, grav_initial, grav_reduction_rate,
iteration, max_iterations):
"""Generate a new population as given by GSA algorithm.
In GSA paper, grav_initial is G_i
"""
# Update th... | python | def _new_population_gsa(population, fitnesses, velocities, lower_bounds,
upper_bounds, grav_initial, grav_reduction_rate,
iteration, max_iterations):
"""Generate a new population as given by GSA algorithm.
In GSA paper, grav_initial is G_i
"""
# Update th... | [
"def",
"_new_population_gsa",
"(",
"population",
",",
"fitnesses",
",",
"velocities",
",",
"lower_bounds",
",",
"upper_bounds",
",",
"grav_initial",
",",
"grav_reduction_rate",
",",
"iteration",
",",
"max_iterations",
")",
":",
"# Update the gravitational constant, and th... | Generate a new population as given by GSA algorithm.
In GSA paper, grav_initial is G_i | [
"Generate",
"a",
"new",
"population",
"as",
"given",
"by",
"GSA",
"algorithm",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L128-L193 |
JustinLovinger/optimal | optimal/algorithms/gsa.py | _next_grav_gsa | def _next_grav_gsa(grav_initial, grav_reduction_rate, iteration,
max_iterations):
"""Calculate G as given by GSA algorithm.
In GSA paper, grav is G
"""
return grav_initial * math.exp(
-grav_reduction_rate * iteration / float(max_iterations)) | python | def _next_grav_gsa(grav_initial, grav_reduction_rate, iteration,
max_iterations):
"""Calculate G as given by GSA algorithm.
In GSA paper, grav is G
"""
return grav_initial * math.exp(
-grav_reduction_rate * iteration / float(max_iterations)) | [
"def",
"_next_grav_gsa",
"(",
"grav_initial",
",",
"grav_reduction_rate",
",",
"iteration",
",",
"max_iterations",
")",
":",
"return",
"grav_initial",
"*",
"math",
".",
"exp",
"(",
"-",
"grav_reduction_rate",
"*",
"iteration",
"/",
"float",
"(",
"max_iterations",
... | Calculate G as given by GSA algorithm.
In GSA paper, grav is G | [
"Calculate",
"G",
"as",
"given",
"by",
"GSA",
"algorithm",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L196-L203 |
JustinLovinger/optimal | optimal/algorithms/gsa.py | _get_masses | def _get_masses(fitnesses):
"""Convert fitnesses into masses, as given by GSA algorithm."""
# Obtain constants
best_fitness = max(fitnesses)
worst_fitness = min(fitnesses)
fitness_range = best_fitness - worst_fitness
# Calculate raw masses for each solution
raw_masses = []
for fitness i... | python | def _get_masses(fitnesses):
"""Convert fitnesses into masses, as given by GSA algorithm."""
# Obtain constants
best_fitness = max(fitnesses)
worst_fitness = min(fitnesses)
fitness_range = best_fitness - worst_fitness
# Calculate raw masses for each solution
raw_masses = []
for fitness i... | [
"def",
"_get_masses",
"(",
"fitnesses",
")",
":",
"# Obtain constants",
"best_fitness",
"=",
"max",
"(",
"fitnesses",
")",
"worst_fitness",
"=",
"min",
"(",
"fitnesses",
")",
"fitness_range",
"=",
"best_fitness",
"-",
"worst_fitness",
"# Calculate raw masses for each ... | Convert fitnesses into masses, as given by GSA algorithm. | [
"Convert",
"fitnesses",
"into",
"masses",
"as",
"given",
"by",
"GSA",
"algorithm",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L206-L226 |
JustinLovinger/optimal | optimal/algorithms/gsa.py | _gsa_force | def _gsa_force(grav, mass_i, mass_j, position_i, position_j):
"""Gives the force of solution j on solution i.
Variable name in GSA paper given in ()
args:
grav: The gravitational constant. (G)
mass_i: The mass of solution i (derived from fitness). (M_i)
mass_j: The mass of solution... | python | def _gsa_force(grav, mass_i, mass_j, position_i, position_j):
"""Gives the force of solution j on solution i.
Variable name in GSA paper given in ()
args:
grav: The gravitational constant. (G)
mass_i: The mass of solution i (derived from fitness). (M_i)
mass_j: The mass of solution... | [
"def",
"_gsa_force",
"(",
"grav",
",",
"mass_i",
",",
"mass_j",
",",
"position_i",
",",
"position_j",
")",
":",
"position_diff",
"=",
"numpy",
".",
"subtract",
"(",
"position_j",
",",
"position_i",
")",
"distance",
"=",
"numpy",
".",
"linalg",
".",
"norm",... | Gives the force of solution j on solution i.
Variable name in GSA paper given in ()
args:
grav: The gravitational constant. (G)
mass_i: The mass of solution i (derived from fitness). (M_i)
mass_j: The mass of solution j (derived from fitness). (M_j)
position_i: The position of ... | [
"Gives",
"the",
"force",
"of",
"solution",
"j",
"on",
"solution",
"i",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L229-L251 |
JustinLovinger/optimal | optimal/algorithms/gsa.py | _gsa_total_force | def _gsa_total_force(force_vectors, vector_length):
"""Return a randomly weighted sum of the force vectors.
args:
force_vectors: A list of force vectors on solution i.
returns:
numpy.array; The total force on solution i.
"""
if len(force_vectors) == 0:
return [0.0] * vector... | python | def _gsa_total_force(force_vectors, vector_length):
"""Return a randomly weighted sum of the force vectors.
args:
force_vectors: A list of force vectors on solution i.
returns:
numpy.array; The total force on solution i.
"""
if len(force_vectors) == 0:
return [0.0] * vector... | [
"def",
"_gsa_total_force",
"(",
"force_vectors",
",",
"vector_length",
")",
":",
"if",
"len",
"(",
"force_vectors",
")",
"==",
"0",
":",
"return",
"[",
"0.0",
"]",
"*",
"vector_length",
"# The GSA algorithm specifies that the total force in each dimension",
"# is a rand... | Return a randomly weighted sum of the force vectors.
args:
force_vectors: A list of force vectors on solution i.
returns:
numpy.array; The total force on solution i. | [
"Return",
"a",
"randomly",
"weighted",
"sum",
"of",
"the",
"force",
"vectors",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L254-L273 |
JustinLovinger/optimal | optimal/algorithms/gsa.py | _gsa_update_velocity | def _gsa_update_velocity(velocity, acceleration):
"""Stochastically update velocity given acceleration.
In GSA paper, velocity is v_i, acceleration is a_i
"""
# The GSA algorithm specifies that the new velocity for each dimension
# is a sum of a random fraction of its current velocity in that dime... | python | def _gsa_update_velocity(velocity, acceleration):
"""Stochastically update velocity given acceleration.
In GSA paper, velocity is v_i, acceleration is a_i
"""
# The GSA algorithm specifies that the new velocity for each dimension
# is a sum of a random fraction of its current velocity in that dime... | [
"def",
"_gsa_update_velocity",
"(",
"velocity",
",",
"acceleration",
")",
":",
"# The GSA algorithm specifies that the new velocity for each dimension",
"# is a sum of a random fraction of its current velocity in that dimension,",
"# and its acceleration in that dimension",
"# For this reason ... | Stochastically update velocity given acceleration.
In GSA paper, velocity is v_i, acceleration is a_i | [
"Stochastically",
"update",
"velocity",
"given",
"acceleration",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L284-L298 |
JustinLovinger/optimal | optimal/algorithms/genalg.py | _new_population_genalg | def _new_population_genalg(population,
fitnesses,
mutation_chance=0.02,
crossover_chance=0.7,
selection_function=gaoperators.tournament_selection,
crossover_function=gaoperators.one_poi... | python | def _new_population_genalg(population,
fitnesses,
mutation_chance=0.02,
crossover_chance=0.7,
selection_function=gaoperators.tournament_selection,
crossover_function=gaoperators.one_poi... | [
"def",
"_new_population_genalg",
"(",
"population",
",",
"fitnesses",
",",
"mutation_chance",
"=",
"0.02",
",",
"crossover_chance",
"=",
"0.7",
",",
"selection_function",
"=",
"gaoperators",
".",
"tournament_selection",
",",
"crossover_function",
"=",
"gaoperators",
"... | Perform all genetic algorithm operations on a population, and return a new population.
population must have an even number of chromosomes.
Args:
population: A list of binary lists, ex. [[0,1,1,0], [1,0,1,0]]
fitness: A list of fitnesses that correspond with chromosomes in the population,
... | [
"Perform",
"all",
"genetic",
"algorithm",
"operations",
"on",
"a",
"population",
"and",
"return",
"a",
"new",
"population",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/genalg.py#L109-L144 |
JustinLovinger/optimal | optimal/algorithms/genalg.py | _crossover | def _crossover(population, crossover_chance, crossover_operator):
"""Perform crossover on a population, return the new crossed-over population."""
new_population = []
for i in range(0, len(population), 2): # For every other index
# Take parents from every set of 2 in the population
# Wrap i... | python | def _crossover(population, crossover_chance, crossover_operator):
"""Perform crossover on a population, return the new crossed-over population."""
new_population = []
for i in range(0, len(population), 2): # For every other index
# Take parents from every set of 2 in the population
# Wrap i... | [
"def",
"_crossover",
"(",
"population",
",",
"crossover_chance",
",",
"crossover_operator",
")",
":",
"new_population",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"population",
")",
",",
"2",
")",
":",
"# For every other index",
"... | Perform crossover on a population, return the new crossed-over population. | [
"Perform",
"crossover",
"on",
"a",
"population",
"return",
"the",
"new",
"crossed",
"-",
"over",
"population",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/genalg.py#L147-L165 |
JustinLovinger/optimal | optimal/common.py | random_real_solution | def random_real_solution(solution_size, lower_bounds, upper_bounds):
"""Make a list of random real numbers between lower and upper bounds."""
return [
random.uniform(lower_bounds[i], upper_bounds[i])
for i in range(solution_size)
] | python | def random_real_solution(solution_size, lower_bounds, upper_bounds):
"""Make a list of random real numbers between lower and upper bounds."""
return [
random.uniform(lower_bounds[i], upper_bounds[i])
for i in range(solution_size)
] | [
"def",
"random_real_solution",
"(",
"solution_size",
",",
"lower_bounds",
",",
"upper_bounds",
")",
":",
"return",
"[",
"random",
".",
"uniform",
"(",
"lower_bounds",
"[",
"i",
"]",
",",
"upper_bounds",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
... | Make a list of random real numbers between lower and upper bounds. | [
"Make",
"a",
"list",
"of",
"random",
"real",
"numbers",
"between",
"lower",
"and",
"upper",
"bounds",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/common.py#L34-L39 |
JustinLovinger/optimal | optimal/common.py | make_population | def make_population(population_size, solution_generator, *args, **kwargs):
"""Make a population with the supplied generator."""
return [
solution_generator(*args, **kwargs) for _ in range(population_size)
] | python | def make_population(population_size, solution_generator, *args, **kwargs):
"""Make a population with the supplied generator."""
return [
solution_generator(*args, **kwargs) for _ in range(population_size)
] | [
"def",
"make_population",
"(",
"population_size",
",",
"solution_generator",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"solution_generator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"_",
"in",
"range",
"(",
"popula... | Make a population with the supplied generator. | [
"Make",
"a",
"population",
"with",
"the",
"supplied",
"generator",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/common.py#L42-L46 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | tournament_selection | def tournament_selection(population,
fitnesses,
num_competitors=2,
diversity_weight=0.0):
"""Create a list of parents with tournament selection.
Args:
population: A list of solutions.
fitnesses: A list of fitness values ... | python | def tournament_selection(population,
fitnesses,
num_competitors=2,
diversity_weight=0.0):
"""Create a list of parents with tournament selection.
Args:
population: A list of solutions.
fitnesses: A list of fitness values ... | [
"def",
"tournament_selection",
"(",
"population",
",",
"fitnesses",
",",
"num_competitors",
"=",
"2",
",",
"diversity_weight",
"=",
"0.0",
")",
":",
"# Optimization if diversity factor is disabled",
"if",
"diversity_weight",
"<=",
"0.0",
":",
"fitness_pop",
"=",
"zip"... | Create a list of parents with tournament selection.
Args:
population: A list of solutions.
fitnesses: A list of fitness values corresponding to solutions in population.
num_competitors: Number of solutions to compare every round.
Best solution among competitors is selected.
... | [
"Create",
"a",
"list",
"of",
"parents",
"with",
"tournament",
"selection",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L35-L95 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | stochastic_selection | def stochastic_selection(population, fitnesses):
"""Create a list of parents with stochastic universal sampling."""
pop_size = len(population)
probabilities = _fitnesses_to_probabilities(fitnesses)
# Create selection list (for stochastic universal sampling)
selection_list = []
selection_spacing... | python | def stochastic_selection(population, fitnesses):
"""Create a list of parents with stochastic universal sampling."""
pop_size = len(population)
probabilities = _fitnesses_to_probabilities(fitnesses)
# Create selection list (for stochastic universal sampling)
selection_list = []
selection_spacing... | [
"def",
"stochastic_selection",
"(",
"population",
",",
"fitnesses",
")",
":",
"pop_size",
"=",
"len",
"(",
"population",
")",
"probabilities",
"=",
"_fitnesses_to_probabilities",
"(",
"fitnesses",
")",
"# Create selection list (for stochastic universal sampling)",
"selectio... | Create a list of parents with stochastic universal sampling. | [
"Create",
"a",
"list",
"of",
"parents",
"with",
"stochastic",
"universal",
"sampling",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L98-L119 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | roulette_selection | def roulette_selection(population, fitnesses):
"""Create a list of parents with roulette selection."""
probabilities = _fitnesses_to_probabilities(fitnesses)
intermediate_population = []
for _ in range(len(population)):
# Choose a random individual
selection = random.uniform(0.0, 1.0)
... | python | def roulette_selection(population, fitnesses):
"""Create a list of parents with roulette selection."""
probabilities = _fitnesses_to_probabilities(fitnesses)
intermediate_population = []
for _ in range(len(population)):
# Choose a random individual
selection = random.uniform(0.0, 1.0)
... | [
"def",
"roulette_selection",
"(",
"population",
",",
"fitnesses",
")",
":",
"probabilities",
"=",
"_fitnesses_to_probabilities",
"(",
"fitnesses",
")",
"intermediate_population",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"population",
")",
")",
... | Create a list of parents with roulette selection. | [
"Create",
"a",
"list",
"of",
"parents",
"with",
"roulette",
"selection",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L122-L136 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | _rescale | def _rescale(vector):
"""Scale values in vector to the range [0, 1].
Args:
vector: A list of real values.
"""
# Subtract min, making smallest value 0
min_val = min(vector)
vector = [v - min_val for v in vector]
# Divide by max, making largest value 1
max_val = float(max(vector)... | python | def _rescale(vector):
"""Scale values in vector to the range [0, 1].
Args:
vector: A list of real values.
"""
# Subtract min, making smallest value 0
min_val = min(vector)
vector = [v - min_val for v in vector]
# Divide by max, making largest value 1
max_val = float(max(vector)... | [
"def",
"_rescale",
"(",
"vector",
")",
":",
"# Subtract min, making smallest value 0",
"min_val",
"=",
"min",
"(",
"vector",
")",
"vector",
"=",
"[",
"v",
"-",
"min_val",
"for",
"v",
"in",
"vector",
"]",
"# Divide by max, making largest value 1",
"max_val",
"=",
... | Scale values in vector to the range [0, 1].
Args:
vector: A list of real values. | [
"Scale",
"values",
"in",
"vector",
"to",
"the",
"range",
"[",
"0",
"1",
"]",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L139-L154 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | _diversity_metric | def _diversity_metric(solution, population):
"""Return diversity value for solution compared to given population.
Metric is sum of distance between solution and each solution in population,
normalized to [0.0, 1.0].
"""
# Edge case for empty population
# If there are no other solutions, the giv... | python | def _diversity_metric(solution, population):
"""Return diversity value for solution compared to given population.
Metric is sum of distance between solution and each solution in population,
normalized to [0.0, 1.0].
"""
# Edge case for empty population
# If there are no other solutions, the giv... | [
"def",
"_diversity_metric",
"(",
"solution",
",",
"population",
")",
":",
"# Edge case for empty population",
"# If there are no other solutions, the given solution has maximum diversity",
"if",
"population",
"==",
"[",
"]",
":",
"return",
"1.0",
"return",
"(",
"sum",
"(",
... | Return diversity value for solution compared to given population.
Metric is sum of distance between solution and each solution in population,
normalized to [0.0, 1.0]. | [
"Return",
"diversity",
"value",
"for",
"solution",
"compared",
"to",
"given",
"population",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L157-L172 |
JustinLovinger/optimal | optimal/algorithms/gaoperators.py | _manhattan_distance | def _manhattan_distance(vec_a, vec_b):
"""Return manhattan distance between two lists of numbers."""
if len(vec_a) != len(vec_b):
raise ValueError('len(vec_a) must equal len(vec_b)')
return sum(map(lambda a, b: abs(a - b), vec_a, vec_b)) | python | def _manhattan_distance(vec_a, vec_b):
"""Return manhattan distance between two lists of numbers."""
if len(vec_a) != len(vec_b):
raise ValueError('len(vec_a) must equal len(vec_b)')
return sum(map(lambda a, b: abs(a - b), vec_a, vec_b)) | [
"def",
"_manhattan_distance",
"(",
"vec_a",
",",
"vec_b",
")",
":",
"if",
"len",
"(",
"vec_a",
")",
"!=",
"len",
"(",
"vec_b",
")",
":",
"raise",
"ValueError",
"(",
"'len(vec_a) must equal len(vec_b)'",
")",
"return",
"sum",
"(",
"map",
"(",
"lambda",
"a",... | Return manhattan distance between two lists of numbers. | [
"Return",
"manhattan",
"distance",
"between",
"two",
"lists",
"of",
"numbers",
"."
] | train | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L175-L179 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.