max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
webkit/tools/layout_tests/layout_package/test_shell_thread.py
zachlatta/chromium
1
6613151
<filename>webkit/tools/layout_tests/layout_package/test_shell_thread.py # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A Thread object for running the test shell and processing URLs from a shared queue. Each thread runs a separate instance of the test_shell binary and validates the output. When there are no more URLs to process in the shared queue, the thread exits. """ import copy import logging import os import Queue import signal import subprocess import sys import thread import threading import time import path_utils import platform_utils import test_failures def ProcessOutput(proc, test_info, test_types, test_args, target): """Receives the output from a test_shell process, subjects it to a number of tests, and returns a list of failure types the test produced. Args: proc: an active test_shell process test_info: Object containing the test filename, uri and timeout test_types: list of test types to subject the output to test_args: arguments to be passed to each test target: Debug or Release Returns: a list of failure objects and times for the test being processed """ outlines = [] failures = [] crash_or_timeout = False # Some test args, such as the image hash, may be added or changed on a # test-by-test basis. local_test_args = copy.copy(test_args) start_time = time.time() line = proc.stdout.readline() while line.rstrip() != "#EOF": # Make sure we haven't crashed. if line == '' and proc.poll() is not None: failures.append(test_failures.FailureCrash()) # This is hex code 0xc000001d, which is used for abrupt termination. # This happens if we hit ctrl+c from the prompt and we happen to # be waiting on the test_shell. # sdoyon: Not sure for which OS and in what circumstances the # above code is valid. What works for me under Linux to detect # ctrl+c is for the subprocess returncode to be negative SIGINT. And # that agrees with the subprocess documentation. if (-1073741510 == proc.returncode or -signal.SIGINT == proc.returncode): raise KeyboardInterrupt crash_or_timeout = True break # Don't include #URL lines in our output if line.startswith("#URL:"): test_string = test_info.uri.strip() url = line.rstrip()[5:] if url != test_string: logging.fatal("Test got out of sync:\n|%s|\n|%s|" % (url, test_string)) raise AssertionError("test out of sync") elif line.startswith("#MD5:"): local_test_args.hash = line.rstrip()[5:] elif line.startswith("#TEST_TIMED_OUT"): # Test timed out, but we still need to read until #EOF. crash_or_timeout = True failures.append(test_failures.FailureTimeout()) else: outlines.append(line) line = proc.stdout.readline() end_test_time = time.time() # Check the output and save the results. time_for_diffs = {} for test_type in test_types: start_diff_time = time.time() new_failures = test_type.CompareOutput(test_info.filename, proc, ''.join(outlines), local_test_args, target) # Don't add any more failures if we already have a crash or timeout, so # we don't double-report those tests. if not crash_or_timeout: failures.extend(new_failures) time_for_diffs[test_type.__class__.__name__] = ( time.time() - start_diff_time) total_time_for_all_diffs = time.time() - end_test_time test_run_time = end_test_time - start_time return TestStats(test_info.filename, failures, test_run_time, total_time_for_all_diffs, time_for_diffs) def StartTestShell(command, args): """Returns the process for a new test_shell started in layout-tests mode.""" cmd = [] # Hook for injecting valgrind or other runtime instrumentation, # used by e.g. tools/valgrind/valgrind_tests.py. wrapper = os.environ.get("BROWSER_WRAPPER", None) if wrapper != None: cmd += [wrapper] cmd += command + ['--layout-tests'] + args return subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) class TestStats: def __init__(self, filename, failures, test_run_time, total_time_for_all_diffs, time_for_diffs): self.filename = filename self.failures = failures self.test_run_time = test_run_time self.total_time_for_all_diffs = total_time_for_all_diffs self.time_for_diffs = time_for_diffs class SingleTestThread(threading.Thread): """Thread wrapper for running a single test file.""" def __init__(self, test_shell_command, shell_args, test_info, test_types, test_args, target): """ Args: test_info: Object containing the test filename, uri and timeout See TestShellThread for documentation of the remaining arguments. """ threading.Thread.__init__(self) self._command = test_shell_command self._shell_args = shell_args self._test_info = test_info self._test_types = test_types self._test_args = test_args self._target = target def run(self): proc = StartTestShell(self._command, self._shell_args + ["--time-out-ms=" + self._test_info.timeout, self._test_info.uri]) self._test_stats = ProcessOutput(proc, self._test_info, self._test_types, self._test_args, self._target) def GetTestStats(self): return self._test_stats class TestShellThread(threading.Thread): def __init__(self, filename_list_queue, test_shell_command, test_types, test_args, shell_args, options): """Initialize all the local state for this test shell thread. Args: filename_list_queue: A thread safe Queue class that contains lists of tuples of (filename, uri) pairs. test_shell_command: A list specifying the command+args for test_shell test_types: A list of TestType objects to run the test output against. test_args: A TestArguments object to pass to each TestType. shell_args: Any extra arguments to be passed to test_shell.exe. options: A property dictionary as produced by optparse. The command-line options should match those expected by run_webkit_tests; they are typically passed via the run_webkit_tests.TestRunner class. """ threading.Thread.__init__(self) self._filename_list_queue = filename_list_queue self._filename_list = [] self._test_shell_command = test_shell_command self._test_types = test_types self._test_args = test_args self._test_shell_proc = None self._shell_args = shell_args self._options = options self._failures = {} self._canceled = False self._exception_info = None self._directory_timing_stats = {} self._test_stats = [] # Current directory of tests we're running. self._current_dir = None # Number of tests in self._current_dir. self._num_tests_in_current_dir = None # Time at which we started running tests from self._current_dir. self._current_dir_start_time = None def GetFailures(self): """Returns a dictionary mapping test filename to a list of TestFailures.""" return self._failures def GetDirectoryTimingStats(self): """Returns a dictionary mapping test directory to a tuple of (number of tests in that directory, time to run the tests)""" return self._directory_timing_stats; def GetIndividualTestStats(self): """Returns a list of (test_filename, time_to_run_test, total_time_for_all_diffs, time_for_diffs) tuples.""" return self._test_stats def Cancel(self): """Set a flag telling this thread to quit.""" self._canceled = True def GetExceptionInfo(self): """If run() terminated on an uncaught exception, return it here ((type, value, traceback) tuple). Returns None if run() terminated normally. Meant to be called after joining this thread.""" return self._exception_info def run(self): """Delegate main work to a helper method and watch for uncaught exceptions.""" try: self._Run() except: # Save the exception for our caller to see. self._exception_info = sys.exc_info() # Re-raise it and die. raise def _Run(self): """Main work entry point of the thread. Basically we pull urls from the filename queue and run the tests until we run out of urls.""" batch_size = 0 batch_count = 0 if self._options.batch_size: try: batch_size = int(self._options.batch_size) except: logging.info("Ignoring invalid batch size '%s'" % self._options.batch_size) while True: if self._canceled: logging.info('Testing canceled') return if len(self._filename_list) is 0: if self._current_dir is not None: self._directory_timing_stats[self._current_dir] = \ (self._num_tests_in_current_dir, time.time() - self._current_dir_start_time) try: self._current_dir, self._filename_list = \ self._filename_list_queue.get_nowait() except Queue.Empty: self._KillTestShell() logging.debug("queue empty, quitting test shell thread") return self._num_tests_in_current_dir = len(self._filename_list) self._current_dir_start_time = time.time() test_info = self._filename_list.pop() # We have a url, run tests. batch_count += 1 if self._options.run_singly: failures = self._RunTestSingly(test_info) else: failures = self._RunTest(test_info) filename = test_info.filename if failures: # Check and kill test shell if we need too. if len([1 for f in failures if f.ShouldKillTestShell()]): self._KillTestShell() # Reset the batch count since the shell just bounced. batch_count = 0 # Print the error message(s). error_str = '\n'.join([' ' + f.Message() for f in failures]) logging.error("%s failed:\n%s" % (path_utils.RelativeTestFilename(filename), error_str)) # Group the errors for reporting. self._failures[filename] = failures else: logging.debug(path_utils.RelativeTestFilename(filename) + " passed") if batch_size > 0 and batch_count > batch_size: # Bounce the shell and reset count. self._KillTestShell() batch_count = 0 def _RunTestSingly(self, test_info): """Run a test in a separate thread, enforcing a hard time limit. Since we can only detect the termination of a thread, not any internal state or progress, we can only run per-test timeouts when running test files singly. Args: test_info: Object containing the test filename, uri and timeout Return: A list of TestFailure objects describing the error. """ worker = SingleTestThread(self._test_shell_command, self._shell_args, test_info, self._test_types, self._test_args, self._options.target) worker.start() # When we're running one test per test_shell process, we can enforce # a hard timeout. the test_shell watchdog uses 2.5x the timeout # We want to be larger than that. worker.join(int(test_info.timeout) * 3.0 / 1000.0) if worker.isAlive(): # If join() returned with the thread still running, the test_shell.exe is # completely hung and there's nothing more we can do with it. We have # to kill all the test_shells to free it up. If we're running more than # one test_shell thread, we'll end up killing the other test_shells too, # introducing spurious crashes. We accept that tradeoff in order to # avoid losing the rest of this thread's results. logging.error('Test thread hung: killing all test_shells') # PlatformUtility() wants a base_dir, but it doesn't matter here. platform_util = platform_utils.PlatformUtility('') platform_util.KillAllTestShells() try: stats = worker.GetTestStats() self._test_stats.append(stats) failures = stats.failures except AttributeError, e: failures = [] logging.error('Cannot get results of test: %s' % test_info.filename) return failures def _RunTest(self, test_info): """Run a single test file using a shared test_shell process. Args: test_info: Object containing the test filename, uri and timeout Return: A list of TestFailure objects describing the error. """ self._EnsureTestShellIsRunning() # Args to test_shell is a space-separated list of "uri timeout pixel_hash" # The timeout and pixel_hash are optional. The timeout is used if this # test has a custom timeout. The pixel_hash is used to avoid doing an image # dump if the checksums match, so it should be set to a blank value if we # are generating a new baseline. (Otherwise, an image from a previous run # will be copied into the baseline.) image_hash = test_info.image_hash if image_hash and self._test_args.new_baseline: image_hash = "" self._test_shell_proc.stdin.write(("%s %s %s\n" % (test_info.uri, test_info.timeout, image_hash))) # If the test shell is dead, the above may cause an IOError as we # try to write onto the broken pipe. If this is the first test for # this test shell process, than the test shell did not # successfully start. If this is not the first test, then the # previous tests have caused some kind of delayed crash. We don't # try to recover here. self._test_shell_proc.stdin.flush() stats = ProcessOutput(self._test_shell_proc, test_info, self._test_types, self._test_args, self._options.target) self._test_stats.append(stats) return stats.failures def _EnsureTestShellIsRunning(self): """Start the shared test shell, if it's not running. Not for use when running tests singly, since those each start a separate test shell in their own thread. """ if (not self._test_shell_proc or self._test_shell_proc.poll() is not None): self._test_shell_proc = StartTestShell(self._test_shell_command, self._shell_args) def _KillTestShell(self): """Kill the test shell process if it's running.""" if self._test_shell_proc: self._test_shell_proc.stdin.close() self._test_shell_proc.stdout.close() if self._test_shell_proc.stderr: self._test_shell_proc.stderr.close() if sys.platform not in ('win32', 'cygwin'): # Closing stdin/stdout/stderr hangs sometimes on OS X. subprocess.Popen(["kill", "-9", str(self._test_shell_proc.pid)]) self._test_shell_proc = None
<filename>webkit/tools/layout_tests/layout_package/test_shell_thread.py # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A Thread object for running the test shell and processing URLs from a shared queue. Each thread runs a separate instance of the test_shell binary and validates the output. When there are no more URLs to process in the shared queue, the thread exits. """ import copy import logging import os import Queue import signal import subprocess import sys import thread import threading import time import path_utils import platform_utils import test_failures def ProcessOutput(proc, test_info, test_types, test_args, target): """Receives the output from a test_shell process, subjects it to a number of tests, and returns a list of failure types the test produced. Args: proc: an active test_shell process test_info: Object containing the test filename, uri and timeout test_types: list of test types to subject the output to test_args: arguments to be passed to each test target: Debug or Release Returns: a list of failure objects and times for the test being processed """ outlines = [] failures = [] crash_or_timeout = False # Some test args, such as the image hash, may be added or changed on a # test-by-test basis. local_test_args = copy.copy(test_args) start_time = time.time() line = proc.stdout.readline() while line.rstrip() != "#EOF": # Make sure we haven't crashed. if line == '' and proc.poll() is not None: failures.append(test_failures.FailureCrash()) # This is hex code 0xc000001d, which is used for abrupt termination. # This happens if we hit ctrl+c from the prompt and we happen to # be waiting on the test_shell. # sdoyon: Not sure for which OS and in what circumstances the # above code is valid. What works for me under Linux to detect # ctrl+c is for the subprocess returncode to be negative SIGINT. And # that agrees with the subprocess documentation. if (-1073741510 == proc.returncode or -signal.SIGINT == proc.returncode): raise KeyboardInterrupt crash_or_timeout = True break # Don't include #URL lines in our output if line.startswith("#URL:"): test_string = test_info.uri.strip() url = line.rstrip()[5:] if url != test_string: logging.fatal("Test got out of sync:\n|%s|\n|%s|" % (url, test_string)) raise AssertionError("test out of sync") elif line.startswith("#MD5:"): local_test_args.hash = line.rstrip()[5:] elif line.startswith("#TEST_TIMED_OUT"): # Test timed out, but we still need to read until #EOF. crash_or_timeout = True failures.append(test_failures.FailureTimeout()) else: outlines.append(line) line = proc.stdout.readline() end_test_time = time.time() # Check the output and save the results. time_for_diffs = {} for test_type in test_types: start_diff_time = time.time() new_failures = test_type.CompareOutput(test_info.filename, proc, ''.join(outlines), local_test_args, target) # Don't add any more failures if we already have a crash or timeout, so # we don't double-report those tests. if not crash_or_timeout: failures.extend(new_failures) time_for_diffs[test_type.__class__.__name__] = ( time.time() - start_diff_time) total_time_for_all_diffs = time.time() - end_test_time test_run_time = end_test_time - start_time return TestStats(test_info.filename, failures, test_run_time, total_time_for_all_diffs, time_for_diffs) def StartTestShell(command, args): """Returns the process for a new test_shell started in layout-tests mode.""" cmd = [] # Hook for injecting valgrind or other runtime instrumentation, # used by e.g. tools/valgrind/valgrind_tests.py. wrapper = os.environ.get("BROWSER_WRAPPER", None) if wrapper != None: cmd += [wrapper] cmd += command + ['--layout-tests'] + args return subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) class TestStats: def __init__(self, filename, failures, test_run_time, total_time_for_all_diffs, time_for_diffs): self.filename = filename self.failures = failures self.test_run_time = test_run_time self.total_time_for_all_diffs = total_time_for_all_diffs self.time_for_diffs = time_for_diffs class SingleTestThread(threading.Thread): """Thread wrapper for running a single test file.""" def __init__(self, test_shell_command, shell_args, test_info, test_types, test_args, target): """ Args: test_info: Object containing the test filename, uri and timeout See TestShellThread for documentation of the remaining arguments. """ threading.Thread.__init__(self) self._command = test_shell_command self._shell_args = shell_args self._test_info = test_info self._test_types = test_types self._test_args = test_args self._target = target def run(self): proc = StartTestShell(self._command, self._shell_args + ["--time-out-ms=" + self._test_info.timeout, self._test_info.uri]) self._test_stats = ProcessOutput(proc, self._test_info, self._test_types, self._test_args, self._target) def GetTestStats(self): return self._test_stats class TestShellThread(threading.Thread): def __init__(self, filename_list_queue, test_shell_command, test_types, test_args, shell_args, options): """Initialize all the local state for this test shell thread. Args: filename_list_queue: A thread safe Queue class that contains lists of tuples of (filename, uri) pairs. test_shell_command: A list specifying the command+args for test_shell test_types: A list of TestType objects to run the test output against. test_args: A TestArguments object to pass to each TestType. shell_args: Any extra arguments to be passed to test_shell.exe. options: A property dictionary as produced by optparse. The command-line options should match those expected by run_webkit_tests; they are typically passed via the run_webkit_tests.TestRunner class. """ threading.Thread.__init__(self) self._filename_list_queue = filename_list_queue self._filename_list = [] self._test_shell_command = test_shell_command self._test_types = test_types self._test_args = test_args self._test_shell_proc = None self._shell_args = shell_args self._options = options self._failures = {} self._canceled = False self._exception_info = None self._directory_timing_stats = {} self._test_stats = [] # Current directory of tests we're running. self._current_dir = None # Number of tests in self._current_dir. self._num_tests_in_current_dir = None # Time at which we started running tests from self._current_dir. self._current_dir_start_time = None def GetFailures(self): """Returns a dictionary mapping test filename to a list of TestFailures.""" return self._failures def GetDirectoryTimingStats(self): """Returns a dictionary mapping test directory to a tuple of (number of tests in that directory, time to run the tests)""" return self._directory_timing_stats; def GetIndividualTestStats(self): """Returns a list of (test_filename, time_to_run_test, total_time_for_all_diffs, time_for_diffs) tuples.""" return self._test_stats def Cancel(self): """Set a flag telling this thread to quit.""" self._canceled = True def GetExceptionInfo(self): """If run() terminated on an uncaught exception, return it here ((type, value, traceback) tuple). Returns None if run() terminated normally. Meant to be called after joining this thread.""" return self._exception_info def run(self): """Delegate main work to a helper method and watch for uncaught exceptions.""" try: self._Run() except: # Save the exception for our caller to see. self._exception_info = sys.exc_info() # Re-raise it and die. raise def _Run(self): """Main work entry point of the thread. Basically we pull urls from the filename queue and run the tests until we run out of urls.""" batch_size = 0 batch_count = 0 if self._options.batch_size: try: batch_size = int(self._options.batch_size) except: logging.info("Ignoring invalid batch size '%s'" % self._options.batch_size) while True: if self._canceled: logging.info('Testing canceled') return if len(self._filename_list) is 0: if self._current_dir is not None: self._directory_timing_stats[self._current_dir] = \ (self._num_tests_in_current_dir, time.time() - self._current_dir_start_time) try: self._current_dir, self._filename_list = \ self._filename_list_queue.get_nowait() except Queue.Empty: self._KillTestShell() logging.debug("queue empty, quitting test shell thread") return self._num_tests_in_current_dir = len(self._filename_list) self._current_dir_start_time = time.time() test_info = self._filename_list.pop() # We have a url, run tests. batch_count += 1 if self._options.run_singly: failures = self._RunTestSingly(test_info) else: failures = self._RunTest(test_info) filename = test_info.filename if failures: # Check and kill test shell if we need too. if len([1 for f in failures if f.ShouldKillTestShell()]): self._KillTestShell() # Reset the batch count since the shell just bounced. batch_count = 0 # Print the error message(s). error_str = '\n'.join([' ' + f.Message() for f in failures]) logging.error("%s failed:\n%s" % (path_utils.RelativeTestFilename(filename), error_str)) # Group the errors for reporting. self._failures[filename] = failures else: logging.debug(path_utils.RelativeTestFilename(filename) + " passed") if batch_size > 0 and batch_count > batch_size: # Bounce the shell and reset count. self._KillTestShell() batch_count = 0 def _RunTestSingly(self, test_info): """Run a test in a separate thread, enforcing a hard time limit. Since we can only detect the termination of a thread, not any internal state or progress, we can only run per-test timeouts when running test files singly. Args: test_info: Object containing the test filename, uri and timeout Return: A list of TestFailure objects describing the error. """ worker = SingleTestThread(self._test_shell_command, self._shell_args, test_info, self._test_types, self._test_args, self._options.target) worker.start() # When we're running one test per test_shell process, we can enforce # a hard timeout. the test_shell watchdog uses 2.5x the timeout # We want to be larger than that. worker.join(int(test_info.timeout) * 3.0 / 1000.0) if worker.isAlive(): # If join() returned with the thread still running, the test_shell.exe is # completely hung and there's nothing more we can do with it. We have # to kill all the test_shells to free it up. If we're running more than # one test_shell thread, we'll end up killing the other test_shells too, # introducing spurious crashes. We accept that tradeoff in order to # avoid losing the rest of this thread's results. logging.error('Test thread hung: killing all test_shells') # PlatformUtility() wants a base_dir, but it doesn't matter here. platform_util = platform_utils.PlatformUtility('') platform_util.KillAllTestShells() try: stats = worker.GetTestStats() self._test_stats.append(stats) failures = stats.failures except AttributeError, e: failures = [] logging.error('Cannot get results of test: %s' % test_info.filename) return failures def _RunTest(self, test_info): """Run a single test file using a shared test_shell process. Args: test_info: Object containing the test filename, uri and timeout Return: A list of TestFailure objects describing the error. """ self._EnsureTestShellIsRunning() # Args to test_shell is a space-separated list of "uri timeout pixel_hash" # The timeout and pixel_hash are optional. The timeout is used if this # test has a custom timeout. The pixel_hash is used to avoid doing an image # dump if the checksums match, so it should be set to a blank value if we # are generating a new baseline. (Otherwise, an image from a previous run # will be copied into the baseline.) image_hash = test_info.image_hash if image_hash and self._test_args.new_baseline: image_hash = "" self._test_shell_proc.stdin.write(("%s %s %s\n" % (test_info.uri, test_info.timeout, image_hash))) # If the test shell is dead, the above may cause an IOError as we # try to write onto the broken pipe. If this is the first test for # this test shell process, than the test shell did not # successfully start. If this is not the first test, then the # previous tests have caused some kind of delayed crash. We don't # try to recover here. self._test_shell_proc.stdin.flush() stats = ProcessOutput(self._test_shell_proc, test_info, self._test_types, self._test_args, self._options.target) self._test_stats.append(stats) return stats.failures def _EnsureTestShellIsRunning(self): """Start the shared test shell, if it's not running. Not for use when running tests singly, since those each start a separate test shell in their own thread. """ if (not self._test_shell_proc or self._test_shell_proc.poll() is not None): self._test_shell_proc = StartTestShell(self._test_shell_command, self._shell_args) def _KillTestShell(self): """Kill the test shell process if it's running.""" if self._test_shell_proc: self._test_shell_proc.stdin.close() self._test_shell_proc.stdout.close() if self._test_shell_proc.stderr: self._test_shell_proc.stderr.close() if sys.platform not in ('win32', 'cygwin'): # Closing stdin/stdout/stderr hangs sometimes on OS X. subprocess.Popen(["kill", "-9", str(self._test_shell_proc.pid)]) self._test_shell_proc = None
en
0.84097
# Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. A Thread object for running the test shell and processing URLs from a shared queue. Each thread runs a separate instance of the test_shell binary and validates the output. When there are no more URLs to process in the shared queue, the thread exits. Receives the output from a test_shell process, subjects it to a number of tests, and returns a list of failure types the test produced. Args: proc: an active test_shell process test_info: Object containing the test filename, uri and timeout test_types: list of test types to subject the output to test_args: arguments to be passed to each test target: Debug or Release Returns: a list of failure objects and times for the test being processed # Some test args, such as the image hash, may be added or changed on a # test-by-test basis. # Make sure we haven't crashed. # This is hex code 0xc000001d, which is used for abrupt termination. # This happens if we hit ctrl+c from the prompt and we happen to # be waiting on the test_shell. # sdoyon: Not sure for which OS and in what circumstances the # above code is valid. What works for me under Linux to detect # ctrl+c is for the subprocess returncode to be negative SIGINT. And # that agrees with the subprocess documentation. # Don't include #URL lines in our output # Test timed out, but we still need to read until #EOF. # Check the output and save the results. # Don't add any more failures if we already have a crash or timeout, so # we don't double-report those tests. Returns the process for a new test_shell started in layout-tests mode. # Hook for injecting valgrind or other runtime instrumentation, # used by e.g. tools/valgrind/valgrind_tests.py. Thread wrapper for running a single test file. Args: test_info: Object containing the test filename, uri and timeout See TestShellThread for documentation of the remaining arguments. Initialize all the local state for this test shell thread. Args: filename_list_queue: A thread safe Queue class that contains lists of tuples of (filename, uri) pairs. test_shell_command: A list specifying the command+args for test_shell test_types: A list of TestType objects to run the test output against. test_args: A TestArguments object to pass to each TestType. shell_args: Any extra arguments to be passed to test_shell.exe. options: A property dictionary as produced by optparse. The command-line options should match those expected by run_webkit_tests; they are typically passed via the run_webkit_tests.TestRunner class. # Current directory of tests we're running. # Number of tests in self._current_dir. # Time at which we started running tests from self._current_dir. Returns a dictionary mapping test filename to a list of TestFailures. Returns a dictionary mapping test directory to a tuple of (number of tests in that directory, time to run the tests) Returns a list of (test_filename, time_to_run_test, total_time_for_all_diffs, time_for_diffs) tuples. Set a flag telling this thread to quit. If run() terminated on an uncaught exception, return it here ((type, value, traceback) tuple). Returns None if run() terminated normally. Meant to be called after joining this thread. Delegate main work to a helper method and watch for uncaught exceptions. # Save the exception for our caller to see. # Re-raise it and die. Main work entry point of the thread. Basically we pull urls from the filename queue and run the tests until we run out of urls. # We have a url, run tests. # Check and kill test shell if we need too. # Reset the batch count since the shell just bounced. # Print the error message(s). # Group the errors for reporting. # Bounce the shell and reset count. Run a test in a separate thread, enforcing a hard time limit. Since we can only detect the termination of a thread, not any internal state or progress, we can only run per-test timeouts when running test files singly. Args: test_info: Object containing the test filename, uri and timeout Return: A list of TestFailure objects describing the error. # When we're running one test per test_shell process, we can enforce # a hard timeout. the test_shell watchdog uses 2.5x the timeout # We want to be larger than that. # If join() returned with the thread still running, the test_shell.exe is # completely hung and there's nothing more we can do with it. We have # to kill all the test_shells to free it up. If we're running more than # one test_shell thread, we'll end up killing the other test_shells too, # introducing spurious crashes. We accept that tradeoff in order to # avoid losing the rest of this thread's results. # PlatformUtility() wants a base_dir, but it doesn't matter here. Run a single test file using a shared test_shell process. Args: test_info: Object containing the test filename, uri and timeout Return: A list of TestFailure objects describing the error. # Args to test_shell is a space-separated list of "uri timeout pixel_hash" # The timeout and pixel_hash are optional. The timeout is used if this # test has a custom timeout. The pixel_hash is used to avoid doing an image # dump if the checksums match, so it should be set to a blank value if we # are generating a new baseline. (Otherwise, an image from a previous run # will be copied into the baseline.) # If the test shell is dead, the above may cause an IOError as we # try to write onto the broken pipe. If this is the first test for # this test shell process, than the test shell did not # successfully start. If this is not the first test, then the # previous tests have caused some kind of delayed crash. We don't # try to recover here. Start the shared test shell, if it's not running. Not for use when running tests singly, since those each start a separate test shell in their own thread. Kill the test shell process if it's running. # Closing stdin/stdout/stderr hangs sometimes on OS X.
2.250755
2
notebook/dimention/4_prod/create_disang.py
yutakasi634/MDToolbox.jl
0
6613152
<gh_stars>0 #!/usr/bin/python # coding: utf-8 ############# define functions def print_lines(f, phi, psi): f.write("harmonic restraint\n") f.write(" &rst\n") f.write(" iat=5,7,9,15,\n") f.write(" r0=%f, k0=50.0,\n" % (phi)) f.write(" /\n") f.write(" &rst\n") f.write(" iat=7,9,15,17,\n") f.write(" r0=%f, k0=50.0,\n" % (psi)) f.write(" /\n") f.write("\n") ############# main phi = range(-180, 0, 15) psi = range(0, 180, 15) for i in phi: for j in psi: filename = "run_%d_%d.disang" % (i, j) print "writing %s..." % (filename) f = open(filename, 'w') print_lines(f, i, j) f.close()
#!/usr/bin/python # coding: utf-8 ############# define functions def print_lines(f, phi, psi): f.write("harmonic restraint\n") f.write(" &rst\n") f.write(" iat=5,7,9,15,\n") f.write(" r0=%f, k0=50.0,\n" % (phi)) f.write(" /\n") f.write(" &rst\n") f.write(" iat=7,9,15,17,\n") f.write(" r0=%f, k0=50.0,\n" % (psi)) f.write(" /\n") f.write("\n") ############# main phi = range(-180, 0, 15) psi = range(0, 180, 15) for i in phi: for j in psi: filename = "run_%d_%d.disang" % (i, j) print "writing %s..." % (filename) f = open(filename, 'w') print_lines(f, i, j) f.close()
de
0.2854
#!/usr/bin/python # coding: utf-8 ############# define functions ############# main
3.162639
3
home_password/config.py
RTBlanco/home_password
0
6613153
class Config: SQLALCHEMY_DATABASE_URI = 'sqlite:///db/test.db' SECRET_KEY = 'test'
class Config: SQLALCHEMY_DATABASE_URI = 'sqlite:///db/test.db' SECRET_KEY = 'test'
none
1
1.393061
1
ppyt/rules/__init__.py
yusukemurayama/ppytrading
4
6613154
<filename>ppyt/rules/__init__.py # coding: utf-8 import logging import abc from ppyt import const from ppyt.mixins import FinderMixin, ArgumentValidationMixin logger = logging.getLogger(__name__) class RuleBase(FinderMixin, ArgumentValidationMixin, metaclass=abc.ABCMeta): """ルール系(conditions, entry_rules, exit_rules)の基底クラスです。""" def __init__(self, *args, **kwds): """コンストラクタ ※このメソッドはオーバーライドせず、初期設定は_setupで実施してください。""" self._setup(*args, **kwds) def __str__(self): return self.__class__.__name__ @abc.abstractmethod def _setup(self, *args, **kwds): """初期設定をします。サブクラスでオーバーライドして使います。 Raises: ArgumentError: 引数チェックに引っかかった場合に発生します。 """ pass @abc.abstractmethod def _update(self): """インスタンス変数を更新します。サブクラスでオーバーライドして使います。""" pass def set_stock(self, stock): """銘柄情報を設定します。 Args: stock: 銘柄情報 """ self.stock = stock self._update() def get_date(self, idx): """指定したindexが示す日付を取得します。 Args: idx: 日付を決めるindex Returns: 日付(datetime.date型オブジェクト) """ return self.stock.get_date(idx) def get_price(self, idx, price_type=const.PRICE_TYPE_CLOSE): """指定したidxにおける各種の価格を取得します。 Args: idx: 日付を決めるindex price_type: 取得する価格種別 Returns: 価格 """ return self.stock.get_price(idx, price_type) def get_open_price(self, idx): """指定したidxにおける始値を取得します。 Args: idx: 日付を決めるindex Returns: 始値 """ return self.stock.get_open_price(idx) def get_high_price(self, idx): """指定したidxにおける高値を取得します。 Args: idx: 日付を決めるindex Returns: 高値 """ return self.stock.get_high_price(idx) def get_low_price(self, idx): """指定したidxにおける安値を取得します。 Args: idx: 日付を決めるindex Returns: 安値 """ return self.stock.get_low_price(idx) def get_close_price(self, idx): """指定したidxにおける終値を取得します。 Args: idx: 日付を決めるindex Returns: 終値 """ return self.stock.get_close_price(idx)
<filename>ppyt/rules/__init__.py # coding: utf-8 import logging import abc from ppyt import const from ppyt.mixins import FinderMixin, ArgumentValidationMixin logger = logging.getLogger(__name__) class RuleBase(FinderMixin, ArgumentValidationMixin, metaclass=abc.ABCMeta): """ルール系(conditions, entry_rules, exit_rules)の基底クラスです。""" def __init__(self, *args, **kwds): """コンストラクタ ※このメソッドはオーバーライドせず、初期設定は_setupで実施してください。""" self._setup(*args, **kwds) def __str__(self): return self.__class__.__name__ @abc.abstractmethod def _setup(self, *args, **kwds): """初期設定をします。サブクラスでオーバーライドして使います。 Raises: ArgumentError: 引数チェックに引っかかった場合に発生します。 """ pass @abc.abstractmethod def _update(self): """インスタンス変数を更新します。サブクラスでオーバーライドして使います。""" pass def set_stock(self, stock): """銘柄情報を設定します。 Args: stock: 銘柄情報 """ self.stock = stock self._update() def get_date(self, idx): """指定したindexが示す日付を取得します。 Args: idx: 日付を決めるindex Returns: 日付(datetime.date型オブジェクト) """ return self.stock.get_date(idx) def get_price(self, idx, price_type=const.PRICE_TYPE_CLOSE): """指定したidxにおける各種の価格を取得します。 Args: idx: 日付を決めるindex price_type: 取得する価格種別 Returns: 価格 """ return self.stock.get_price(idx, price_type) def get_open_price(self, idx): """指定したidxにおける始値を取得します。 Args: idx: 日付を決めるindex Returns: 始値 """ return self.stock.get_open_price(idx) def get_high_price(self, idx): """指定したidxにおける高値を取得します。 Args: idx: 日付を決めるindex Returns: 高値 """ return self.stock.get_high_price(idx) def get_low_price(self, idx): """指定したidxにおける安値を取得します。 Args: idx: 日付を決めるindex Returns: 安値 """ return self.stock.get_low_price(idx) def get_close_price(self, idx): """指定したidxにおける終値を取得します。 Args: idx: 日付を決めるindex Returns: 終値 """ return self.stock.get_close_price(idx)
ja
0.99963
# coding: utf-8 ルール系(conditions, entry_rules, exit_rules)の基底クラスです。 コンストラクタ ※このメソッドはオーバーライドせず、初期設定は_setupで実施してください。 初期設定をします。サブクラスでオーバーライドして使います。 Raises: ArgumentError: 引数チェックに引っかかった場合に発生します。 インスタンス変数を更新します。サブクラスでオーバーライドして使います。 銘柄情報を設定します。 Args: stock: 銘柄情報 指定したindexが示す日付を取得します。 Args: idx: 日付を決めるindex Returns: 日付(datetime.date型オブジェクト) 指定したidxにおける各種の価格を取得します。 Args: idx: 日付を決めるindex price_type: 取得する価格種別 Returns: 価格 指定したidxにおける始値を取得します。 Args: idx: 日付を決めるindex Returns: 始値 指定したidxにおける高値を取得します。 Args: idx: 日付を決めるindex Returns: 高値 指定したidxにおける安値を取得します。 Args: idx: 日付を決めるindex Returns: 安値 指定したidxにおける終値を取得します。 Args: idx: 日付を決めるindex Returns: 終値
2.507512
3
lib/schedule/__init__.py
cookieisland/cabernet
16
6613155
<gh_stars>10-100 import lib.schedule.schedule_html
import lib.schedule.schedule_html
none
1
1.024301
1
Lights/RPi_Pico/code/NeopixelPIO.py
IanSMoyes/SpiderPi
7
6613156
<gh_stars>1-10 """ MIT License Copyright (c) 2021 benevpi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" # Further development by <EMAIL> import array import time import board # from machine import Pin import rp2 @rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24) def ws2812_3(): T1 = 2 T2 = 5 T3 = 3 wrap_target() label("bitloop") out(x, 1) .side(0) [T3 - 1] jmp(not_x, "do_zero") .side(1) [T1 - 1] jmp("bitloop") .side(1) [T2 - 1] label("do_zero") nop() .side(0) [T2 - 1] wrap() @rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=32) def ws2812_4(): T1 = 2 T2 = 5 T3 = 3 wrap_target() label("bitloop") out(x, 1) .side(0) [T3 - 1] jmp(not_x, "do_zero") .side(1) [T1 - 1] jmp("bitloop") .side(1) [T2 - 1] label("do_zero") nop() .side(0) [T2 - 1] wrap() #delay here is the reset time. You need a pause to reset the LED strip back to the initial LED #however, if you have quite a bit of processing to do before the next time you update the strip #you could put in delay=0 (or a lower delay) class ws2812b: def __init__(self, num_leds, state_machine, pin, colour_order="RGB", delay=0.001, brightness = 1, autoshow = True): self.num_leds = num_leds self.pixels = array.array("I", [0 for _ in range(num_leds)]) self.red_shift = colour_order.index("R") * 8 self.green_shift = colour_order.index("G") * 8 self.blue_shift = colour_order.index("B") * 8 self.white_shift = colour_order.find("W") * 8 # Use the "find" method in case the Neopixels are 3 colour if self.white_shift >= 0: self.sm = rp2.StateMachine(state_machine, ws2812_4, freq=8000000, sideset_base=board.pin) else: self.sm = rp2.StateMachine(state_machine, ws2812_3, freq=8000000, sideset_base=board.pin) """ if self.white_shift >= 0: self.sm = rp2.StateMachine(state_machine, ws2812_4, freq=8000000, sideset_base=Pin(pin)) else: self.sm = rp2.StateMachine(state_machine, ws2812_3, freq=8000000, sideset_base=Pin.pin)) """ self.sm.active(1) self.delay = delay self.brightness = brightness self.autoshow = autoshow # Set the overall value to adjust brightness when updating leds def set_brightness(self, brightness = None): if brightness == None: return self.brightness else: if (brightness < 0): brightness = 0 if (brightness > 1): brightness = 1 self.brightness = brightness if self.autoshow: self.show() # Create a gradient with two RGB(W) colors between "pixel1" and "pixel2" (inclusive) def set_pixel_line_gradient(self, pixel1, pixel2, colour1, colour2): right_pixel = max(pixel1, pixel2) left_pixel = min(pixel1, pixel2) for i in range(right_pixel - left_pixel + 1): fraction = i / (right_pixel - left_pixel) colour[0] = round((colour2[0] - colour1[0]) * fraction + colour1[0]) colour[1] = round((colour2[1] - colour1[1]) * fraction + colour1[1]) colour[2] = round((colour2[2] - colour1[2]) * fraction + colour1[2]) if self.white_shift >= 0: colour[3] = round((colour2[3] - colour1[3]) * fraction + colour1[3]) self.set_pixel(left_pixel + i, colour) # Set an array of pixels starting from "pixel1" to "pixel2" to the desired color def set_pixel_line(self, pixel1, pixel2, colour): for i in range(pixel1, pixel2+1): self.set_pixel(i, colour) # Set an individual pixel def set_pixel(self, pixel_num, colour): # Adjust color values with brightnesslevel red = round(colour[0] * self.brightness) green = round(colour[1] * self.brightness) blue = int(colour[2] * self.brightness) if self.white_shift >= 0: white = int(colour[3] * self.brightness) self.pixels[pixel_num] = white << self.white_shift | blue << self.blue_shift | green << self.green_shift | red << self.red_shift else: self.pixels[pixel_num] = blue << self.blue_shift | green << self.green_shift | red << self.red_shift if autoshow: self.show() # rotate x pixels to the left def rotate_left(self, num_of_pixels): if num_of_pixels == None: num_of_pixels = 1 self.pixels = self.pixels[num_of_pixels:] + self.pixels[:num_of_pixels] if self.autoshow: self.show() # rotate x pixels to the right def rotate_right(self, num_of_pixels): if num_of_pixels == None: num_of_pixels = 1 self.rotate_left(self, num_of_pixels * -1) if self.autoshow: self.show() def fill(self, colour): for i in range(self.num_leds): self.set_pixel(i, colour) time.sleep(self.delay) def show(self): for i in range(self.num_leds): if self.white_shift >= 0: self.sm.put(self.pixels[i]) else: self.sm.put(self.pixels[i],8) time.sleep(self.delay)
""" MIT License Copyright (c) 2021 benevpi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" # Further development by <EMAIL> import array import time import board # from machine import Pin import rp2 @rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24) def ws2812_3(): T1 = 2 T2 = 5 T3 = 3 wrap_target() label("bitloop") out(x, 1) .side(0) [T3 - 1] jmp(not_x, "do_zero") .side(1) [T1 - 1] jmp("bitloop") .side(1) [T2 - 1] label("do_zero") nop() .side(0) [T2 - 1] wrap() @rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=32) def ws2812_4(): T1 = 2 T2 = 5 T3 = 3 wrap_target() label("bitloop") out(x, 1) .side(0) [T3 - 1] jmp(not_x, "do_zero") .side(1) [T1 - 1] jmp("bitloop") .side(1) [T2 - 1] label("do_zero") nop() .side(0) [T2 - 1] wrap() #delay here is the reset time. You need a pause to reset the LED strip back to the initial LED #however, if you have quite a bit of processing to do before the next time you update the strip #you could put in delay=0 (or a lower delay) class ws2812b: def __init__(self, num_leds, state_machine, pin, colour_order="RGB", delay=0.001, brightness = 1, autoshow = True): self.num_leds = num_leds self.pixels = array.array("I", [0 for _ in range(num_leds)]) self.red_shift = colour_order.index("R") * 8 self.green_shift = colour_order.index("G") * 8 self.blue_shift = colour_order.index("B") * 8 self.white_shift = colour_order.find("W") * 8 # Use the "find" method in case the Neopixels are 3 colour if self.white_shift >= 0: self.sm = rp2.StateMachine(state_machine, ws2812_4, freq=8000000, sideset_base=board.pin) else: self.sm = rp2.StateMachine(state_machine, ws2812_3, freq=8000000, sideset_base=board.pin) """ if self.white_shift >= 0: self.sm = rp2.StateMachine(state_machine, ws2812_4, freq=8000000, sideset_base=Pin(pin)) else: self.sm = rp2.StateMachine(state_machine, ws2812_3, freq=8000000, sideset_base=Pin.pin)) """ self.sm.active(1) self.delay = delay self.brightness = brightness self.autoshow = autoshow # Set the overall value to adjust brightness when updating leds def set_brightness(self, brightness = None): if brightness == None: return self.brightness else: if (brightness < 0): brightness = 0 if (brightness > 1): brightness = 1 self.brightness = brightness if self.autoshow: self.show() # Create a gradient with two RGB(W) colors between "pixel1" and "pixel2" (inclusive) def set_pixel_line_gradient(self, pixel1, pixel2, colour1, colour2): right_pixel = max(pixel1, pixel2) left_pixel = min(pixel1, pixel2) for i in range(right_pixel - left_pixel + 1): fraction = i / (right_pixel - left_pixel) colour[0] = round((colour2[0] - colour1[0]) * fraction + colour1[0]) colour[1] = round((colour2[1] - colour1[1]) * fraction + colour1[1]) colour[2] = round((colour2[2] - colour1[2]) * fraction + colour1[2]) if self.white_shift >= 0: colour[3] = round((colour2[3] - colour1[3]) * fraction + colour1[3]) self.set_pixel(left_pixel + i, colour) # Set an array of pixels starting from "pixel1" to "pixel2" to the desired color def set_pixel_line(self, pixel1, pixel2, colour): for i in range(pixel1, pixel2+1): self.set_pixel(i, colour) # Set an individual pixel def set_pixel(self, pixel_num, colour): # Adjust color values with brightnesslevel red = round(colour[0] * self.brightness) green = round(colour[1] * self.brightness) blue = int(colour[2] * self.brightness) if self.white_shift >= 0: white = int(colour[3] * self.brightness) self.pixels[pixel_num] = white << self.white_shift | blue << self.blue_shift | green << self.green_shift | red << self.red_shift else: self.pixels[pixel_num] = blue << self.blue_shift | green << self.green_shift | red << self.red_shift if autoshow: self.show() # rotate x pixels to the left def rotate_left(self, num_of_pixels): if num_of_pixels == None: num_of_pixels = 1 self.pixels = self.pixels[num_of_pixels:] + self.pixels[:num_of_pixels] if self.autoshow: self.show() # rotate x pixels to the right def rotate_right(self, num_of_pixels): if num_of_pixels == None: num_of_pixels = 1 self.rotate_left(self, num_of_pixels * -1) if self.autoshow: self.show() def fill(self, colour): for i in range(self.num_leds): self.set_pixel(i, colour) time.sleep(self.delay) def show(self): for i in range(self.num_leds): if self.white_shift >= 0: self.sm.put(self.pixels[i]) else: self.sm.put(self.pixels[i],8) time.sleep(self.delay)
en
0.775467
MIT License Copyright (c) 2021 benevpi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Further development by <EMAIL> # from machine import Pin #delay here is the reset time. You need a pause to reset the LED strip back to the initial LED #however, if you have quite a bit of processing to do before the next time you update the strip #you could put in delay=0 (or a lower delay) # Use the "find" method in case the Neopixels are 3 colour if self.white_shift >= 0: self.sm = rp2.StateMachine(state_machine, ws2812_4, freq=8000000, sideset_base=Pin(pin)) else: self.sm = rp2.StateMachine(state_machine, ws2812_3, freq=8000000, sideset_base=Pin.pin)) # Set the overall value to adjust brightness when updating leds # Create a gradient with two RGB(W) colors between "pixel1" and "pixel2" (inclusive) # Set an array of pixels starting from "pixel1" to "pixel2" to the desired color # Set an individual pixel # Adjust color values with brightnesslevel # rotate x pixels to the left # rotate x pixels to the right
1.886429
2
lib/realtimeclock.py
ubirch/ubirch-elevate-application
0
6613157
import utime as time import machine NTP_SERVER_DEFAULT = "192.168.127.12" NTP_SERVER_BACKUP = "172.16.31.10" SYNC_INTERVAL_DEFAULT = 60 * 60 * 12 # sec * min. * hours rtc = machine.RTC() def enable_time_sync(server=NTP_SERVER_DEFAULT, interval=SYNC_INTERVAL_DEFAULT): rtc.ntp_sync(server, interval) def disable_time_sync(): rtc.ntp_sync(None) def wait_for_sync(timeout=60, print_dots=True): i = 0 while not rtc.synced(): if print_dots: print(".", end="") time.sleep(1.0) i += 1 if i > timeout: raise Exception("timeout when waiting for time sync") return def board_time(): return rtc.now() def board_time_valid(): return board_time()[0] >= 2020
import utime as time import machine NTP_SERVER_DEFAULT = "192.168.127.12" NTP_SERVER_BACKUP = "172.16.31.10" SYNC_INTERVAL_DEFAULT = 60 * 60 * 12 # sec * min. * hours rtc = machine.RTC() def enable_time_sync(server=NTP_SERVER_DEFAULT, interval=SYNC_INTERVAL_DEFAULT): rtc.ntp_sync(server, interval) def disable_time_sync(): rtc.ntp_sync(None) def wait_for_sync(timeout=60, print_dots=True): i = 0 while not rtc.synced(): if print_dots: print(".", end="") time.sleep(1.0) i += 1 if i > timeout: raise Exception("timeout when waiting for time sync") return def board_time(): return rtc.now() def board_time_valid(): return board_time()[0] >= 2020
eo
0.233668
# sec * min. * hours
3.072068
3
nntools/utils/scheduler.py
ClementPla/NNTools
0
6613158
import torch def pass_args(*args): return args def block_args(*args): pass from collections import namedtuple Scheduler = namedtuple('Scheduler', ['func', 'callback']) SCHEDULERS = { 'LambdaLR': Scheduler(torch.optim.lr_scheduler.LambdaLR, block_args), 'MultiplicativeLR': Scheduler(torch.optim.lr_scheduler.MultiplicativeLR, block_args), 'StepLR': Scheduler(torch.optim.lr_scheduler.StepLR, block_args), 'MultiStepLR': Scheduler(torch.optim.lr_scheduler.MultiStepLR, block_args), 'ExponentialLR': Scheduler(torch.optim.lr_scheduler.ExponentialLR, block_args), 'CosineAnnealingLR': Scheduler(torch.optim.lr_scheduler.CosineAnnealingLR, block_args), 'ReduceLROnPlateau': Scheduler(torch.optim.lr_scheduler.ReduceLROnPlateau, pass_args), 'CyclicLR': Scheduler(torch.optim.lr_scheduler.CyclicLR, block_args), 'OneCycleLR': Scheduler(torch.optim.lr_scheduler.OneCycleLR, block_args), 'CosineAnnealingWarmRestarts': Scheduler(torch.optim.lr_scheduler.CosineAnnealingWarmRestarts, block_args) }
import torch def pass_args(*args): return args def block_args(*args): pass from collections import namedtuple Scheduler = namedtuple('Scheduler', ['func', 'callback']) SCHEDULERS = { 'LambdaLR': Scheduler(torch.optim.lr_scheduler.LambdaLR, block_args), 'MultiplicativeLR': Scheduler(torch.optim.lr_scheduler.MultiplicativeLR, block_args), 'StepLR': Scheduler(torch.optim.lr_scheduler.StepLR, block_args), 'MultiStepLR': Scheduler(torch.optim.lr_scheduler.MultiStepLR, block_args), 'ExponentialLR': Scheduler(torch.optim.lr_scheduler.ExponentialLR, block_args), 'CosineAnnealingLR': Scheduler(torch.optim.lr_scheduler.CosineAnnealingLR, block_args), 'ReduceLROnPlateau': Scheduler(torch.optim.lr_scheduler.ReduceLROnPlateau, pass_args), 'CyclicLR': Scheduler(torch.optim.lr_scheduler.CyclicLR, block_args), 'OneCycleLR': Scheduler(torch.optim.lr_scheduler.OneCycleLR, block_args), 'CosineAnnealingWarmRestarts': Scheduler(torch.optim.lr_scheduler.CosineAnnealingWarmRestarts, block_args) }
none
1
2.689165
3
module_2/server.py
Sukhrobjon/career-lab
0
6613159
<filename>module_2/server.py def server_time_check(task_config, task_times): """Determines how many tasks can be done in a given number of minutes NOTE: tasks must be done in a given order! Args: task_config(list): number of tasks and the max total execution time task_times(list): times takes for each task submitted Returns: number of tasks(int): number of tasks can be done in a given time """ # converting user input into lists # comment this out if the input is given by user on terminal # task_config = task_config.split() # task_times = task_times.split() max_min = int(task_config[1]) total_task_mins = 0 tasks = [] for index, task in enumerate(task_times, 1): total_task_mins += int(task) tasks.append(task) if total_task_mins <= max_min: continue else: print(f"index: {index-1}") print(f"Tasks before removing last item: {tasks}") tasks.pop() print(f"Tasks after removing last item: {tasks}") return # task config is [num of tasks, max time to be spent on] task_config = [10, 200] task_times = [20, 70, 40, 30, 10, 27, 2, 3, 10, 5] server_time_check(task_config, task_times)
<filename>module_2/server.py def server_time_check(task_config, task_times): """Determines how many tasks can be done in a given number of minutes NOTE: tasks must be done in a given order! Args: task_config(list): number of tasks and the max total execution time task_times(list): times takes for each task submitted Returns: number of tasks(int): number of tasks can be done in a given time """ # converting user input into lists # comment this out if the input is given by user on terminal # task_config = task_config.split() # task_times = task_times.split() max_min = int(task_config[1]) total_task_mins = 0 tasks = [] for index, task in enumerate(task_times, 1): total_task_mins += int(task) tasks.append(task) if total_task_mins <= max_min: continue else: print(f"index: {index-1}") print(f"Tasks before removing last item: {tasks}") tasks.pop() print(f"Tasks after removing last item: {tasks}") return # task config is [num of tasks, max time to be spent on] task_config = [10, 200] task_times = [20, 70, 40, 30, 10, 27, 2, 3, 10, 5] server_time_check(task_config, task_times)
en
0.788853
Determines how many tasks can be done in a given number of minutes NOTE: tasks must be done in a given order! Args: task_config(list): number of tasks and the max total execution time task_times(list): times takes for each task submitted Returns: number of tasks(int): number of tasks can be done in a given time # converting user input into lists # comment this out if the input is given by user on terminal # task_config = task_config.split() # task_times = task_times.split() # task config is [num of tasks, max time to be spent on]
4.181885
4
lab3/api.py
mit-pdos/6.S060-labs
10
6613160
#!/usr/bin/env python3 from enum import IntEnum, auto, unique import codec from util import auto_str """ A common API between the client and the server. """ @unique class Errcode(IntEnum): UNKNOWN = auto() USER_ALREADY_EXISTS = auto() LOGIN_FAILED = auto() INVALID_TOKEN = auto() VERSION_TOO_LOW = auto() VERSION_TOO_HIGH = auto() PHOTO_DOES_NOT_EXIST = auto() CONTACT_BOOK_DOES_NOT_EXIST = auto() ALBUM_DOES_NOT_EXIST = auto() @unique class OperationCode(IntEnum): REGISTER = auto() PUT_PHOTO = auto() @auto_str class PhotoAlbum: def __init__(self, name, photos, owner, friends, metadata=None): self.name = name self.photos = photos self.owner = owner self.friends = friends try: encoder = codec.Encoding() encoder.add_obj(metadata) except TypeError: raise TypeError("Album's metadata should be encodable") self.metadata = metadata def add_photo(self, photo): self.photos.append(photo) def add_friend(self, friend): self.friends[friend.username] = friend def remove_friend(self, name_friend): del self.friends[name_friend] def is_owner(self, username): return username == self.owner @auto_str class RequestError: """An error returned by a request, identified with an error code and extra information.""" def __init__(self, error_code, info): self.error_code = int(error_code) self.info = info @auto_str class Request: def __init__(self, username, token): self.username = username self.token = token @auto_str class PushRequest(Request): def __init__(self, username, token, encoded_log_entry): if type(encoded_log_entry) is not codec.Encoding: raise TypeError("encoded_log_entry must be Encoding") Request.__init__(self, username, token) self.encoded_log_entry = encoded_log_entry @auto_str class RegisterRequest(): def __init__(self, username, auth_secret, encoded_log_entry): if type(encoded_log_entry) is not codec.Encoding: raise TypeError("encoded_log_entry must be Encoding") self.username = username self.auth_secret = auth_secret self.encoded_log_entry = encoded_log_entry @auto_str class RegisterResponse: """The register response is composed of an error code (indicating if the registration was successful and a session token""" def __init__(self, error, token): self.token = token self.error = error @auto_str class LoginRequest: def __init__(self, username, auth_secret): self.username = username self.auth_secret = auth_secret @auto_str class LoginResponse: """The login response is composed of an error code (indicating if the registration was successful and a session token""" def __init__(self, error, token): self.token = token self.error = error @auto_str class UpdatePublicProfileRequest(Request): def __init__(self, username, token, public_profile): super().__init__(username, token) self.public_profile = public_profile @auto_str class UpdatePublicProfileResponse(): def __init__(self, error): self.error = error @auto_str class GetFriendPublicProfileRequest(Request): def __init__(self, username, token, friend_username): super().__init__(username, token) self.friend_username = friend_username @auto_str class GetFriendPublicProfileResponse(): def __init__(self, error, public_profile): self.error = error self.public_profile = public_profile @auto_str class PutPhotoRequest(PushRequest): def __init__(self, username, token, photo_blob, photo_id, encoded_log_entry): super().__init__(username, token, encoded_log_entry) self.photo_blob = photo_blob self.photo_id = photo_id @auto_str class PutPhotoResponse: def __init__(self, error): self.error = error @auto_str class GetPhotoRequest(Request): def __init__(self, username, token, photo_id): super().__init__(username, token) self.photo_id = photo_id @auto_str class GetPhotoResponse: def __init__(self, error, photo_blob): self.error = error self.photo_blob = photo_blob @auto_str class SynchronizeRequest(Request): def __init__(self, username, token, min_version_number): super().__init__(username, token) self.min_version_number = min_version_number @auto_str class SynchronizeResponse(): def __init__(self, error, encoded_log_entries): self.error = error self.encoded_log_entries = encoded_log_entries @auto_str class UploadAlbumRequest(Request): def __init__(self, username, token, album): super().__init__(username, token) self.album = album @auto_str class UploadAlbumResponse(): def __init__(self, error): self.error = error @auto_str class GetAlbumRequest(Request): def __init__(self, username, token, name_album): super().__init__(username, token) self.name_album = name_album @auto_str class GetAlbumResponse(): def __init__(self, error, album): self.error = error self.album = album
#!/usr/bin/env python3 from enum import IntEnum, auto, unique import codec from util import auto_str """ A common API between the client and the server. """ @unique class Errcode(IntEnum): UNKNOWN = auto() USER_ALREADY_EXISTS = auto() LOGIN_FAILED = auto() INVALID_TOKEN = auto() VERSION_TOO_LOW = auto() VERSION_TOO_HIGH = auto() PHOTO_DOES_NOT_EXIST = auto() CONTACT_BOOK_DOES_NOT_EXIST = auto() ALBUM_DOES_NOT_EXIST = auto() @unique class OperationCode(IntEnum): REGISTER = auto() PUT_PHOTO = auto() @auto_str class PhotoAlbum: def __init__(self, name, photos, owner, friends, metadata=None): self.name = name self.photos = photos self.owner = owner self.friends = friends try: encoder = codec.Encoding() encoder.add_obj(metadata) except TypeError: raise TypeError("Album's metadata should be encodable") self.metadata = metadata def add_photo(self, photo): self.photos.append(photo) def add_friend(self, friend): self.friends[friend.username] = friend def remove_friend(self, name_friend): del self.friends[name_friend] def is_owner(self, username): return username == self.owner @auto_str class RequestError: """An error returned by a request, identified with an error code and extra information.""" def __init__(self, error_code, info): self.error_code = int(error_code) self.info = info @auto_str class Request: def __init__(self, username, token): self.username = username self.token = token @auto_str class PushRequest(Request): def __init__(self, username, token, encoded_log_entry): if type(encoded_log_entry) is not codec.Encoding: raise TypeError("encoded_log_entry must be Encoding") Request.__init__(self, username, token) self.encoded_log_entry = encoded_log_entry @auto_str class RegisterRequest(): def __init__(self, username, auth_secret, encoded_log_entry): if type(encoded_log_entry) is not codec.Encoding: raise TypeError("encoded_log_entry must be Encoding") self.username = username self.auth_secret = auth_secret self.encoded_log_entry = encoded_log_entry @auto_str class RegisterResponse: """The register response is composed of an error code (indicating if the registration was successful and a session token""" def __init__(self, error, token): self.token = token self.error = error @auto_str class LoginRequest: def __init__(self, username, auth_secret): self.username = username self.auth_secret = auth_secret @auto_str class LoginResponse: """The login response is composed of an error code (indicating if the registration was successful and a session token""" def __init__(self, error, token): self.token = token self.error = error @auto_str class UpdatePublicProfileRequest(Request): def __init__(self, username, token, public_profile): super().__init__(username, token) self.public_profile = public_profile @auto_str class UpdatePublicProfileResponse(): def __init__(self, error): self.error = error @auto_str class GetFriendPublicProfileRequest(Request): def __init__(self, username, token, friend_username): super().__init__(username, token) self.friend_username = friend_username @auto_str class GetFriendPublicProfileResponse(): def __init__(self, error, public_profile): self.error = error self.public_profile = public_profile @auto_str class PutPhotoRequest(PushRequest): def __init__(self, username, token, photo_blob, photo_id, encoded_log_entry): super().__init__(username, token, encoded_log_entry) self.photo_blob = photo_blob self.photo_id = photo_id @auto_str class PutPhotoResponse: def __init__(self, error): self.error = error @auto_str class GetPhotoRequest(Request): def __init__(self, username, token, photo_id): super().__init__(username, token) self.photo_id = photo_id @auto_str class GetPhotoResponse: def __init__(self, error, photo_blob): self.error = error self.photo_blob = photo_blob @auto_str class SynchronizeRequest(Request): def __init__(self, username, token, min_version_number): super().__init__(username, token) self.min_version_number = min_version_number @auto_str class SynchronizeResponse(): def __init__(self, error, encoded_log_entries): self.error = error self.encoded_log_entries = encoded_log_entries @auto_str class UploadAlbumRequest(Request): def __init__(self, username, token, album): super().__init__(username, token) self.album = album @auto_str class UploadAlbumResponse(): def __init__(self, error): self.error = error @auto_str class GetAlbumRequest(Request): def __init__(self, username, token, name_album): super().__init__(username, token) self.name_album = name_album @auto_str class GetAlbumResponse(): def __init__(self, error, album): self.error = error self.album = album
en
0.935619
#!/usr/bin/env python3 A common API between the client and the server. An error returned by a request, identified with an error code and extra information. The register response is composed of an error code (indicating if the registration was successful and a session token The login response is composed of an error code (indicating if the registration was successful and a session token
2.737425
3
gears/compilers/base.py
gears/gears
9
6613161
<reponame>gears/gears # -*- coding: utf-8 -*- from ..asset_handler import BaseAssetHandler, ExecMixin class BaseCompiler(BaseAssetHandler): """Base class for all asset compilers. Subclass's :meth:`__call__` method must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. """ #: MIME type of the asset source code after compiling. result_mimetype = None @classmethod def as_handler(cls, **initkwargs): handler = super(BaseCompiler, cls).as_handler(**initkwargs) handler.result_mimetype = cls.result_mimetype return handler class ExecCompiler(BaseCompiler, ExecMixin): def __init__(self, executable=None, **kwargs): if executable is not None: self.executable = executable def __call__(self, asset): asset.processed_source = self.run(asset.processed_source)
# -*- coding: utf-8 -*- from ..asset_handler import BaseAssetHandler, ExecMixin class BaseCompiler(BaseAssetHandler): """Base class for all asset compilers. Subclass's :meth:`__call__` method must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. """ #: MIME type of the asset source code after compiling. result_mimetype = None @classmethod def as_handler(cls, **initkwargs): handler = super(BaseCompiler, cls).as_handler(**initkwargs) handler.result_mimetype = cls.result_mimetype return handler class ExecCompiler(BaseCompiler, ExecMixin): def __init__(self, executable=None, **kwargs): if executable is not None: self.executable = executable def __call__(self, asset): asset.processed_source = self.run(asset.processed_source)
en
0.767301
# -*- coding: utf-8 -*- Base class for all asset compilers. Subclass's :meth:`__call__` method must change asset's :attr:`~gears.assets.Asset.processed_source` attribute. #: MIME type of the asset source code after compiling.
2.221374
2
python/fibonacci/fibonacci.py
DavidMellul/Projets
1
6613162
<reponame>DavidMellul/Projets a = 0 b = 1 c = 0 n = int(input("Nombre de termes : ")) for i in range (1, n+1): c = a+b b = a a= c print(c)
a = 0 b = 1 c = 0 n = int(input("Nombre de termes : ")) for i in range (1, n+1): c = a+b b = a a= c print(c)
none
1
3.727144
4
src/kgmk/etyping/login.py
kagemeka/python
0
6613163
import dataclasses import typing import selenium from \ selenium.webdriver \ .common.by \ import ( By, ) @dataclasses.dataclass class LoginFormID(): email: str = 'mail' passwd: str = 'password' submit: str = 'login_btn' @dataclasses.dataclass class Auth(): email: str passwd: str class Login(): def __call__( self, driver: ( selenium .webdriver .remote .webdriver .WebDriver ), ) -> typing.NoReturn: auth = self.__auth ids = LoginFormID() driver.find_element( by=By.ID, value=ids.email, ).send_keys(auth.email) driver.find_element( by=By.ID, value=ids.passwd, ).send_keys(auth.passwd) driver.find_element( by=By.ID, value=ids.submit, ).click() def __init__( self, auth: Auth, ): self.__auth = auth
import dataclasses import typing import selenium from \ selenium.webdriver \ .common.by \ import ( By, ) @dataclasses.dataclass class LoginFormID(): email: str = 'mail' passwd: str = 'password' submit: str = 'login_btn' @dataclasses.dataclass class Auth(): email: str passwd: str class Login(): def __call__( self, driver: ( selenium .webdriver .remote .webdriver .WebDriver ), ) -> typing.NoReturn: auth = self.__auth ids = LoginFormID() driver.find_element( by=By.ID, value=ids.email, ).send_keys(auth.email) driver.find_element( by=By.ID, value=ids.passwd, ).send_keys(auth.passwd) driver.find_element( by=By.ID, value=ids.submit, ).click() def __init__( self, auth: Auth, ): self.__auth = auth
none
1
2.776981
3
scripts/ignore_diff.py
abrachet/llvm-premerge-checks
0
6613164
#!/usr/bin/env python3 # Copyright 2020 Google LLC # # Licensed under the the Apache License v2.0 with LLVM Exceptions (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://llvm.org/LICENSE.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re import sys import pathspec # Takes an output of git diff and removes files ignored by patten specified by ignore file. def main(): argv = sys.argv[1:] if not argv: print("Please provide a path to .ignore file.") sys.exit(1) ignore = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, open(argv[0], 'r').readlines()) good = True for line in sys.stdin: match = re.search(r'^diff --git a/(.*) b/(.*)$', line) if match: good = not (ignore.match_file(match.group(1)) and ignore.match_file(match.group(2))) if not good: continue sys.stdout.write(line) if __name__ == "__main__": main()
#!/usr/bin/env python3 # Copyright 2020 Google LLC # # Licensed under the the Apache License v2.0 with LLVM Exceptions (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://llvm.org/LICENSE.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re import sys import pathspec # Takes an output of git diff and removes files ignored by patten specified by ignore file. def main(): argv = sys.argv[1:] if not argv: print("Please provide a path to .ignore file.") sys.exit(1) ignore = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, open(argv[0], 'r').readlines()) good = True for line in sys.stdin: match = re.search(r'^diff --git a/(.*) b/(.*)$', line) if match: good = not (ignore.match_file(match.group(1)) and ignore.match_file(match.group(2))) if not good: continue sys.stdout.write(line) if __name__ == "__main__": main()
en
0.863391
#!/usr/bin/env python3 # Copyright 2020 Google LLC # # Licensed under the the Apache License v2.0 with LLVM Exceptions (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://llvm.org/LICENSE.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Takes an output of git diff and removes files ignored by patten specified by ignore file.
2.56975
3
tests/engine/test_config.py
pronovic/vplan
0
6613165
<reponame>pronovic/vplan # -*- coding: utf-8 -*- # vim: set ft=python ts=4 sw=4 expandtab: import os from unittest.mock import patch import pytest from vplan.engine.config import config, reset from vplan.engine.exception import EngineError def fixture(filename: str) -> str: return os.path.join(os.path.dirname(__file__), "fixtures", "config", filename) APPLICATION_YAML = fixture("application.yaml") class TestConfig: @pytest.fixture(autouse=True) def cleanup(self): """Reset configuration before and after tests.""" reset() yield reset() @patch.dict(os.environ, {"VPLAN_CONFIG_PATH": APPLICATION_YAML, "VPLAN_DATABASE_PATH": ".runtime/db"}, clear=True) def test_config_env(self): result = config() TestConfig._validate_config(result) @patch.dict(os.environ, {"VPLAN_DATABASE_PATH": ".runtime/db"}, clear=True) def test_config_path(self): result = config(config_path=APPLICATION_YAML) TestConfig._validate_config(result) @patch.dict(os.environ, {"VPLAN_DATABASE_PATH": ".runtime/db"}, clear=True) def test_config_env_no_var(self): with pytest.raises(EngineError, match=r"Server is not properly configured, no \$VPLAN_CONFIG_PATH found"): config() @patch.dict(os.environ, {"VPLAN_CONFIG_PATH": "bogus", "VPLAN_DATABASE_PATH": ".runtime/db"}, clear=True) def test_config_env_not_found(self): with pytest.raises(EngineError, match=r"Server configuration is not readable: bogus"): config() @staticmethod def _validate_config(result): assert result.database_dir == ".runtime/db" assert result.database_url == "sqlite+pysqlite:///.runtime/db/vplan.sqlite" assert result.database_log_level == "DEBUG" assert result.smartthings.base_api_url == "https://api.smartthings.com" assert result.scheduler.database_url == "sqlite+pysqlite:///.runtime/db/jobs.sqlite" assert result.scheduler.daily_job.jitter_sec == 300 assert result.scheduler.daily_job.misfire_grace_sec == 1800 assert result.retry.max_attempts == 4 assert result.retry.min_sec == 1 assert result.retry.max_sec == 5
# -*- coding: utf-8 -*- # vim: set ft=python ts=4 sw=4 expandtab: import os from unittest.mock import patch import pytest from vplan.engine.config import config, reset from vplan.engine.exception import EngineError def fixture(filename: str) -> str: return os.path.join(os.path.dirname(__file__), "fixtures", "config", filename) APPLICATION_YAML = fixture("application.yaml") class TestConfig: @pytest.fixture(autouse=True) def cleanup(self): """Reset configuration before and after tests.""" reset() yield reset() @patch.dict(os.environ, {"VPLAN_CONFIG_PATH": APPLICATION_YAML, "VPLAN_DATABASE_PATH": ".runtime/db"}, clear=True) def test_config_env(self): result = config() TestConfig._validate_config(result) @patch.dict(os.environ, {"VPLAN_DATABASE_PATH": ".runtime/db"}, clear=True) def test_config_path(self): result = config(config_path=APPLICATION_YAML) TestConfig._validate_config(result) @patch.dict(os.environ, {"VPLAN_DATABASE_PATH": ".runtime/db"}, clear=True) def test_config_env_no_var(self): with pytest.raises(EngineError, match=r"Server is not properly configured, no \$VPLAN_CONFIG_PATH found"): config() @patch.dict(os.environ, {"VPLAN_CONFIG_PATH": "bogus", "VPLAN_DATABASE_PATH": ".runtime/db"}, clear=True) def test_config_env_not_found(self): with pytest.raises(EngineError, match=r"Server configuration is not readable: bogus"): config() @staticmethod def _validate_config(result): assert result.database_dir == ".runtime/db" assert result.database_url == "sqlite+pysqlite:///.runtime/db/vplan.sqlite" assert result.database_log_level == "DEBUG" assert result.smartthings.base_api_url == "https://api.smartthings.com" assert result.scheduler.database_url == "sqlite+pysqlite:///.runtime/db/jobs.sqlite" assert result.scheduler.daily_job.jitter_sec == 300 assert result.scheduler.daily_job.misfire_grace_sec == 1800 assert result.retry.max_attempts == 4 assert result.retry.min_sec == 1 assert result.retry.max_sec == 5
en
0.595488
# -*- coding: utf-8 -*- # vim: set ft=python ts=4 sw=4 expandtab: Reset configuration before and after tests.
2.3133
2
vesper/django/app/clip_album_commands_preset.py
RichardLitt/Vesper
29
6613166
"""Module containing class `ClipAlbumCommandsPreset`.""" from vesper.util.yaml_preset import YamlPreset import vesper.util.case_utils as case_utils class ClipAlbumCommandsPreset(YamlPreset): """ Preset that specifies clip album keyboard commands. The preset body is YAML that specifies two mappings, one called `globals` that maps command interpreter global variable names to values, and another called `commands` that maps command names to command actions. """ extension_name = 'Clip Album Commands' @property def camel_case_data(self): # We convert only the top-level dictionary keys to camel # case here since the global and command definitions of a # keyboard commands preset should remain snake case. return dict(_camelize_key(*i) for i in self.data.items()) def _camelize_key(key, value): return (case_utils.snake_to_camel(key), value)
"""Module containing class `ClipAlbumCommandsPreset`.""" from vesper.util.yaml_preset import YamlPreset import vesper.util.case_utils as case_utils class ClipAlbumCommandsPreset(YamlPreset): """ Preset that specifies clip album keyboard commands. The preset body is YAML that specifies two mappings, one called `globals` that maps command interpreter global variable names to values, and another called `commands` that maps command names to command actions. """ extension_name = 'Clip Album Commands' @property def camel_case_data(self): # We convert only the top-level dictionary keys to camel # case here since the global and command definitions of a # keyboard commands preset should remain snake case. return dict(_camelize_key(*i) for i in self.data.items()) def _camelize_key(key, value): return (case_utils.snake_to_camel(key), value)
en
0.815759
Module containing class `ClipAlbumCommandsPreset`. Preset that specifies clip album keyboard commands. The preset body is YAML that specifies two mappings, one called `globals` that maps command interpreter global variable names to values, and another called `commands` that maps command names to command actions. # We convert only the top-level dictionary keys to camel # case here since the global and command definitions of a # keyboard commands preset should remain snake case.
2.246712
2
cubetl/util/__init__.py
jjmontesl/cubetl
23
6613167
# CubETL # Copyright (c) 2013-2019 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from pygments import highlight from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexers.agile import PythonLexer from pygments.lexers.web import JsonLexer import json import logging import pprint import simplejson import sys from cubetl.core import Node #from bunch import Bunch # Get an instance of a logger logger = logging.getLogger(__name__) class Assert(Node): """ Evaluates and expression and """ eval = None message = None def process(self, ctx, m): value = ctx.interpolate(self.eval, m) if (not value): if (self.message): logger.error(ctx.interpolate(self.message, m)) raise Exception("Assertion failed: %s = %s" % (self.eval, value)) yield m class Print(Node): """ This class simply prints a message. Accepts an 'eval' property to evaluate. A default instance can be found in CubETL default objects. """ def __init__(self, eval=None, condition=None, truncate_line=120, style='friendly'): super().__init__() self.eval = eval self.truncate_line = truncate_line self.condition = condition #['friendly', 'perldoc', 'vs', 'xcode', 'abap', 'autumn', 'bw', 'lovelace', 'paraiso-light', 'algol', 'arduino', 'rrt', 'algol_nu', 'paraiso-dark', 'colorful', 'manni', 'pastie', 'emacs', 'igor', 'trac', 'vim', 'murphy', 'rainbow_dash', 'default', 'tango', 'native', 'fruity', 'monokai', 'borland'] self.style = style self._lexer = None self._formatter = None def initialize(self, ctx): super(Print, self).initialize(ctx) self._lexer = PythonLexer() #self._formatter = TerminalFormatter() self._formatter = Terminal256Formatter(style=self.style) logger.debug("Initializing Print node %s" % (self)) def _prepare_res(self, ctx, m, obj): return str(obj) def process(self, ctx, m): if (not ctx.quiet): do_print = True if (self.condition): cond = ctx.interpolate(self.condition, m) if (not cond): do_print = False if do_print: if (self.eval): obj = ctx.interpolate(self.eval, m) else: obj = m res = self._prepare_res(ctx, m, obj) if (self.truncate_line): truncated = [] for line in res.split("\n"): if (len(line) > self.truncate_line): line = line[:self.truncate_line - 2] + ".." truncated.append(line) res = "\n".join(truncated) if sys.stdout.isatty(): print(highlight(res, self._lexer, self._formatter)[:-1]) #print(res) else: print(res) yield m class PrettyPrint(Print): """ This class prints an object using pretty print, which allows for indenting. """ def __init__(self, depth=3, indent=4): super().__init__() self.depth = depth self.indent = indent self._pp = None def initialize(self, ctx): super().initialize(ctx) self._pp = pprint.PrettyPrinter(indent=self.indent, depth=self.depth, width=self.truncate_line) def _prepare_res(self, ctx, m, obj): #res = str(obj) #if isinstance(obj, Bunch): # obj = obj.toDict() res = self._pp.pformat(obj) return res
# CubETL # Copyright (c) 2013-2019 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from pygments import highlight from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexers.agile import PythonLexer from pygments.lexers.web import JsonLexer import json import logging import pprint import simplejson import sys from cubetl.core import Node #from bunch import Bunch # Get an instance of a logger logger = logging.getLogger(__name__) class Assert(Node): """ Evaluates and expression and """ eval = None message = None def process(self, ctx, m): value = ctx.interpolate(self.eval, m) if (not value): if (self.message): logger.error(ctx.interpolate(self.message, m)) raise Exception("Assertion failed: %s = %s" % (self.eval, value)) yield m class Print(Node): """ This class simply prints a message. Accepts an 'eval' property to evaluate. A default instance can be found in CubETL default objects. """ def __init__(self, eval=None, condition=None, truncate_line=120, style='friendly'): super().__init__() self.eval = eval self.truncate_line = truncate_line self.condition = condition #['friendly', 'perldoc', 'vs', 'xcode', 'abap', 'autumn', 'bw', 'lovelace', 'paraiso-light', 'algol', 'arduino', 'rrt', 'algol_nu', 'paraiso-dark', 'colorful', 'manni', 'pastie', 'emacs', 'igor', 'trac', 'vim', 'murphy', 'rainbow_dash', 'default', 'tango', 'native', 'fruity', 'monokai', 'borland'] self.style = style self._lexer = None self._formatter = None def initialize(self, ctx): super(Print, self).initialize(ctx) self._lexer = PythonLexer() #self._formatter = TerminalFormatter() self._formatter = Terminal256Formatter(style=self.style) logger.debug("Initializing Print node %s" % (self)) def _prepare_res(self, ctx, m, obj): return str(obj) def process(self, ctx, m): if (not ctx.quiet): do_print = True if (self.condition): cond = ctx.interpolate(self.condition, m) if (not cond): do_print = False if do_print: if (self.eval): obj = ctx.interpolate(self.eval, m) else: obj = m res = self._prepare_res(ctx, m, obj) if (self.truncate_line): truncated = [] for line in res.split("\n"): if (len(line) > self.truncate_line): line = line[:self.truncate_line - 2] + ".." truncated.append(line) res = "\n".join(truncated) if sys.stdout.isatty(): print(highlight(res, self._lexer, self._formatter)[:-1]) #print(res) else: print(res) yield m class PrettyPrint(Print): """ This class prints an object using pretty print, which allows for indenting. """ def __init__(self, depth=3, indent=4): super().__init__() self.depth = depth self.indent = indent self._pp = None def initialize(self, ctx): super().initialize(ctx) self._pp = pprint.PrettyPrinter(indent=self.indent, depth=self.depth, width=self.truncate_line) def _prepare_res(self, ctx, m, obj): #res = str(obj) #if isinstance(obj, Bunch): # obj = obj.toDict() res = self._pp.pformat(obj) return res
en
0.563303
# CubETL # Copyright (c) 2013-2019 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #from bunch import Bunch # Get an instance of a logger Evaluates and expression and This class simply prints a message. Accepts an 'eval' property to evaluate. A default instance can be found in CubETL default objects. #['friendly', 'perldoc', 'vs', 'xcode', 'abap', 'autumn', 'bw', 'lovelace', 'paraiso-light', 'algol', 'arduino', 'rrt', 'algol_nu', 'paraiso-dark', 'colorful', 'manni', 'pastie', 'emacs', 'igor', 'trac', 'vim', 'murphy', 'rainbow_dash', 'default', 'tango', 'native', 'fruity', 'monokai', 'borland'] #self._formatter = TerminalFormatter() #print(res) This class prints an object using pretty print, which allows for indenting. #res = str(obj) #if isinstance(obj, Bunch): # obj = obj.toDict()
2.077032
2
causal_world/task_generators/stacking2.py
michaelfeil/CausalWorld
2
6613168
<reponame>michaelfeil/CausalWorld from causal_world.task_generators.base_task import BaseTask import numpy as np import copy class Stacking2TaskGenerator(BaseTask): def __init__(self, variables_space='space_a_b', fractional_reward_weight=1, dense_reward_weights=np.array([750, 250, 250, 125, 0.005]), activate_sparse_reward=False, tool_block_mass=0.02, tool_block_size=0.065, joint_positions=None, tool_block_1_position=np.array([0, 0, 0.0325]), tool_block_1_orientation=np.array([0, 0, 0, 1]), tool_block_2_position=np.array([0.01, 0.08, 0.0325]), tool_block_2_orientation=np.array([0, 0, 0, 1]), goal_position=np.array([-0.06, -0.06, 0.0325]), goal_orientation=np.array([0, 0, 0, 1])): """ This task generates a task for stacking 2 blocks above each other. Note: it belongs to the same shape family of towers, we only provide a specific task generator for it to be able to do reward engineering and to reproduce the baselines for it in an easy way. :param variables_space: (str) space to be used either 'space_a' or 'space_b' or 'space_a_b' :param fractional_reward_weight: (float) weight multiplied by the fractional volumetric overlap in the reward. :param dense_reward_weights: (list float) specifies the reward weights for all the other reward terms calculated in the calculate_dense_rewards function. :param activate_sparse_reward: (bool) specified if you want to sparsify the reward by having +1 or 0 if the volumetric fraction overlap more than 90%. :param tool_block_mass: (float) specifies the blocks mass. :param joint_positions: (nd.array) specifies the joints position to start the episode with. None if the default to be used. :param tool_block_1_position: (nd.array) specifies the cartesian position of the first tool block, x, y, z. :param tool_block_1_orientation: (nd.array) specifies the euler orientation of the first tool block, yaw, roll, pitch. :param tool_block_2_position: (nd.array) specifies the cartesian position of the second tool block, x, y, z. :param tool_block_2_orientation: (nd.array) specifies the euler orientation of the second tool block, yaw, roll, pitch. :param goal_position: (nd.array) specifies the cartesian position of the goal stack, x, y, z. :param goal_orientation: (nd.array) specifies the euler orientation of the goal stack, yaw, roll, pitch. """ super().__init__(task_name="stacking2", variables_space=variables_space, fractional_reward_weight=fractional_reward_weight, dense_reward_weights=dense_reward_weights, activate_sparse_reward=activate_sparse_reward) self._task_robot_observation_keys = ["time_left_for_task", "joint_positions", "joint_velocities", "end_effector_positions"] self._task_params["tool_block_mass"] = tool_block_mass self._task_params["joint_positions"] = joint_positions self._task_params["tool_block_1_position"] = tool_block_1_position self._task_params["tool_block_1_orientation"] = tool_block_1_orientation self._task_params["tool_block_2_position"] = tool_block_2_position self._task_params["tool_block_2_orientation"] = tool_block_2_orientation self._task_params["goal_position"] = goal_position self._task_params["goal_orientation"] = goal_orientation self._task_params["tool_block_size"] = tool_block_size self.previous_tool_block_1_position = None self.previous_tool_block_2_position = None self.previous_end_effector_positions = None self.previous_joint_velocities = None def get_description(self): """ :return: (str) returns the description of the task itself. """ return "Task where the goal shape is a tower of two blocks" def _set_up_stage_arena(self): """ :return: """ creation_dict = { 'name': "tool_block_1", 'shape': "cube", 'initial_position': self._task_params["tool_block_1_position"], 'initial_orientation': self._task_params["tool_block_1_orientation"], 'mass': self._task_params["tool_block_mass"] } self._stage.add_rigid_general_object(**creation_dict) creation_dict = { 'name': "tool_block_2", 'shape': "cube", 'initial_position': self._task_params["tool_block_2_position"], 'initial_orientation': self._task_params["tool_block_2_orientation"], 'mass': self._task_params["tool_block_mass"] } self._stage.add_rigid_general_object(**creation_dict) creation_dict = { 'name': "goal_block_1", 'shape': "cube", 'position': self._task_params["goal_position"], 'orientation': self._task_params["goal_orientation"] } self._stage.add_silhoutte_general_object(**creation_dict) goal_block_2_position = copy.deepcopy(np.array(self._task_params["goal_position"])) goal_block_2_position[2] += self._task_params["tool_block_size"] creation_dict = { 'name': "goal_block_2", 'shape': "cube", 'position': goal_block_2_position, 'orientation': self._task_params["goal_orientation"] } self._stage.add_silhoutte_general_object(**creation_dict) self._task_stage_observation_keys = [ "tool_block_1_type", "tool_block_1_size", "tool_block_1_cartesian_position", "tool_block_1_orientation", "tool_block_1_linear_velocity", "tool_block_1_angular_velocity", "tool_block_2_type", "tool_block_2_size", "tool_block_2_cartesian_position", "tool_block_2_orientation", "tool_block_2_linear_velocity", "tool_block_2_angular_velocity", "goal_block_1_type", "goal_block_1_size", "goal_block_1_cartesian_position", "goal_block_1_orientation", "goal_block_2_type", "goal_block_2_size", "goal_block_2_cartesian_position", "goal_block_2_orientation" ] return def _calculate_dense_rewards(self, desired_goal, achieved_goal): """ :param desired_goal: :param achieved_goal: :return: """ rewards = [0.0] * 5 block_position_1 = self._stage.get_object_state('tool_block_1', 'cartesian_position') block_position_2 = self._stage.get_object_state('tool_block_2', 'cartesian_position') goal_block_1_position = self._stage.get_object_state('goal_block_1', 'cartesian_position') goal_block_2_position = self._stage.get_object_state('goal_block_2', 'cartesian_position') joint_velocities = self._robot.get_latest_full_state()['velocities'] end_effector_positions = \ self._robot.get_latest_full_state()['end_effector_positions'] end_effector_positions = end_effector_positions.reshape(-1, 3) lower_block_positioned = False if np.linalg.norm(block_position_1 - goal_block_1_position) < 0.02: lower_block_positioned = True if not lower_block_positioned: current_distance_from_block = np.linalg.norm(end_effector_positions - block_position_1) previous_distance_from_block = np.linalg.norm( self.previous_end_effector_positions - self.previous_tool_block_1_position) rewards[0] = previous_distance_from_block - current_distance_from_block previous_dist_to_goal = np.linalg.norm(goal_block_1_position - self.previous_tool_block_1_position) current_dist_to_goal = np.linalg.norm(goal_block_1_position - block_position_1) rewards[1] = previous_dist_to_goal - current_dist_to_goal else: current_distance_from_block = np.linalg.norm(end_effector_positions - block_position_2) previous_distance_from_block = np.linalg.norm( self.previous_end_effector_positions - self.previous_tool_block_2_position) rewards[0] = previous_distance_from_block - current_distance_from_block block_2_above_block_1 = False if np.linalg.norm(block_position_1[:2] - block_position_2[:2]) < 0.005: block_2_above_block_1 = True previous_block_to_goal_height = abs(self.previous_tool_block_2_position[2] - goal_block_2_position[2]) current_block_to_goal_height = abs(block_position_2[2] - goal_block_2_position[2]) if not block_2_above_block_1: rewards[2] = (previous_block_to_goal_height - current_block_to_goal_height) else: rewards[2] = 0.0 if block_position_2[2] > goal_block_2_position[2]: # if block 2 high enough activate horizontal reward previous_block_1_to_block_2 = np.linalg.norm( self.previous_tool_block_1_position[:2] - self.previous_tool_block_2_position[:2]) current_block_1_to_block_2 = np.linalg.norm( block_position_1[:2] - block_position_2[:2]) rewards[3] = previous_block_1_to_block_2 - current_block_1_to_block_2 else: rewards[3] = 0.0 rewards[4] = -np.linalg.norm(joint_velocities - self.previous_joint_velocities) update_task_info = { 'current_end_effector_positions': end_effector_positions, 'current_tool_block_1_position': block_position_1, 'current_tool_block_2_position': block_position_2, 'current_velocity': joint_velocities } return rewards, update_task_info def _update_task_state(self, update_task_info): """ :param update_task_info: :return: """ self.previous_end_effector_positions = \ update_task_info['current_end_effector_positions'] self.previous_tool_block_1_position = \ update_task_info['current_tool_block_1_position'] self.previous_tool_block_2_position = \ update_task_info['current_tool_block_2_position'] self.previous_joint_velocities = \ update_task_info['current_velocity'] return def _set_task_state(self): """ :return: """ self.previous_end_effector_positions = \ self._robot.get_latest_full_state()['end_effector_positions'] self.previous_end_effector_positions = \ self.previous_end_effector_positions.reshape(-1, 3) self.previous_tool_block_1_position = \ self._stage.get_object_state('tool_block_1', 'cartesian_position') self.previous_tool_block_2_position = \ self._stage.get_object_state('tool_block_2', 'cartesian_position') self.previous_joint_velocities = \ self._robot.get_latest_full_state()['velocities'] return def _set_intervention_space_a(self): """ :return: """ super(Stacking2TaskGenerator, self)._set_intervention_space_a() self._intervention_space_a['goal_tower'] = dict() self._intervention_space_a['goal_tower']['cylindrical_position'] = \ copy.deepcopy(self._intervention_space_a['goal_block_1'] ['cylindrical_position']) self._intervention_space_a['goal_tower']['cylindrical_position'][0][-1] = \ self._task_params["goal_position"][-1] * 2.0 self._intervention_space_a['goal_tower']['cylindrical_position'][1][ -1] = \ self._task_params["goal_position"][-1] * 2.0 self._intervention_space_a['goal_tower']['euler_orientation'] = \ copy.deepcopy(self._intervention_space_a['goal_block_1'] ['euler_orientation']) for visual_object in self._stage.get_visual_objects(): del self._intervention_space_a[visual_object]['size'] del self._intervention_space_a[visual_object]['euler_orientation'] del self._intervention_space_a[visual_object]['cylindrical_position'] for rigid_object in self._stage.get_rigid_objects(): del self._intervention_space_a[rigid_object]['size'] return def _set_intervention_space_b(self): """ :return: """ super(Stacking2TaskGenerator, self)._set_intervention_space_b() self._intervention_space_b['goal_tower'] = dict() self._intervention_space_b['goal_tower']['cylindrical_position'] = \ copy.deepcopy(self._intervention_space_b['goal_block_1'] ['cylindrical_position']) self._intervention_space_b['goal_tower']['cylindrical_position'][0][-1] = \ self._task_params["goal_position"][-1] * 2.0 self._intervention_space_b['goal_tower']['cylindrical_position'][1][-1] = \ self._task_params["goal_position"][-1] * 2.0 self._intervention_space_b['goal_tower']['euler_orientation'] = \ copy.deepcopy(self._intervention_space_b['goal_block_1'] ['euler_orientation']) for visual_object in self._stage.get_visual_objects(): del self._intervention_space_b[visual_object]['size'] del self._intervention_space_b[visual_object]['euler_orientation'] del self._intervention_space_b[visual_object][ 'cylindrical_position'] for rigid_object in self._stage.get_rigid_objects(): del self._intervention_space_b[rigid_object]['size'] return def get_task_generator_variables_values(self): """ :return: (dict) specifying the variables belonging to the task itself. """ return { 'goal_tower': {'cylindrical_position': self._stage.get_object_state('goal_block_1', 'cylindrical_position'), 'euler_orientation': self._stage.get_object_state('goal_block_1', 'euler_orientation') } } def apply_task_generator_interventions(self, interventions_dict): """ :param interventions_dict: (dict) variables and their corresponding intervention value. :return: (tuple) first position if the intervention was successful or not, and second position indicates if observation_space needs to be reset. """ if len(interventions_dict) == 0: return True, False reset_observation_space = False if 'goal_tower' in interventions_dict: new_interventions_dict = dict() new_interventions_dict['goal_block_1'] = dict() new_interventions_dict['goal_block_2'] = dict() if 'cylindrical_position' in interventions_dict['goal_tower']: new_interventions_dict['goal_block_1']['cylindrical_position'] = \ copy.deepcopy(interventions_dict['goal_tower']['cylindrical_position']) new_interventions_dict['goal_block_2'][ 'cylindrical_position'] = \ copy.deepcopy(interventions_dict['goal_tower'][ 'cylindrical_position']) new_interventions_dict['goal_block_1']['cylindrical_position'][-1] \ = interventions_dict['goal_tower']['cylindrical_position'][-1] / 2.0 new_interventions_dict['goal_block_2']['cylindrical_position'][ -1] \ = interventions_dict['goal_tower'][ 'cylindrical_position'][-1] * (3 / 2.0) elif 'euler_orientation' in interventions_dict['goal_tower']: new_interventions_dict['goal_block_1']['euler_orientation'] = \ copy.deepcopy( interventions_dict['goal_tower']['euler_orientation']) new_interventions_dict['goal_block_2'][ 'euler_orientation'] = \ copy.deepcopy(interventions_dict['goal_tower'][ 'euler_orientation']) else: raise Exception("this task generator variable " "is not yet defined") self._stage.apply_interventions(new_interventions_dict) else: raise Exception("this task generator variable " "is not yet defined") return True, reset_observation_space def sample_new_goal(self, level=None): """ Used to sample new goal from the corresponding shape families. :param level: (int) specifying the level - not used for now. :return: (dict) the corresponding interventions dict that could then be applied to get a new sampled goal. """ intervention_space = self.get_variable_space_used() intervention_dict = dict() intervention_dict['goal_tower'] = dict() intervention_dict['goal_tower']['cylindrical_position'] = \ np.random.uniform( intervention_space['goal_tower']['cylindrical_position'][0], intervention_space['goal_tower']['cylindrical_position'][1]) intervention_dict['goal_tower']['euler_orientation'] = \ np.random.uniform( intervention_space['goal_tower']['euler_orientation'][0], intervention_space['goal_tower']['euler_orientation'][1]) return intervention_dict
from causal_world.task_generators.base_task import BaseTask import numpy as np import copy class Stacking2TaskGenerator(BaseTask): def __init__(self, variables_space='space_a_b', fractional_reward_weight=1, dense_reward_weights=np.array([750, 250, 250, 125, 0.005]), activate_sparse_reward=False, tool_block_mass=0.02, tool_block_size=0.065, joint_positions=None, tool_block_1_position=np.array([0, 0, 0.0325]), tool_block_1_orientation=np.array([0, 0, 0, 1]), tool_block_2_position=np.array([0.01, 0.08, 0.0325]), tool_block_2_orientation=np.array([0, 0, 0, 1]), goal_position=np.array([-0.06, -0.06, 0.0325]), goal_orientation=np.array([0, 0, 0, 1])): """ This task generates a task for stacking 2 blocks above each other. Note: it belongs to the same shape family of towers, we only provide a specific task generator for it to be able to do reward engineering and to reproduce the baselines for it in an easy way. :param variables_space: (str) space to be used either 'space_a' or 'space_b' or 'space_a_b' :param fractional_reward_weight: (float) weight multiplied by the fractional volumetric overlap in the reward. :param dense_reward_weights: (list float) specifies the reward weights for all the other reward terms calculated in the calculate_dense_rewards function. :param activate_sparse_reward: (bool) specified if you want to sparsify the reward by having +1 or 0 if the volumetric fraction overlap more than 90%. :param tool_block_mass: (float) specifies the blocks mass. :param joint_positions: (nd.array) specifies the joints position to start the episode with. None if the default to be used. :param tool_block_1_position: (nd.array) specifies the cartesian position of the first tool block, x, y, z. :param tool_block_1_orientation: (nd.array) specifies the euler orientation of the first tool block, yaw, roll, pitch. :param tool_block_2_position: (nd.array) specifies the cartesian position of the second tool block, x, y, z. :param tool_block_2_orientation: (nd.array) specifies the euler orientation of the second tool block, yaw, roll, pitch. :param goal_position: (nd.array) specifies the cartesian position of the goal stack, x, y, z. :param goal_orientation: (nd.array) specifies the euler orientation of the goal stack, yaw, roll, pitch. """ super().__init__(task_name="stacking2", variables_space=variables_space, fractional_reward_weight=fractional_reward_weight, dense_reward_weights=dense_reward_weights, activate_sparse_reward=activate_sparse_reward) self._task_robot_observation_keys = ["time_left_for_task", "joint_positions", "joint_velocities", "end_effector_positions"] self._task_params["tool_block_mass"] = tool_block_mass self._task_params["joint_positions"] = joint_positions self._task_params["tool_block_1_position"] = tool_block_1_position self._task_params["tool_block_1_orientation"] = tool_block_1_orientation self._task_params["tool_block_2_position"] = tool_block_2_position self._task_params["tool_block_2_orientation"] = tool_block_2_orientation self._task_params["goal_position"] = goal_position self._task_params["goal_orientation"] = goal_orientation self._task_params["tool_block_size"] = tool_block_size self.previous_tool_block_1_position = None self.previous_tool_block_2_position = None self.previous_end_effector_positions = None self.previous_joint_velocities = None def get_description(self): """ :return: (str) returns the description of the task itself. """ return "Task where the goal shape is a tower of two blocks" def _set_up_stage_arena(self): """ :return: """ creation_dict = { 'name': "tool_block_1", 'shape': "cube", 'initial_position': self._task_params["tool_block_1_position"], 'initial_orientation': self._task_params["tool_block_1_orientation"], 'mass': self._task_params["tool_block_mass"] } self._stage.add_rigid_general_object(**creation_dict) creation_dict = { 'name': "tool_block_2", 'shape': "cube", 'initial_position': self._task_params["tool_block_2_position"], 'initial_orientation': self._task_params["tool_block_2_orientation"], 'mass': self._task_params["tool_block_mass"] } self._stage.add_rigid_general_object(**creation_dict) creation_dict = { 'name': "goal_block_1", 'shape': "cube", 'position': self._task_params["goal_position"], 'orientation': self._task_params["goal_orientation"] } self._stage.add_silhoutte_general_object(**creation_dict) goal_block_2_position = copy.deepcopy(np.array(self._task_params["goal_position"])) goal_block_2_position[2] += self._task_params["tool_block_size"] creation_dict = { 'name': "goal_block_2", 'shape': "cube", 'position': goal_block_2_position, 'orientation': self._task_params["goal_orientation"] } self._stage.add_silhoutte_general_object(**creation_dict) self._task_stage_observation_keys = [ "tool_block_1_type", "tool_block_1_size", "tool_block_1_cartesian_position", "tool_block_1_orientation", "tool_block_1_linear_velocity", "tool_block_1_angular_velocity", "tool_block_2_type", "tool_block_2_size", "tool_block_2_cartesian_position", "tool_block_2_orientation", "tool_block_2_linear_velocity", "tool_block_2_angular_velocity", "goal_block_1_type", "goal_block_1_size", "goal_block_1_cartesian_position", "goal_block_1_orientation", "goal_block_2_type", "goal_block_2_size", "goal_block_2_cartesian_position", "goal_block_2_orientation" ] return def _calculate_dense_rewards(self, desired_goal, achieved_goal): """ :param desired_goal: :param achieved_goal: :return: """ rewards = [0.0] * 5 block_position_1 = self._stage.get_object_state('tool_block_1', 'cartesian_position') block_position_2 = self._stage.get_object_state('tool_block_2', 'cartesian_position') goal_block_1_position = self._stage.get_object_state('goal_block_1', 'cartesian_position') goal_block_2_position = self._stage.get_object_state('goal_block_2', 'cartesian_position') joint_velocities = self._robot.get_latest_full_state()['velocities'] end_effector_positions = \ self._robot.get_latest_full_state()['end_effector_positions'] end_effector_positions = end_effector_positions.reshape(-1, 3) lower_block_positioned = False if np.linalg.norm(block_position_1 - goal_block_1_position) < 0.02: lower_block_positioned = True if not lower_block_positioned: current_distance_from_block = np.linalg.norm(end_effector_positions - block_position_1) previous_distance_from_block = np.linalg.norm( self.previous_end_effector_positions - self.previous_tool_block_1_position) rewards[0] = previous_distance_from_block - current_distance_from_block previous_dist_to_goal = np.linalg.norm(goal_block_1_position - self.previous_tool_block_1_position) current_dist_to_goal = np.linalg.norm(goal_block_1_position - block_position_1) rewards[1] = previous_dist_to_goal - current_dist_to_goal else: current_distance_from_block = np.linalg.norm(end_effector_positions - block_position_2) previous_distance_from_block = np.linalg.norm( self.previous_end_effector_positions - self.previous_tool_block_2_position) rewards[0] = previous_distance_from_block - current_distance_from_block block_2_above_block_1 = False if np.linalg.norm(block_position_1[:2] - block_position_2[:2]) < 0.005: block_2_above_block_1 = True previous_block_to_goal_height = abs(self.previous_tool_block_2_position[2] - goal_block_2_position[2]) current_block_to_goal_height = abs(block_position_2[2] - goal_block_2_position[2]) if not block_2_above_block_1: rewards[2] = (previous_block_to_goal_height - current_block_to_goal_height) else: rewards[2] = 0.0 if block_position_2[2] > goal_block_2_position[2]: # if block 2 high enough activate horizontal reward previous_block_1_to_block_2 = np.linalg.norm( self.previous_tool_block_1_position[:2] - self.previous_tool_block_2_position[:2]) current_block_1_to_block_2 = np.linalg.norm( block_position_1[:2] - block_position_2[:2]) rewards[3] = previous_block_1_to_block_2 - current_block_1_to_block_2 else: rewards[3] = 0.0 rewards[4] = -np.linalg.norm(joint_velocities - self.previous_joint_velocities) update_task_info = { 'current_end_effector_positions': end_effector_positions, 'current_tool_block_1_position': block_position_1, 'current_tool_block_2_position': block_position_2, 'current_velocity': joint_velocities } return rewards, update_task_info def _update_task_state(self, update_task_info): """ :param update_task_info: :return: """ self.previous_end_effector_positions = \ update_task_info['current_end_effector_positions'] self.previous_tool_block_1_position = \ update_task_info['current_tool_block_1_position'] self.previous_tool_block_2_position = \ update_task_info['current_tool_block_2_position'] self.previous_joint_velocities = \ update_task_info['current_velocity'] return def _set_task_state(self): """ :return: """ self.previous_end_effector_positions = \ self._robot.get_latest_full_state()['end_effector_positions'] self.previous_end_effector_positions = \ self.previous_end_effector_positions.reshape(-1, 3) self.previous_tool_block_1_position = \ self._stage.get_object_state('tool_block_1', 'cartesian_position') self.previous_tool_block_2_position = \ self._stage.get_object_state('tool_block_2', 'cartesian_position') self.previous_joint_velocities = \ self._robot.get_latest_full_state()['velocities'] return def _set_intervention_space_a(self): """ :return: """ super(Stacking2TaskGenerator, self)._set_intervention_space_a() self._intervention_space_a['goal_tower'] = dict() self._intervention_space_a['goal_tower']['cylindrical_position'] = \ copy.deepcopy(self._intervention_space_a['goal_block_1'] ['cylindrical_position']) self._intervention_space_a['goal_tower']['cylindrical_position'][0][-1] = \ self._task_params["goal_position"][-1] * 2.0 self._intervention_space_a['goal_tower']['cylindrical_position'][1][ -1] = \ self._task_params["goal_position"][-1] * 2.0 self._intervention_space_a['goal_tower']['euler_orientation'] = \ copy.deepcopy(self._intervention_space_a['goal_block_1'] ['euler_orientation']) for visual_object in self._stage.get_visual_objects(): del self._intervention_space_a[visual_object]['size'] del self._intervention_space_a[visual_object]['euler_orientation'] del self._intervention_space_a[visual_object]['cylindrical_position'] for rigid_object in self._stage.get_rigid_objects(): del self._intervention_space_a[rigid_object]['size'] return def _set_intervention_space_b(self): """ :return: """ super(Stacking2TaskGenerator, self)._set_intervention_space_b() self._intervention_space_b['goal_tower'] = dict() self._intervention_space_b['goal_tower']['cylindrical_position'] = \ copy.deepcopy(self._intervention_space_b['goal_block_1'] ['cylindrical_position']) self._intervention_space_b['goal_tower']['cylindrical_position'][0][-1] = \ self._task_params["goal_position"][-1] * 2.0 self._intervention_space_b['goal_tower']['cylindrical_position'][1][-1] = \ self._task_params["goal_position"][-1] * 2.0 self._intervention_space_b['goal_tower']['euler_orientation'] = \ copy.deepcopy(self._intervention_space_b['goal_block_1'] ['euler_orientation']) for visual_object in self._stage.get_visual_objects(): del self._intervention_space_b[visual_object]['size'] del self._intervention_space_b[visual_object]['euler_orientation'] del self._intervention_space_b[visual_object][ 'cylindrical_position'] for rigid_object in self._stage.get_rigid_objects(): del self._intervention_space_b[rigid_object]['size'] return def get_task_generator_variables_values(self): """ :return: (dict) specifying the variables belonging to the task itself. """ return { 'goal_tower': {'cylindrical_position': self._stage.get_object_state('goal_block_1', 'cylindrical_position'), 'euler_orientation': self._stage.get_object_state('goal_block_1', 'euler_orientation') } } def apply_task_generator_interventions(self, interventions_dict): """ :param interventions_dict: (dict) variables and their corresponding intervention value. :return: (tuple) first position if the intervention was successful or not, and second position indicates if observation_space needs to be reset. """ if len(interventions_dict) == 0: return True, False reset_observation_space = False if 'goal_tower' in interventions_dict: new_interventions_dict = dict() new_interventions_dict['goal_block_1'] = dict() new_interventions_dict['goal_block_2'] = dict() if 'cylindrical_position' in interventions_dict['goal_tower']: new_interventions_dict['goal_block_1']['cylindrical_position'] = \ copy.deepcopy(interventions_dict['goal_tower']['cylindrical_position']) new_interventions_dict['goal_block_2'][ 'cylindrical_position'] = \ copy.deepcopy(interventions_dict['goal_tower'][ 'cylindrical_position']) new_interventions_dict['goal_block_1']['cylindrical_position'][-1] \ = interventions_dict['goal_tower']['cylindrical_position'][-1] / 2.0 new_interventions_dict['goal_block_2']['cylindrical_position'][ -1] \ = interventions_dict['goal_tower'][ 'cylindrical_position'][-1] * (3 / 2.0) elif 'euler_orientation' in interventions_dict['goal_tower']: new_interventions_dict['goal_block_1']['euler_orientation'] = \ copy.deepcopy( interventions_dict['goal_tower']['euler_orientation']) new_interventions_dict['goal_block_2'][ 'euler_orientation'] = \ copy.deepcopy(interventions_dict['goal_tower'][ 'euler_orientation']) else: raise Exception("this task generator variable " "is not yet defined") self._stage.apply_interventions(new_interventions_dict) else: raise Exception("this task generator variable " "is not yet defined") return True, reset_observation_space def sample_new_goal(self, level=None): """ Used to sample new goal from the corresponding shape families. :param level: (int) specifying the level - not used for now. :return: (dict) the corresponding interventions dict that could then be applied to get a new sampled goal. """ intervention_space = self.get_variable_space_used() intervention_dict = dict() intervention_dict['goal_tower'] = dict() intervention_dict['goal_tower']['cylindrical_position'] = \ np.random.uniform( intervention_space['goal_tower']['cylindrical_position'][0], intervention_space['goal_tower']['cylindrical_position'][1]) intervention_dict['goal_tower']['euler_orientation'] = \ np.random.uniform( intervention_space['goal_tower']['euler_orientation'][0], intervention_space['goal_tower']['euler_orientation'][1]) return intervention_dict
en
0.751447
This task generates a task for stacking 2 blocks above each other. Note: it belongs to the same shape family of towers, we only provide a specific task generator for it to be able to do reward engineering and to reproduce the baselines for it in an easy way. :param variables_space: (str) space to be used either 'space_a' or 'space_b' or 'space_a_b' :param fractional_reward_weight: (float) weight multiplied by the fractional volumetric overlap in the reward. :param dense_reward_weights: (list float) specifies the reward weights for all the other reward terms calculated in the calculate_dense_rewards function. :param activate_sparse_reward: (bool) specified if you want to sparsify the reward by having +1 or 0 if the volumetric fraction overlap more than 90%. :param tool_block_mass: (float) specifies the blocks mass. :param joint_positions: (nd.array) specifies the joints position to start the episode with. None if the default to be used. :param tool_block_1_position: (nd.array) specifies the cartesian position of the first tool block, x, y, z. :param tool_block_1_orientation: (nd.array) specifies the euler orientation of the first tool block, yaw, roll, pitch. :param tool_block_2_position: (nd.array) specifies the cartesian position of the second tool block, x, y, z. :param tool_block_2_orientation: (nd.array) specifies the euler orientation of the second tool block, yaw, roll, pitch. :param goal_position: (nd.array) specifies the cartesian position of the goal stack, x, y, z. :param goal_orientation: (nd.array) specifies the euler orientation of the goal stack, yaw, roll, pitch. :return: (str) returns the description of the task itself. :return: :param desired_goal: :param achieved_goal: :return: # if block 2 high enough activate horizontal reward :param update_task_info: :return: :return: :return: :return: :return: (dict) specifying the variables belonging to the task itself. :param interventions_dict: (dict) variables and their corresponding intervention value. :return: (tuple) first position if the intervention was successful or not, and second position indicates if observation_space needs to be reset. Used to sample new goal from the corresponding shape families. :param level: (int) specifying the level - not used for now. :return: (dict) the corresponding interventions dict that could then be applied to get a new sampled goal.
2.52911
3
covfee/orm/task.py
josedvq/covfee
4
6613169
<reponame>josedvq/covfee<filename>covfee/orm/task.py import json import datetime from .orm import db, app from .. import tasks import os def url_prepend(url): if url[:4] != 'http': return app.config['MEDIA_URL'] + '/' + url return url class Task(db.Model): """ Represents a single task, like eg. annotating one video """ __tablename__ = 'tasks' id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String) order = db.Column(db.Integer) name = db.Column(db.String) props = db.Column(db.JSON) responses = db.relationship("TaskResponse", backref='task', cascade="all, delete-orphan") # backref hits # backref hitinstances created_at = db.Column(db.Date, default=datetime.datetime.now) updated_at = db.Column(db.Date, onupdate=datetime.datetime.now) def __init__(self, type, order=0, name=None, **props): self.type = type self.order = order self.name = name # fix URLs if 'media' in props: for k, v in props['media'].items(): if k[-3:] == 'url': props['media'][k] = url_prepend(v) if k[-4:] == 'urls' and isinstance(v, list): props['media'][k] = [url_prepend(url) for url in v] self.props = props def as_dict(self, editable=False): task_dict = {c.name: getattr(self, c.name) for c in self.__table__.columns if c != 'props'} task_dict = {**task_dict, **self.props} task_dict['editable'] = editable return task_dict def __str__(self): return f'{self.name}: chunks={len(self.chunks):d}' def __repr__(self): return str(self) class TaskResponse(db.Model): """ Represents a task's response """ __tablename__ = 'taskresponses' id = db.Column(db.Integer, primary_key=True) # for numbering multiple response submissions index = db.Column(db.Integer) submitted = db.Column(db.Boolean) task_id = db.Column(db.Integer, db.ForeignKey('tasks.id')) hitinstance_id = db.Column(db.LargeBinary, db.ForeignKey('hitinstances.id')) data = db.Column(db.JSON) chunks = db.relationship("Chunk", backref='taskresponse', order_by="Chunk.index", cascade="all, delete-orphan") def __init__(self, task_id, hitinstance_id, index, submitted=False, data=None, chunks=None): self.task_id = task_id self.hitinstance_id = hitinstance_id self.index = index self.submitted = submitted self.data = data self.chunks = chunks def as_dict(self, with_chunk_data=False): response_dict = {c.name: getattr(self, c.name) for c in self.__table__.columns} response_dict['hitinstance_id'] = response_dict['hitinstance_id'].hex() if with_chunk_data: response_dict['chunk_data'] = self.aggregate_chunk_data() return response_dict def aggregate_chunk_data(self): if hasattr(tasks, self.task.type): task_class = getattr(tasks, self.task.type) chunk_data = [chunk.data for chunk in self.chunks] return task_class.process_response(self.data, chunk_data, self.hitinstance, self.task) else: # default aggregation return [x for y in self.chunks for x in y.data] def make_results_object(self): # apply task-specific aggregation method result = { 'hit_id': self.hitinstance.hit.id.hex(), 'instance_id': self.hitinstance.id.hex(), 'task_id': self.task.id, 'hit_name': self.hitinstance.hit.name, 'task_name': self.task.name, 'data': self.aggregate_chunk_data() } return result def write_json(self, dirpath): fpath = os.path.join(dirpath, f'{self.task.name}_{self.index:d}.json') processed_response = self.make_results_object() if processed_response is None: return False json.dump(processed_response, open(fpath, 'w')) return True def write_csv(self, dirpath): if not hasattr(tasks, self.task.type): return False processed_response = self.make_results_object() if processed_response is None: return False fpath = os.path.join(dirpath, f'{self.task.name}_{self.index:d}.csv') task_class = getattr(tasks, self.task.type) df = task_class.to_dataframe(processed_response) df.to_csv(fpath) return True db.Index('taskresponse_index', TaskResponse.task_id, TaskResponse.hitinstance_id, TaskResponse.index) # represents a chunk of task response (for continuous responses) class Chunk(db.Model): """ Represents a chunk of or partial task response""" __tablename__ = 'chunks' # for order-keeping of the chunks index = db.Column(db.Integer, primary_key=True) taskresponse_id = db.Column(db.Integer, db.ForeignKey( 'taskresponses.id'), primary_key=True) data = db.Column(db.JSON) def __init__(self, index, data): self.index = index self.data = data def __str__(self): return f' idx={self.index}' def __repr__(self): return str(self)
import json import datetime from .orm import db, app from .. import tasks import os def url_prepend(url): if url[:4] != 'http': return app.config['MEDIA_URL'] + '/' + url return url class Task(db.Model): """ Represents a single task, like eg. annotating one video """ __tablename__ = 'tasks' id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String) order = db.Column(db.Integer) name = db.Column(db.String) props = db.Column(db.JSON) responses = db.relationship("TaskResponse", backref='task', cascade="all, delete-orphan") # backref hits # backref hitinstances created_at = db.Column(db.Date, default=datetime.datetime.now) updated_at = db.Column(db.Date, onupdate=datetime.datetime.now) def __init__(self, type, order=0, name=None, **props): self.type = type self.order = order self.name = name # fix URLs if 'media' in props: for k, v in props['media'].items(): if k[-3:] == 'url': props['media'][k] = url_prepend(v) if k[-4:] == 'urls' and isinstance(v, list): props['media'][k] = [url_prepend(url) for url in v] self.props = props def as_dict(self, editable=False): task_dict = {c.name: getattr(self, c.name) for c in self.__table__.columns if c != 'props'} task_dict = {**task_dict, **self.props} task_dict['editable'] = editable return task_dict def __str__(self): return f'{self.name}: chunks={len(self.chunks):d}' def __repr__(self): return str(self) class TaskResponse(db.Model): """ Represents a task's response """ __tablename__ = 'taskresponses' id = db.Column(db.Integer, primary_key=True) # for numbering multiple response submissions index = db.Column(db.Integer) submitted = db.Column(db.Boolean) task_id = db.Column(db.Integer, db.ForeignKey('tasks.id')) hitinstance_id = db.Column(db.LargeBinary, db.ForeignKey('hitinstances.id')) data = db.Column(db.JSON) chunks = db.relationship("Chunk", backref='taskresponse', order_by="Chunk.index", cascade="all, delete-orphan") def __init__(self, task_id, hitinstance_id, index, submitted=False, data=None, chunks=None): self.task_id = task_id self.hitinstance_id = hitinstance_id self.index = index self.submitted = submitted self.data = data self.chunks = chunks def as_dict(self, with_chunk_data=False): response_dict = {c.name: getattr(self, c.name) for c in self.__table__.columns} response_dict['hitinstance_id'] = response_dict['hitinstance_id'].hex() if with_chunk_data: response_dict['chunk_data'] = self.aggregate_chunk_data() return response_dict def aggregate_chunk_data(self): if hasattr(tasks, self.task.type): task_class = getattr(tasks, self.task.type) chunk_data = [chunk.data for chunk in self.chunks] return task_class.process_response(self.data, chunk_data, self.hitinstance, self.task) else: # default aggregation return [x for y in self.chunks for x in y.data] def make_results_object(self): # apply task-specific aggregation method result = { 'hit_id': self.hitinstance.hit.id.hex(), 'instance_id': self.hitinstance.id.hex(), 'task_id': self.task.id, 'hit_name': self.hitinstance.hit.name, 'task_name': self.task.name, 'data': self.aggregate_chunk_data() } return result def write_json(self, dirpath): fpath = os.path.join(dirpath, f'{self.task.name}_{self.index:d}.json') processed_response = self.make_results_object() if processed_response is None: return False json.dump(processed_response, open(fpath, 'w')) return True def write_csv(self, dirpath): if not hasattr(tasks, self.task.type): return False processed_response = self.make_results_object() if processed_response is None: return False fpath = os.path.join(dirpath, f'{self.task.name}_{self.index:d}.csv') task_class = getattr(tasks, self.task.type) df = task_class.to_dataframe(processed_response) df.to_csv(fpath) return True db.Index('taskresponse_index', TaskResponse.task_id, TaskResponse.hitinstance_id, TaskResponse.index) # represents a chunk of task response (for continuous responses) class Chunk(db.Model): """ Represents a chunk of or partial task response""" __tablename__ = 'chunks' # for order-keeping of the chunks index = db.Column(db.Integer, primary_key=True) taskresponse_id = db.Column(db.Integer, db.ForeignKey( 'taskresponses.id'), primary_key=True) data = db.Column(db.JSON) def __init__(self, index, data): self.index = index self.data = data def __str__(self): return f' idx={self.index}' def __repr__(self): return str(self)
en
0.834808
Represents a single task, like eg. annotating one video # backref hits # backref hitinstances # fix URLs Represents a task's response # for numbering multiple response submissions # default aggregation # apply task-specific aggregation method # represents a chunk of task response (for continuous responses) Represents a chunk of or partial task response # for order-keeping of the chunks
2.366451
2
1080.py
luizgallas/uri_iniciante
0
6613170
<gh_stars>0 numbers = [] for i in range(100): n = int(input()) numbers.append(n) maior = max(numbers) pos = numbers.index(maior) + 1 print("%d\n%d" %(maior, pos))
numbers = [] for i in range(100): n = int(input()) numbers.append(n) maior = max(numbers) pos = numbers.index(maior) + 1 print("%d\n%d" %(maior, pos))
none
1
3.457518
3
btkb_service.py
dylanbeattie/BL_keyboard_RPI
1
6613171
from __future__ import absolute_import, print_function from optparse import OptionParser, make_option import os import sys import uuid import dbus import dbus.service import dbus.mainloop.glib import time import bluetooth from bluetooth import * from btkb_device import BTKbDevice #define a dbus service that emulates a bluetooth keyboard #this will enable different clients to connect to and use #the service class BTKbService(dbus.service.Object): def __init__(self): print("Setting up service") #set up as a dbus service bus_name=dbus.service.BusName("org.yaptb.btkbservice",bus=dbus.SystemBus()) dbus.service.Object.__init__(self,bus_name,"/org/yaptb/btkbservice") #create and setup our device self.device= BTKbDevice() #start listening for connections self.device.listen() @dbus.service.method('org.yaptb.btkbservice', in_signature='yay') def send_keys(self,modifier_byte,keys): cmd_str="" cmd_str+=chr(0xA1) cmd_str+=chr(0x01) cmd_str+=chr(modifier_byte) cmd_str+=chr(0x00) count=0 for key_code in keys: if(count<6): cmd_str+=chr(key_code) count+=1 print ("self.device.send_string(" + cmd_str + ")") self.device.send_string(cmd_str)
from __future__ import absolute_import, print_function from optparse import OptionParser, make_option import os import sys import uuid import dbus import dbus.service import dbus.mainloop.glib import time import bluetooth from bluetooth import * from btkb_device import BTKbDevice #define a dbus service that emulates a bluetooth keyboard #this will enable different clients to connect to and use #the service class BTKbService(dbus.service.Object): def __init__(self): print("Setting up service") #set up as a dbus service bus_name=dbus.service.BusName("org.yaptb.btkbservice",bus=dbus.SystemBus()) dbus.service.Object.__init__(self,bus_name,"/org/yaptb/btkbservice") #create and setup our device self.device= BTKbDevice() #start listening for connections self.device.listen() @dbus.service.method('org.yaptb.btkbservice', in_signature='yay') def send_keys(self,modifier_byte,keys): cmd_str="" cmd_str+=chr(0xA1) cmd_str+=chr(0x01) cmd_str+=chr(modifier_byte) cmd_str+=chr(0x00) count=0 for key_code in keys: if(count<6): cmd_str+=chr(key_code) count+=1 print ("self.device.send_string(" + cmd_str + ")") self.device.send_string(cmd_str)
en
0.879396
#define a dbus service that emulates a bluetooth keyboard #this will enable different clients to connect to and use #the service #set up as a dbus service #create and setup our device #start listening for connections
2.854421
3
test/webdnn_test/frontend_test/keras_test.py
gunpowder78/webdnn
1
6613172
<reponame>gunpowder78/webdnn from test.runtime.frontend_test.keras_test.util import keras from webdnn.frontend.keras.converter import KerasConverter from webdnn.graph import traverse from webdnn.graph.operators.elementwise_add import ElementwiseAdd from webdnn.graph.operators.linear import Linear from webdnn.util.assertion import assert_equal def test_sequential_one_layer(): model = keras.models.Sequential() model.add(keras.layers.Dense(4, use_bias=False, activation=None, input_shape=(2,))) model.build() graph = KerasConverter(batch_size=1).convert(model) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 1) assert_equal(type(ops[0]), Linear) assert_equal(len(graph.outputs), 1) def test_sequential_multi_layer(): model = keras.models.Sequential() model.add(keras.layers.Dense(4, use_bias=False, activation=None, input_shape=(2,))) model.add(keras.layers.Dense(8, use_bias=False, activation=None)) model.build() graph = KerasConverter(batch_size=1).convert(model) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 2) assert_equal(type(ops[0]), Linear) assert_equal(type(ops[1]), Linear) assert_equal(len(graph.outputs), 1) def test_use_same_layer_twice(): model = keras.models.Sequential() model.add(keras.layers.Dense(4, use_bias=False, activation=None, input_shape=(2,))) layer = keras.layers.Dense(4, use_bias=False, activation=None) model.add(layer) model.add(layer) model.build() graph = KerasConverter(batch_size=1).convert(model) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 3) assert_equal(type(ops[0]), Linear) assert_equal(type(ops[1]), Linear) assert_equal(type(ops[2]), Linear) assert_equal(len(graph.outputs), 1) def test_nested_model(): model1 = keras.models.Sequential() model1.add(keras.layers.Dense(8, use_bias=False, activation=None, input_shape=(4,))) model2 = keras.models.Sequential() model2.add(keras.layers.Dense(4, use_bias=False, activation=None, input_shape=(2,))) model2.add(model1) model2.add(keras.layers.Dense(16, use_bias=False, activation=None)) model2.build() graph = KerasConverter(batch_size=1).convert(model2) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 3) assert_equal(type(ops[0]), Linear) assert_equal(type(ops[1]), Linear) assert_equal(type(ops[2]), Linear) assert_equal(len(graph.outputs), 1) def test_residual(): x = keras.layers.Input(shape=(4,)) h1 = keras.layers.Dense(8, use_bias=False, activation=None)(x) h21 = keras.layers.Dense(4, use_bias=False, activation=None)(h1) h22 = keras.layers.Dense(4, use_bias=False, activation=None)(h1) y = keras.layers.add([h21, h22]) model = keras.models.Model([x], [y]) model.build(input_shape=(1, 4)) graph = KerasConverter(batch_size=1).convert(model) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 4) assert_equal(type(ops[0]), Linear) assert_equal(type(ops[1]), Linear) assert_equal(type(ops[2]), Linear) assert_equal(type(ops[3]), ElementwiseAdd) assert_equal(len(graph.outputs), 1)
from test.runtime.frontend_test.keras_test.util import keras from webdnn.frontend.keras.converter import KerasConverter from webdnn.graph import traverse from webdnn.graph.operators.elementwise_add import ElementwiseAdd from webdnn.graph.operators.linear import Linear from webdnn.util.assertion import assert_equal def test_sequential_one_layer(): model = keras.models.Sequential() model.add(keras.layers.Dense(4, use_bias=False, activation=None, input_shape=(2,))) model.build() graph = KerasConverter(batch_size=1).convert(model) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 1) assert_equal(type(ops[0]), Linear) assert_equal(len(graph.outputs), 1) def test_sequential_multi_layer(): model = keras.models.Sequential() model.add(keras.layers.Dense(4, use_bias=False, activation=None, input_shape=(2,))) model.add(keras.layers.Dense(8, use_bias=False, activation=None)) model.build() graph = KerasConverter(batch_size=1).convert(model) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 2) assert_equal(type(ops[0]), Linear) assert_equal(type(ops[1]), Linear) assert_equal(len(graph.outputs), 1) def test_use_same_layer_twice(): model = keras.models.Sequential() model.add(keras.layers.Dense(4, use_bias=False, activation=None, input_shape=(2,))) layer = keras.layers.Dense(4, use_bias=False, activation=None) model.add(layer) model.add(layer) model.build() graph = KerasConverter(batch_size=1).convert(model) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 3) assert_equal(type(ops[0]), Linear) assert_equal(type(ops[1]), Linear) assert_equal(type(ops[2]), Linear) assert_equal(len(graph.outputs), 1) def test_nested_model(): model1 = keras.models.Sequential() model1.add(keras.layers.Dense(8, use_bias=False, activation=None, input_shape=(4,))) model2 = keras.models.Sequential() model2.add(keras.layers.Dense(4, use_bias=False, activation=None, input_shape=(2,))) model2.add(model1) model2.add(keras.layers.Dense(16, use_bias=False, activation=None)) model2.build() graph = KerasConverter(batch_size=1).convert(model2) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 3) assert_equal(type(ops[0]), Linear) assert_equal(type(ops[1]), Linear) assert_equal(type(ops[2]), Linear) assert_equal(len(graph.outputs), 1) def test_residual(): x = keras.layers.Input(shape=(4,)) h1 = keras.layers.Dense(8, use_bias=False, activation=None)(x) h21 = keras.layers.Dense(4, use_bias=False, activation=None)(h1) h22 = keras.layers.Dense(4, use_bias=False, activation=None)(h1) y = keras.layers.add([h21, h22]) model = keras.models.Model([x], [y]) model.build(input_shape=(1, 4)) graph = KerasConverter(batch_size=1).convert(model) assert_equal(len(graph.inputs), 1) ops = traverse.listup_operators(graph) assert_equal(len(ops), 4) assert_equal(type(ops[0]), Linear) assert_equal(type(ops[1]), Linear) assert_equal(type(ops[2]), Linear) assert_equal(type(ops[3]), ElementwiseAdd) assert_equal(len(graph.outputs), 1)
none
1
2.404562
2
TuFlix/Checkout/urls.py
judrodriguezgo/TuFlixPlusOSE
2
6613173
#URLS CHECKOUT (locales) from django.urls import path urlpatterns = [ ]
#URLS CHECKOUT (locales) from django.urls import path urlpatterns = [ ]
en
0.550526
#URLS CHECKOUT (locales)
1.144647
1
main.py
sebasgverde/mono_music_rnn_generator
0
6613174
# coding: utf-8 """ based in the notebook in https://www.tensorflow.org/tutorials/sequences/text_generation """ # ##### Copyright 2018 The TensorFlow Authors. #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ## Setup # ### Import TensorFlow and other libraries from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf # # This run the model step by step, use only for debugging # tf.enable_eager_execution() import numpy as np import os import time import data_preparation_music as data_preparation import nn_model import argparse parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--db_type', type=str) parser.add_argument('--rnn_type', type=str) parser.add_argument('--rnn_units', type=int) parser.add_argument('--epochs', type=int) args = parser.parse_args() # db_type = "control" # db_type = "interval" # db_type = "db12" # rnn_type = "lstm" # rnn_type = "gru" # Number of RNN units # rnn_units = 256 # rnn_units = 512 # rnn_units = 1024 # epochs=30 db_type = args.db_type rnn_type = args.rnn_type rnn_units = args.rnn_units epochs = args.epochs dataset_train, dataset_validation, vocab_size, BATCH_SIZE, steps_per_epoch, min_note = data_preparation.prepare_data(db_type) # ## Build The Model # Length of the vocabulary in chars # vocab_size = len(vocab) # The embedding dimension embedding_dim = 256 model = nn_model.build_model( vocab_size = vocab_size, embedding_dim=embedding_dim, rnn_units=rnn_units, batch_size=BATCH_SIZE, rnn_type=rnn_type) model.summary() # ## Train the model # At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character. # ### Attach an optimizer, and a loss function # The standard `tf.keras.losses.sparse_categorical_crossentropy` loss function works in this case because it is applied across the last dimension of the predictions. # Because our model returns logits, we need to set the `from_logits` flag. def loss(labels, logits): return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True) # Configure the training procedure using the `tf.keras.Model.compile` method. We'll use `tf.train.AdamOptimizer` with default arguments and the loss function. model.compile( optimizer = tf.train.AdamOptimizer(), loss = loss) # ### Configure checkpoints # Directory where the checkpoints will be saved checkpoint_dir = './models/training_checkpoints_' + db_type + '_'+ rnn_type +'_units_' + str(rnn_units) # Name of the checkpoint files checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}") checkpoint_callback=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_prefix, save_weights_only=True, save_freq=int(steps_per_epoch*epochs/5)) # to save only last one, can be every epoch or something like checkpoint_min_train_loss=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_dir + "/ckpt_min_train_loss", save_weights_only=True, save_best_only=True, mode="min", monitor="loss") checkpoint_min_val_loss=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_dir + "/ckpt_min_val_loss", save_weights_only=True, save_best_only=True, mode="min", monitor="val_loss") # ### Execute the training history = model.fit(dataset_train.repeat(), validation_data=dataset_validation, epochs=epochs, steps_per_epoch=steps_per_epoch, callbacks=[checkpoint_callback, checkpoint_min_train_loss, checkpoint_min_val_loss], verbose=2) # history = model.fit(dataset.repeat(), epochs=10, steps_per_epoch=steps_per_epoch, callbacks=[checkpoint_callback], verbose=2) import pickle model_params = {"vocab_size": vocab_size, "embedding_dim": embedding_dim, "rnn_units": rnn_units, "min_note": min_note} pickle.dump(model_params,open(checkpoint_dir + "/model_params.p", "wb")) pickle.dump({"epochs": history.epoch, "training_loss": history.history["loss"], "validation_loss": history.history["val_loss"]},open(checkpoint_dir + "/learning_curve_info.p", "wb")) import matplotlib.pyplot as plt plt.plot(history.epoch, history.history["loss"], linewidth=2.0, label="training") plt.plot(history.epoch, history.history["val_loss"], linewidth=2.0, label="validation") plt.legend() # plt.title(r'loss') plt.xlabel('Epochs') plt.ylabel('Loss (Cross Entropy)') # plt.show() plt.savefig(checkpoint_dir + '/learnig_curve.png') # tambien lo guardo en caso de que llegue a necesitar informacion de aca, ya buscare como cargar el pickle sin errores pickle.dump(history.history,open(checkpoint_dir + "/history.p", "wb")) # # Advanced Trainig # # model = nn_model.build_model( # vocab_size = len(vocab), # embedding_dim=embedding_dim, # rnn_units=rnn_units, # batch_size=BATCH_SIZE) # # optimizer = tf.train.AdamOptimizer() # # # Training step # epochs = 1 # # for epoch in range(epochs): # start = time.time() # # # initializing the hidden state at the start of every epoch # # initially hidden is None # hidden = model.reset_states() # # for (batch_n, (inp, target)) in enumerate(dataset): # with tf.GradientTape() as tape: # # feeding the hidden state back into the model # # This is the interesting step # predictions = model(inp) # loss = tf.losses.sparse_softmax_cross_entropy(target, predictions) # # grads = tape.gradient(loss, model.trainable_variables) # optimizer.apply_gradients(zip(grads, model.trainable_variables)) # # if batch_n % 100 == 0: # template = 'Epoch {} Batch {} Loss {:.4f}' # print(template.format(epoch+1, batch_n, loss)) # # # saving (checkpoint) the model every 5 epochs # if (epoch + 1) % 5 == 0: # model.save_weights(checkpoint_prefix.format(epoch=epoch)) # # print ('Epoch {} Loss {:.4f}'.format(epoch+1, loss)) # print ('Time taken for 1 epoch {} sec\n'.format(time.time() - start)) # # model.save_weights(checkpoint_prefix.format(epoch=epoch))
# coding: utf-8 """ based in the notebook in https://www.tensorflow.org/tutorials/sequences/text_generation """ # ##### Copyright 2018 The TensorFlow Authors. #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ## Setup # ### Import TensorFlow and other libraries from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf # # This run the model step by step, use only for debugging # tf.enable_eager_execution() import numpy as np import os import time import data_preparation_music as data_preparation import nn_model import argparse parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--db_type', type=str) parser.add_argument('--rnn_type', type=str) parser.add_argument('--rnn_units', type=int) parser.add_argument('--epochs', type=int) args = parser.parse_args() # db_type = "control" # db_type = "interval" # db_type = "db12" # rnn_type = "lstm" # rnn_type = "gru" # Number of RNN units # rnn_units = 256 # rnn_units = 512 # rnn_units = 1024 # epochs=30 db_type = args.db_type rnn_type = args.rnn_type rnn_units = args.rnn_units epochs = args.epochs dataset_train, dataset_validation, vocab_size, BATCH_SIZE, steps_per_epoch, min_note = data_preparation.prepare_data(db_type) # ## Build The Model # Length of the vocabulary in chars # vocab_size = len(vocab) # The embedding dimension embedding_dim = 256 model = nn_model.build_model( vocab_size = vocab_size, embedding_dim=embedding_dim, rnn_units=rnn_units, batch_size=BATCH_SIZE, rnn_type=rnn_type) model.summary() # ## Train the model # At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character. # ### Attach an optimizer, and a loss function # The standard `tf.keras.losses.sparse_categorical_crossentropy` loss function works in this case because it is applied across the last dimension of the predictions. # Because our model returns logits, we need to set the `from_logits` flag. def loss(labels, logits): return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True) # Configure the training procedure using the `tf.keras.Model.compile` method. We'll use `tf.train.AdamOptimizer` with default arguments and the loss function. model.compile( optimizer = tf.train.AdamOptimizer(), loss = loss) # ### Configure checkpoints # Directory where the checkpoints will be saved checkpoint_dir = './models/training_checkpoints_' + db_type + '_'+ rnn_type +'_units_' + str(rnn_units) # Name of the checkpoint files checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}") checkpoint_callback=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_prefix, save_weights_only=True, save_freq=int(steps_per_epoch*epochs/5)) # to save only last one, can be every epoch or something like checkpoint_min_train_loss=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_dir + "/ckpt_min_train_loss", save_weights_only=True, save_best_only=True, mode="min", monitor="loss") checkpoint_min_val_loss=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_dir + "/ckpt_min_val_loss", save_weights_only=True, save_best_only=True, mode="min", monitor="val_loss") # ### Execute the training history = model.fit(dataset_train.repeat(), validation_data=dataset_validation, epochs=epochs, steps_per_epoch=steps_per_epoch, callbacks=[checkpoint_callback, checkpoint_min_train_loss, checkpoint_min_val_loss], verbose=2) # history = model.fit(dataset.repeat(), epochs=10, steps_per_epoch=steps_per_epoch, callbacks=[checkpoint_callback], verbose=2) import pickle model_params = {"vocab_size": vocab_size, "embedding_dim": embedding_dim, "rnn_units": rnn_units, "min_note": min_note} pickle.dump(model_params,open(checkpoint_dir + "/model_params.p", "wb")) pickle.dump({"epochs": history.epoch, "training_loss": history.history["loss"], "validation_loss": history.history["val_loss"]},open(checkpoint_dir + "/learning_curve_info.p", "wb")) import matplotlib.pyplot as plt plt.plot(history.epoch, history.history["loss"], linewidth=2.0, label="training") plt.plot(history.epoch, history.history["val_loss"], linewidth=2.0, label="validation") plt.legend() # plt.title(r'loss') plt.xlabel('Epochs') plt.ylabel('Loss (Cross Entropy)') # plt.show() plt.savefig(checkpoint_dir + '/learnig_curve.png') # tambien lo guardo en caso de que llegue a necesitar informacion de aca, ya buscare como cargar el pickle sin errores pickle.dump(history.history,open(checkpoint_dir + "/history.p", "wb")) # # Advanced Trainig # # model = nn_model.build_model( # vocab_size = len(vocab), # embedding_dim=embedding_dim, # rnn_units=rnn_units, # batch_size=BATCH_SIZE) # # optimizer = tf.train.AdamOptimizer() # # # Training step # epochs = 1 # # for epoch in range(epochs): # start = time.time() # # # initializing the hidden state at the start of every epoch # # initially hidden is None # hidden = model.reset_states() # # for (batch_n, (inp, target)) in enumerate(dataset): # with tf.GradientTape() as tape: # # feeding the hidden state back into the model # # This is the interesting step # predictions = model(inp) # loss = tf.losses.sparse_softmax_cross_entropy(target, predictions) # # grads = tape.gradient(loss, model.trainable_variables) # optimizer.apply_gradients(zip(grads, model.trainable_variables)) # # if batch_n % 100 == 0: # template = 'Epoch {} Batch {} Loss {:.4f}' # print(template.format(epoch+1, batch_n, loss)) # # # saving (checkpoint) the model every 5 epochs # if (epoch + 1) % 5 == 0: # model.save_weights(checkpoint_prefix.format(epoch=epoch)) # # print ('Epoch {} Loss {:.4f}'.format(epoch+1, loss)) # print ('Time taken for 1 epoch {} sec\n'.format(time.time() - start)) # # model.save_weights(checkpoint_prefix.format(epoch=epoch))
en
0.6217
# coding: utf-8 based in the notebook in https://www.tensorflow.org/tutorials/sequences/text_generation # ##### Copyright 2018 The TensorFlow Authors. #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ## Setup # ### Import TensorFlow and other libraries # # This run the model step by step, use only for debugging # tf.enable_eager_execution() # db_type = "control" # db_type = "interval" # db_type = "db12" # rnn_type = "lstm" # rnn_type = "gru" # Number of RNN units # rnn_units = 256 # rnn_units = 512 # rnn_units = 1024 # epochs=30 # ## Build The Model # Length of the vocabulary in chars # vocab_size = len(vocab) # The embedding dimension # ## Train the model # At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character. # ### Attach an optimizer, and a loss function # The standard `tf.keras.losses.sparse_categorical_crossentropy` loss function works in this case because it is applied across the last dimension of the predictions. # Because our model returns logits, we need to set the `from_logits` flag. # Configure the training procedure using the `tf.keras.Model.compile` method. We'll use `tf.train.AdamOptimizer` with default arguments and the loss function. # ### Configure checkpoints # Directory where the checkpoints will be saved # Name of the checkpoint files # to save only last one, can be every epoch or something like # ### Execute the training # history = model.fit(dataset.repeat(), epochs=10, steps_per_epoch=steps_per_epoch, callbacks=[checkpoint_callback], verbose=2) # plt.title(r'loss') # plt.show() # tambien lo guardo en caso de que llegue a necesitar informacion de aca, ya buscare como cargar el pickle sin errores # # Advanced Trainig # # model = nn_model.build_model( # vocab_size = len(vocab), # embedding_dim=embedding_dim, # rnn_units=rnn_units, # batch_size=BATCH_SIZE) # # optimizer = tf.train.AdamOptimizer() # # # Training step # epochs = 1 # # for epoch in range(epochs): # start = time.time() # # # initializing the hidden state at the start of every epoch # # initially hidden is None # hidden = model.reset_states() # # for (batch_n, (inp, target)) in enumerate(dataset): # with tf.GradientTape() as tape: # # feeding the hidden state back into the model # # This is the interesting step # predictions = model(inp) # loss = tf.losses.sparse_softmax_cross_entropy(target, predictions) # # grads = tape.gradient(loss, model.trainable_variables) # optimizer.apply_gradients(zip(grads, model.trainable_variables)) # # if batch_n % 100 == 0: # template = 'Epoch {} Batch {} Loss {:.4f}' # print(template.format(epoch+1, batch_n, loss)) # # # saving (checkpoint) the model every 5 epochs # if (epoch + 1) % 5 == 0: # model.save_weights(checkpoint_prefix.format(epoch=epoch)) # # print ('Epoch {} Loss {:.4f}'.format(epoch+1, loss)) # print ('Time taken for 1 epoch {} sec\n'.format(time.time() - start)) # # model.save_weights(checkpoint_prefix.format(epoch=epoch))
2.471328
2
analyzer/expression/empty_syntax.py
vbondarevsky/ones_analyzer
12
6613175
from analyzer.syntax_kind import SyntaxKind class EmptySyntax(object): def __init__(self): self.kind = SyntaxKind.Empty def __str__(self): return ""
from analyzer.syntax_kind import SyntaxKind class EmptySyntax(object): def __init__(self): self.kind = SyntaxKind.Empty def __str__(self): return ""
none
1
2.652748
3
broadside/components/steps/project/payloads/formulations.py
biomicrodev/broadside
0
6613176
<filename>broadside/components/steps/project/payloads/formulations.py import copy import logging from typing import Any, Tuple, List from natsort import natsort_keygen from qtpy.QtCore import QAbstractTableModel, QModelIndex, Qt, QItemSelectionModel from qtpy.QtWidgets import ( QTableView, QAbstractItemView, QHeaderView, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QGroupBox, ) from ....utils import CellState, LineEditItemDelegate from .....models.payload import Formulation from .....utils.events import EventedAngle, EventedList class FormulationsTableModel(QAbstractTableModel): def __init__(self, formulations: EventedList[Formulation], *args, **kwargs): super().__init__(*args, **kwargs) self.formulations = formulations def data(self, index: QModelIndex, role: Qt.ItemDataRole = None) -> Any: if role in [Qt.DisplayRole, Qt.EditRole, Qt.ToolTipRole]: key = Formulation.keys[index.column()] value = getattr(self.formulations[index.row()], key) if value is None: return "" else: if key == "angle": # for now, since we almost always work with clean divisors of 360 value: EventedAngle value: int = value.int return str(value) elif role == Qt.BackgroundRole: row = index.row() key = Formulation.keys[index.column()] value = getattr(self.formulations[row], key) if (key in ["level", "name"]) and (value == ""): return CellState.Invalid # are formulations unique? (up to level, angle) levelAngle = (self.formulations[row].level, self.formulations[row].angle) otherLevelsAngles = [ (f.level, f.angle) for i, f in enumerate(self.formulations) if i != row ] if levelAngle in otherLevelsAngles: return CellState.Invalid # otherwise... return CellState.Valid elif role == Qt.TextAlignmentRole: return Qt.AlignCenter def setData( self, index: QModelIndex, value: Any, role: Qt.ItemDataRole = None ) -> bool: if role == Qt.EditRole: row = index.row() col = index.column() key = Formulation.keys[col] type_ = Formulation.types[col] try: value = type_(value) except ValueError: return False if key == "angle": self.formulations[row].angle.deg = int(round(value)) else: setattr(self.formulations[row], key, value) self.dataChanged.emit(index, index, [Qt.EditRole]) return True return False def flags(self, index: QModelIndex) -> Qt.ItemFlags: return super().flags(index) | Qt.ItemIsEditable def rowCount(self, parent: QModelIndex = None, *args, **kwargs) -> int: return len(self.formulations) def columnCount(self, parent: QModelIndex = None, *args, **kwargs) -> int: return len(Formulation.keys) def headerData( self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole = None ) -> Any: if role == Qt.DisplayRole: # column headers if orientation == Qt.Horizontal: return Formulation.headers[section] # row headers elif orientation == Qt.Vertical: return section + 1 # section is 0-indexed class FormulationsTableView(QTableView): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setSelectionMode(QAbstractItemView.SingleSelection) horizontalHeader: QHeaderView = self.horizontalHeader() horizontalHeader.setStretchLastSection(True) delegate = LineEditItemDelegate(parent=self) self.setItemDelegate(delegate) class FormulationsEditorView(QWidget): def __init__(self, tableView: FormulationsTableView, *args, **kwargs): super().__init__(*args, **kwargs) self.tableView = tableView self.initUI() self.initBindings() def initUI(self): addFormulationButton = QPushButton() addFormulationButton.setText("Add formulation") addFormulationButton.setCursor(Qt.PointingHandCursor) self.addFormulationButton = addFormulationButton deleteFormulationButton = QPushButton() deleteFormulationButton.setText("Delete formulation") deleteFormulationButton.setObjectName("deleteFormulationButton") deleteFormulationButton.setDisabled(True) deleteFormulationButton.setCursor(Qt.ForbiddenCursor) self.deleteFormulationButton = deleteFormulationButton sortFormulationsButton = QPushButton() sortFormulationsButton.setText("Sort") sortFormulationsButton.setCursor(Qt.PointingHandCursor) self.sortFormulationsButton = sortFormulationsButton buttonsLayout = QHBoxLayout() buttonsLayout.addWidget(addFormulationButton) buttonsLayout.addWidget(deleteFormulationButton) buttonsLayout.addWidget(sortFormulationsButton) layout = QVBoxLayout() layout.addWidget(self.tableView, 1) layout.addLayout(buttonsLayout, 0) groupBox = QGroupBox() groupBox.setTitle("Formulations") groupBox.setLayout(layout) parentLayout = QVBoxLayout() parentLayout.addWidget(groupBox) self.setLayout(parentLayout) def initBindings(self): selectionModel: QItemSelectionModel = self.tableView.selectionModel() selectionModel.selectionChanged.connect(lambda: self.updateButtons()) def updateButtons(self): indexes: List[int] = self.tableView.selectedIndexes() self.deleteFormulationButton.setEnabled(len(indexes) > 0) self.deleteFormulationButton.setCursor( Qt.PointingHandCursor if (len(indexes) > 0) else Qt.ForbiddenCursor ) def formulation_key(f: Formulation) -> Tuple[bool, str, float]: return (f.level == ""), f.level, f.angle.deg class FormulationsEditor: log = logging.getLogger(__name__) def __init__(self, formulations: EventedList[Formulation]): self.formulations = formulations # set up Qt model/view self._model = FormulationsTableModel(formulations) table_view = FormulationsTableView() table_view.setModel(self._model) self._view = FormulationsEditorView(table_view) self._view.setMaximumWidth(600) self._view.setMinimumHeight(300) # bindings from view to model self._view.addFormulationButton.clicked.connect(lambda: self.add_formulation()) self._view.deleteFormulationButton.clicked.connect( lambda: self.delete_formulation() ) self._view.sortFormulationsButton.clicked.connect( lambda: self.sort_formulations() ) # bindings from model to view self.formulations.events.changed.connect(lambda _: self._view.updateButtons()) def add_formulation(self): # update model row = len(self.formulations) index = self._model.createIndex(row, 0) self._model.layoutAboutToBeChanged.emit() self._model.beginInsertRows(index, row, row) self.formulations.append(Formulation(name=f"Formulation {row + 1}")) self._model.endInsertRows() self._model.layoutChanged.emit() # update view self._view.tableView.setCurrentIndex(index) self._view.tableView.setFocus() def delete_formulation(self): indexes: List[QModelIndex] = self._view.tableView.selectedIndexes() index = indexes[0] # selection model guarantees exactly one selection row = index.row() # update model self._model.layoutAboutToBeChanged.emit() self._model.beginRemoveRows(index, row, row) del self.formulations[row] self._model.endRemoveRows() self._model.layoutChanged.emit() # update view if row >= len(self.formulations): self._view.tableView.clearSelection() else: self._view.tableView.setCurrentIndex(index) self._view.tableView.setFocus() def sort_formulations(self): natkey = natsort_keygen(key=formulation_key) # copying like this is okay since this list won't ever be more than 40 # formulations old_formulations = copy.copy(self.formulations) self.formulations.sort(key=natkey) if self.formulations != old_formulations: self._model.layoutChanged.emit()
<filename>broadside/components/steps/project/payloads/formulations.py import copy import logging from typing import Any, Tuple, List from natsort import natsort_keygen from qtpy.QtCore import QAbstractTableModel, QModelIndex, Qt, QItemSelectionModel from qtpy.QtWidgets import ( QTableView, QAbstractItemView, QHeaderView, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QGroupBox, ) from ....utils import CellState, LineEditItemDelegate from .....models.payload import Formulation from .....utils.events import EventedAngle, EventedList class FormulationsTableModel(QAbstractTableModel): def __init__(self, formulations: EventedList[Formulation], *args, **kwargs): super().__init__(*args, **kwargs) self.formulations = formulations def data(self, index: QModelIndex, role: Qt.ItemDataRole = None) -> Any: if role in [Qt.DisplayRole, Qt.EditRole, Qt.ToolTipRole]: key = Formulation.keys[index.column()] value = getattr(self.formulations[index.row()], key) if value is None: return "" else: if key == "angle": # for now, since we almost always work with clean divisors of 360 value: EventedAngle value: int = value.int return str(value) elif role == Qt.BackgroundRole: row = index.row() key = Formulation.keys[index.column()] value = getattr(self.formulations[row], key) if (key in ["level", "name"]) and (value == ""): return CellState.Invalid # are formulations unique? (up to level, angle) levelAngle = (self.formulations[row].level, self.formulations[row].angle) otherLevelsAngles = [ (f.level, f.angle) for i, f in enumerate(self.formulations) if i != row ] if levelAngle in otherLevelsAngles: return CellState.Invalid # otherwise... return CellState.Valid elif role == Qt.TextAlignmentRole: return Qt.AlignCenter def setData( self, index: QModelIndex, value: Any, role: Qt.ItemDataRole = None ) -> bool: if role == Qt.EditRole: row = index.row() col = index.column() key = Formulation.keys[col] type_ = Formulation.types[col] try: value = type_(value) except ValueError: return False if key == "angle": self.formulations[row].angle.deg = int(round(value)) else: setattr(self.formulations[row], key, value) self.dataChanged.emit(index, index, [Qt.EditRole]) return True return False def flags(self, index: QModelIndex) -> Qt.ItemFlags: return super().flags(index) | Qt.ItemIsEditable def rowCount(self, parent: QModelIndex = None, *args, **kwargs) -> int: return len(self.formulations) def columnCount(self, parent: QModelIndex = None, *args, **kwargs) -> int: return len(Formulation.keys) def headerData( self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole = None ) -> Any: if role == Qt.DisplayRole: # column headers if orientation == Qt.Horizontal: return Formulation.headers[section] # row headers elif orientation == Qt.Vertical: return section + 1 # section is 0-indexed class FormulationsTableView(QTableView): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setSelectionMode(QAbstractItemView.SingleSelection) horizontalHeader: QHeaderView = self.horizontalHeader() horizontalHeader.setStretchLastSection(True) delegate = LineEditItemDelegate(parent=self) self.setItemDelegate(delegate) class FormulationsEditorView(QWidget): def __init__(self, tableView: FormulationsTableView, *args, **kwargs): super().__init__(*args, **kwargs) self.tableView = tableView self.initUI() self.initBindings() def initUI(self): addFormulationButton = QPushButton() addFormulationButton.setText("Add formulation") addFormulationButton.setCursor(Qt.PointingHandCursor) self.addFormulationButton = addFormulationButton deleteFormulationButton = QPushButton() deleteFormulationButton.setText("Delete formulation") deleteFormulationButton.setObjectName("deleteFormulationButton") deleteFormulationButton.setDisabled(True) deleteFormulationButton.setCursor(Qt.ForbiddenCursor) self.deleteFormulationButton = deleteFormulationButton sortFormulationsButton = QPushButton() sortFormulationsButton.setText("Sort") sortFormulationsButton.setCursor(Qt.PointingHandCursor) self.sortFormulationsButton = sortFormulationsButton buttonsLayout = QHBoxLayout() buttonsLayout.addWidget(addFormulationButton) buttonsLayout.addWidget(deleteFormulationButton) buttonsLayout.addWidget(sortFormulationsButton) layout = QVBoxLayout() layout.addWidget(self.tableView, 1) layout.addLayout(buttonsLayout, 0) groupBox = QGroupBox() groupBox.setTitle("Formulations") groupBox.setLayout(layout) parentLayout = QVBoxLayout() parentLayout.addWidget(groupBox) self.setLayout(parentLayout) def initBindings(self): selectionModel: QItemSelectionModel = self.tableView.selectionModel() selectionModel.selectionChanged.connect(lambda: self.updateButtons()) def updateButtons(self): indexes: List[int] = self.tableView.selectedIndexes() self.deleteFormulationButton.setEnabled(len(indexes) > 0) self.deleteFormulationButton.setCursor( Qt.PointingHandCursor if (len(indexes) > 0) else Qt.ForbiddenCursor ) def formulation_key(f: Formulation) -> Tuple[bool, str, float]: return (f.level == ""), f.level, f.angle.deg class FormulationsEditor: log = logging.getLogger(__name__) def __init__(self, formulations: EventedList[Formulation]): self.formulations = formulations # set up Qt model/view self._model = FormulationsTableModel(formulations) table_view = FormulationsTableView() table_view.setModel(self._model) self._view = FormulationsEditorView(table_view) self._view.setMaximumWidth(600) self._view.setMinimumHeight(300) # bindings from view to model self._view.addFormulationButton.clicked.connect(lambda: self.add_formulation()) self._view.deleteFormulationButton.clicked.connect( lambda: self.delete_formulation() ) self._view.sortFormulationsButton.clicked.connect( lambda: self.sort_formulations() ) # bindings from model to view self.formulations.events.changed.connect(lambda _: self._view.updateButtons()) def add_formulation(self): # update model row = len(self.formulations) index = self._model.createIndex(row, 0) self._model.layoutAboutToBeChanged.emit() self._model.beginInsertRows(index, row, row) self.formulations.append(Formulation(name=f"Formulation {row + 1}")) self._model.endInsertRows() self._model.layoutChanged.emit() # update view self._view.tableView.setCurrentIndex(index) self._view.tableView.setFocus() def delete_formulation(self): indexes: List[QModelIndex] = self._view.tableView.selectedIndexes() index = indexes[0] # selection model guarantees exactly one selection row = index.row() # update model self._model.layoutAboutToBeChanged.emit() self._model.beginRemoveRows(index, row, row) del self.formulations[row] self._model.endRemoveRows() self._model.layoutChanged.emit() # update view if row >= len(self.formulations): self._view.tableView.clearSelection() else: self._view.tableView.setCurrentIndex(index) self._view.tableView.setFocus() def sort_formulations(self): natkey = natsort_keygen(key=formulation_key) # copying like this is okay since this list won't ever be more than 40 # formulations old_formulations = copy.copy(self.formulations) self.formulations.sort(key=natkey) if self.formulations != old_formulations: self._model.layoutChanged.emit()
en
0.907931
# for now, since we almost always work with clean divisors of 360 # are formulations unique? (up to level, angle) # otherwise... # column headers # row headers # section is 0-indexed # set up Qt model/view # bindings from view to model # bindings from model to view # update model # update view # selection model guarantees exactly one selection # update model # update view # copying like this is okay since this list won't ever be more than 40 # formulations
2.130535
2
examples/lammps/freezing/lammps-2nodes.py
tpeterka/decaf
1
6613177
# a small 2-node example # usage: python3 lammps-2nodes.py --args "<infile> <outfile>" # --- include the following lines each time --- import networkx as nx import os import imp import argparse wf = imp.load_source('workflow', os.environ['DECAF_PREFIX'] + '/python/decaf.py') # --- set your options here --- # parse command line args parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) wf.initParserForTopology(parser) args = parser.parse_args() # define workflow graph # 2-node workflow # # lammps (4 procs) -> filter (4 procs) # # --- Graph definition --- lammps = wf.Node("lammps", start_proc=0, nprocs=4, func='lammps', cmdline='./freeze') outPort0 = lammps.addOutputPort("out") detect = wf.Node("detect", start_proc=4, nprocs=4, func='detect', cmdline='./detect') inPort1 = detect.addInputPort("in") lammps_detect = wf.Edge(lammps.getOutputPort("out"), detect.getInputPort("in"), start_proc=0, nprocs=0, func='', prod_dflow_redist='count', dflow_con_redist='count') # --- convert the nx graph into a workflow data structure and run the workflow --- wf.processGraph("lammps", args.custom_args)
# a small 2-node example # usage: python3 lammps-2nodes.py --args "<infile> <outfile>" # --- include the following lines each time --- import networkx as nx import os import imp import argparse wf = imp.load_source('workflow', os.environ['DECAF_PREFIX'] + '/python/decaf.py') # --- set your options here --- # parse command line args parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) wf.initParserForTopology(parser) args = parser.parse_args() # define workflow graph # 2-node workflow # # lammps (4 procs) -> filter (4 procs) # # --- Graph definition --- lammps = wf.Node("lammps", start_proc=0, nprocs=4, func='lammps', cmdline='./freeze') outPort0 = lammps.addOutputPort("out") detect = wf.Node("detect", start_proc=4, nprocs=4, func='detect', cmdline='./detect') inPort1 = detect.addInputPort("in") lammps_detect = wf.Edge(lammps.getOutputPort("out"), detect.getInputPort("in"), start_proc=0, nprocs=0, func='', prod_dflow_redist='count', dflow_con_redist='count') # --- convert the nx graph into a workflow data structure and run the workflow --- wf.processGraph("lammps", args.custom_args)
en
0.818342
# a small 2-node example # usage: python3 lammps-2nodes.py --args "<infile> <outfile>" # --- include the following lines each time --- # --- set your options here --- # parse command line args # define workflow graph # 2-node workflow # # lammps (4 procs) -> filter (4 procs) # # --- Graph definition --- # --- convert the nx graph into a workflow data structure and run the workflow ---
2.614664
3
ex074.py
RodrigoMoro3736/Python
0
6613178
<gh_stars>0 import random sort = (random.randint(0, 10), random.randint(0, 10), random.randint(0, 10), random.randint(0, 10), random.randint(0, 10)) print(f'Valores sorteados: {sort}') print(f'Maior valor sorteado: {max(sort)}\nMenor valor sorteado: {min(sort)}')
import random sort = (random.randint(0, 10), random.randint(0, 10), random.randint(0, 10), random.randint(0, 10), random.randint(0, 10)) print(f'Valores sorteados: {sort}') print(f'Maior valor sorteado: {max(sort)}\nMenor valor sorteado: {min(sort)}')
none
1
3.181653
3
api/log_listener.py
ngshiheng/automated-valet-car-parking-backend
1
6613179
from typing import Any, Dict from lib.database import Status from lib.logs import log from api.event import subscribe def handle_vehicle_enter_event(data: Dict[str, Any]) -> None: """ Examples: - Accept MotorcycleLot1 - Accept CarLot1 - Accept CarLot2 - Accept CarLot3 - Reject """ lot_no = data['lot_no'] status = data['status'] if status == Status.ACCEPTED: log(f"Accept {lot_no}") else: log("Reject") def handle_vehicle_exit_event(data: Dict[str, Any]) -> None: """ Examples: - MotorcycleLot1 2 - CarLot3 6 """ lot_no = data['lot_no'] parking_fee = data['parking_fee'] log(f"{lot_no} {parking_fee}") def setup_log_event() -> None: subscribe("vehicle_enter", handle_vehicle_enter_event) subscribe("vehicle_exit", handle_vehicle_exit_event)
from typing import Any, Dict from lib.database import Status from lib.logs import log from api.event import subscribe def handle_vehicle_enter_event(data: Dict[str, Any]) -> None: """ Examples: - Accept MotorcycleLot1 - Accept CarLot1 - Accept CarLot2 - Accept CarLot3 - Reject """ lot_no = data['lot_no'] status = data['status'] if status == Status.ACCEPTED: log(f"Accept {lot_no}") else: log("Reject") def handle_vehicle_exit_event(data: Dict[str, Any]) -> None: """ Examples: - MotorcycleLot1 2 - CarLot3 6 """ lot_no = data['lot_no'] parking_fee = data['parking_fee'] log(f"{lot_no} {parking_fee}") def setup_log_event() -> None: subscribe("vehicle_enter", handle_vehicle_enter_event) subscribe("vehicle_exit", handle_vehicle_exit_event)
en
0.377314
Examples: - Accept MotorcycleLot1 - Accept CarLot1 - Accept CarLot2 - Accept CarLot3 - Reject Examples: - MotorcycleLot1 2 - CarLot3 6
2.733389
3
Conputional_Genonics/Assignment/assignment1/src/base_qualities.py
infinityglow/Unimelb-CS-Subjects
1
6613180
#!usr/lib/python2.7 # Auther : <NAME> <<EMAIL>> # Porpuse : Darw the distribution of quality score for all reads and # mismatches separately. import os import sys from numpy import * import getopt import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # Reverse a read def reverse(read): reverse_read = "" read = read[::-1] #reverse the read # get comlimentary read for i in range(len(read)): if read[i] == 'A': reverse_read += 'T' elif read[i] == 'T': reverse_read += 'A' elif read[i] == 'G': reverse_read += 'C' elif read[i] == 'C': reverse_read += 'G' return reverse_read # Compute hamming distance less than min_dis def hamming_dis(a, b, min_dis): dis = 0 mis_set = set() for i in range(len(a)): if a[i] != b[i]: mis_set.add(i) dis += 1 if dis > min_dis: return dis, mis_set return dis, mis_set # Read two files def init(ref_file, read_file): # Reference ref_f = open(ref_file, "r") line = ref_f.readline() ref = ">" for line in ref_f.readlines(): line = line.strip() ref += line ref = ref.upper() # Read file read_f = open(read_file, "r") reads = [] line = read_f.readline() while line: read_name = line.strip()[1:] read = read_f.readline().strip() read_f.readline() read_quality = read_f.readline().strip() reads.append((read_name, read, read_quality)) line = read_f.readline() return (ref, reads) # Aligner def alignment(ref, reads): # read is tuple of (read_name, read_sequence, quality) # all reads reads_mis = [] for read in reads: min_dis = 2 min_pos = 9999 mis_set = set() # forward search # all positions for start in range(len(ref)-len(read[1])): end = start + len(read[1]) dis, mis = hamming_dis(read[1], ref[start:end], min_dis) if dis == 0: mis_dis = dis mis_set.clear() elif dis < min_dis: min_dis = dis mis_set = mis min_pos = start # reverse search if reverse(read[1]) != read[1]: ref = reverse(ref) # all positions for start in range(len(ref)-len(read[1])): end = start + len(read[1]) dis, mis = hamming_dis(read[1], ref[start:end], min_dis) if dis == 0: mis_dis = dis mis_set.clear() elif (dis < min_dis) or (dis == min_dis and start < min_pos): min_dis = dis mis_set = mis min_pos = start reads_mis.append((read[0],read[1],read[2],mis_set)) return reads_mis # Plot distribution of base quality score def plot_base_qs(reads, out_qs): qs = [] rlen = {} for read in reads: score = [] for ch in read[2]: score.append(ord(ch)-ord('!')) qs.append(score) plt.boxplot([list(i) for i in zip(*qs)]) plt.show() plt.savefig(out_qs) # Plot distribution of quality score of all mismatches def plot_mis_qs(reads_mis, out_qs): scores = [[] for i in range(101)] for read in reads_mis: for pos in read[3]: scores[pos].append(ord(read[2][pos])-ord('!')) plt.boxplot(scores) plt.show() plt.savefig(out_qs) # Usage of the tool def usage(): print ("usage:python naive_aligner.py [options] ... [-f reffile | -r readfile | ... ]") print ("Options and arguments:") print ("-h :Help") print ("-f :Reference file.") print ("-r :FASTQ read file.") print ("-o :Output path for pictures.") def main(argv): try: opts, args = getopt.getopt(argv[1:], "hf:r:o:", \ ["help", "reference=", "read="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help+'): usage() sys.exit() elif opt in ('-f', '--reference+'): ref_file = arg elif opt in ('-r', '--read='): read_file = arg elif opt in ('-o','--output='): out_path = arg # If two essential variables has been defined if not('ref_file' in locals().keys()) or not('read_file' in locals().keys()): usage() sys.exit() # main process out_base_qs = out_path + "/base_qs.png" out_mis_qs = out_path + "/mis_qs.png" ref, reads = init(ref_file, read_file) reads_mis = alignment(ref, reads) # plot # plot_base_qs(reads, out_base_qs) plot_mis_qs(reads_mis, out_mis_qs) if __name__ == "__main__": main(sys.argv)
#!usr/lib/python2.7 # Auther : <NAME> <<EMAIL>> # Porpuse : Darw the distribution of quality score for all reads and # mismatches separately. import os import sys from numpy import * import getopt import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # Reverse a read def reverse(read): reverse_read = "" read = read[::-1] #reverse the read # get comlimentary read for i in range(len(read)): if read[i] == 'A': reverse_read += 'T' elif read[i] == 'T': reverse_read += 'A' elif read[i] == 'G': reverse_read += 'C' elif read[i] == 'C': reverse_read += 'G' return reverse_read # Compute hamming distance less than min_dis def hamming_dis(a, b, min_dis): dis = 0 mis_set = set() for i in range(len(a)): if a[i] != b[i]: mis_set.add(i) dis += 1 if dis > min_dis: return dis, mis_set return dis, mis_set # Read two files def init(ref_file, read_file): # Reference ref_f = open(ref_file, "r") line = ref_f.readline() ref = ">" for line in ref_f.readlines(): line = line.strip() ref += line ref = ref.upper() # Read file read_f = open(read_file, "r") reads = [] line = read_f.readline() while line: read_name = line.strip()[1:] read = read_f.readline().strip() read_f.readline() read_quality = read_f.readline().strip() reads.append((read_name, read, read_quality)) line = read_f.readline() return (ref, reads) # Aligner def alignment(ref, reads): # read is tuple of (read_name, read_sequence, quality) # all reads reads_mis = [] for read in reads: min_dis = 2 min_pos = 9999 mis_set = set() # forward search # all positions for start in range(len(ref)-len(read[1])): end = start + len(read[1]) dis, mis = hamming_dis(read[1], ref[start:end], min_dis) if dis == 0: mis_dis = dis mis_set.clear() elif dis < min_dis: min_dis = dis mis_set = mis min_pos = start # reverse search if reverse(read[1]) != read[1]: ref = reverse(ref) # all positions for start in range(len(ref)-len(read[1])): end = start + len(read[1]) dis, mis = hamming_dis(read[1], ref[start:end], min_dis) if dis == 0: mis_dis = dis mis_set.clear() elif (dis < min_dis) or (dis == min_dis and start < min_pos): min_dis = dis mis_set = mis min_pos = start reads_mis.append((read[0],read[1],read[2],mis_set)) return reads_mis # Plot distribution of base quality score def plot_base_qs(reads, out_qs): qs = [] rlen = {} for read in reads: score = [] for ch in read[2]: score.append(ord(ch)-ord('!')) qs.append(score) plt.boxplot([list(i) for i in zip(*qs)]) plt.show() plt.savefig(out_qs) # Plot distribution of quality score of all mismatches def plot_mis_qs(reads_mis, out_qs): scores = [[] for i in range(101)] for read in reads_mis: for pos in read[3]: scores[pos].append(ord(read[2][pos])-ord('!')) plt.boxplot(scores) plt.show() plt.savefig(out_qs) # Usage of the tool def usage(): print ("usage:python naive_aligner.py [options] ... [-f reffile | -r readfile | ... ]") print ("Options and arguments:") print ("-h :Help") print ("-f :Reference file.") print ("-r :FASTQ read file.") print ("-o :Output path for pictures.") def main(argv): try: opts, args = getopt.getopt(argv[1:], "hf:r:o:", \ ["help", "reference=", "read="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help+'): usage() sys.exit() elif opt in ('-f', '--reference+'): ref_file = arg elif opt in ('-r', '--read='): read_file = arg elif opt in ('-o','--output='): out_path = arg # If two essential variables has been defined if not('ref_file' in locals().keys()) or not('read_file' in locals().keys()): usage() sys.exit() # main process out_base_qs = out_path + "/base_qs.png" out_mis_qs = out_path + "/mis_qs.png" ref, reads = init(ref_file, read_file) reads_mis = alignment(ref, reads) # plot # plot_base_qs(reads, out_base_qs) plot_mis_qs(reads_mis, out_mis_qs) if __name__ == "__main__": main(sys.argv)
en
0.820554
#!usr/lib/python2.7 # Auther : <NAME> <<EMAIL>> # Porpuse : Darw the distribution of quality score for all reads and # mismatches separately. # Reverse a read #reverse the read # get comlimentary read # Compute hamming distance less than min_dis # Read two files # Reference # Read file # Aligner # read is tuple of (read_name, read_sequence, quality) # all reads # forward search # all positions # reverse search # all positions # Plot distribution of base quality score # Plot distribution of quality score of all mismatches # Usage of the tool # If two essential variables has been defined # main process # plot # plot_base_qs(reads, out_base_qs)
2.834179
3
src/collection/minikube.py
sudosubin/bins
0
6613181
import sys from package import Package from package.source import PackageSource from utils import hardware class Minikube(Package): name = 'minikube' description = 'Local Kubernetes, focusing on making it easy to learn and develop for Kubernetes' repo = 'kubernetes/minikube' source = PackageSource.GITHUB_RELEASE bin_pattern = ['./minikube-*'] link_pattern = {'./minikube-*': '$BIN_DIR/minikube'} async def download_url(self) -> str: arch = 'amd64' if hardware.is_x86_64 else '386' planned_version = await self.planned_version() return f'https://storage.googleapis.com/minikube/releases/v{planned_version}/minikube-{sys.platform}-{arch}'
import sys from package import Package from package.source import PackageSource from utils import hardware class Minikube(Package): name = 'minikube' description = 'Local Kubernetes, focusing on making it easy to learn and develop for Kubernetes' repo = 'kubernetes/minikube' source = PackageSource.GITHUB_RELEASE bin_pattern = ['./minikube-*'] link_pattern = {'./minikube-*': '$BIN_DIR/minikube'} async def download_url(self) -> str: arch = 'amd64' if hardware.is_x86_64 else '386' planned_version = await self.planned_version() return f'https://storage.googleapis.com/minikube/releases/v{planned_version}/minikube-{sys.platform}-{arch}'
none
1
2.04071
2
cvxpy/reductions/dgp2dcp/atom_canonicalizers/one_minus_pos_canon.py
jasondark/cvxpy
7
6613182
from cvxpy.atoms.elementwise.log import log from cvxpy.atoms.elementwise.exp import exp def one_minus_pos_canon(expr, args): return log(expr._ones - exp(args[0])), []
from cvxpy.atoms.elementwise.log import log from cvxpy.atoms.elementwise.exp import exp def one_minus_pos_canon(expr, args): return log(expr._ones - exp(args[0])), []
none
1
1.826834
2
userbot/plugins/indianmap.py
Declan57/SPARKZZZ
1
6613183
# Coded by @AbirHasan2005 # Telegram Group: http://t.me/linux_repo from telethon import events import asyncio from userbot.utils import admin_cmd @borg.on(admin_cmd("inmap")) async def _(event): if event.fwd_from: return animation_interval = 2 animation_ttl = range(0,36) #input_str = event.pattern_match.group(1) # if input_str == "Read This Telegraph Whole info here": await event.edit("Loading Map ") animation_chars = [ "⣿⣿⣿⣿⣿⣍⠀⠉⠻⠟⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⣿⠓⠀⠀⢒⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⡿⠃⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⣿\n⣿⡿⠋⠋⠀⠀⠀⠀⠀⠀⠈⠙⠻⢿⢿⣿⣿⡿⣿⣿⡟⠋⠀⢀⣩\n⣿⣿⡄⠀⠀⠀⠀⠀⠁⡀⠀⠀⠀⠀⠈⠉⠛⢷⣭⠉⠁⠀⠀⣿⣿\n⣇⣀ . ..INDIA🇮🇳INDIA . . . ⢷⣿⣿⣛⠐⣶⣿⣿\n⣿⣄⠀⣰⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⢀⣠⣿⣿⣿⣾⣿⣿⣿\n⣿⣿⣿⣿⠀⠀⠀⠀⡠⠀⠀⠀⠀⠀⢀⣠⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠄⠀⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⡄⠀⠀⠀⠀⠀⣠⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ \n⣿⣿⣿⣿⣿⣇⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⣿⡆⠀⢀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⣿⣿⣦⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿" ] for i in animation_ttl: await asyncio.sleep(animation_interval) await event.edit(animation_chars[i % 18])
# Coded by @AbirHasan2005 # Telegram Group: http://t.me/linux_repo from telethon import events import asyncio from userbot.utils import admin_cmd @borg.on(admin_cmd("inmap")) async def _(event): if event.fwd_from: return animation_interval = 2 animation_ttl = range(0,36) #input_str = event.pattern_match.group(1) # if input_str == "Read This Telegraph Whole info here": await event.edit("Loading Map ") animation_chars = [ "⣿⣿⣿⣿⣿⣍⠀⠉⠻⠟⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⣿⠓⠀⠀⢒⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⡿⠃⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⣿\n⣿⡿⠋⠋⠀⠀⠀⠀⠀⠀⠈⠙⠻⢿⢿⣿⣿⡿⣿⣿⡟⠋⠀⢀⣩\n⣿⣿⡄⠀⠀⠀⠀⠀⠁⡀⠀⠀⠀⠀⠈⠉⠛⢷⣭⠉⠁⠀⠀⣿⣿\n⣇⣀ . ..INDIA🇮🇳INDIA . . . ⢷⣿⣿⣛⠐⣶⣿⣿\n⣿⣄⠀⣰⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⢀⣠⣿⣿⣿⣾⣿⣿⣿\n⣿⣿⣿⣿⠀⠀⠀⠀⡠⠀⠀⠀⠀⠀⢀⣠⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠄⠀⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⡄⠀⠀⠀⠀⠀⣠⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ \n⣿⣿⣿⣿⣿⣇⠀⠀⠀⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⣿⡆⠀⢀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⣿⣿⣦⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿" ] for i in animation_ttl: await asyncio.sleep(animation_interval) await event.edit(animation_chars[i % 18])
en
0.232322
# Coded by @AbirHasan2005 # Telegram Group: http://t.me/linux_repo #input_str = event.pattern_match.group(1) # if input_str == "Read This Telegraph Whole info here":
2.725855
3
src/django_secrecy/utils.py
Cyxapic/django-secrecy
0
6613184
import os import json import logging logger = logging.getLogger('setup_log') COLORS = { 'white': '\033[0m', 'red': '\033[31m', 'green': '\033[32m', 'orange': '\033[33m', 'yellow': '\033[93m', 'blue': '\033[34m', 'purple': '\033[35m', } class Secrets: '''Get secrets params from "secrets.json" file generated with "generator <PROJ_NAME>" ''' def __init__(self, SETTINGS_DIR, *args, **kwargs): self.SETTINGS_DIR = SETTINGS_DIR self.__dict__.update(self._get_secrets()) def __getattr__(self, attr): logger.warning(f'Secret param {attr} not found!') return None def _get_secrets(self): SECRET_FILE = os.path.join(self.SETTINGS_DIR, 'secrets.json') try: with open(SECRET_FILE, 'r') as file: SECRETS = json.load(file) except FileNotFoundError: logger.warning('File not found! "generator <PROJ_NAME>" first please!') SECRETS = {} return SECRETS # backwards compatibility get_secrets = Secrets
import os import json import logging logger = logging.getLogger('setup_log') COLORS = { 'white': '\033[0m', 'red': '\033[31m', 'green': '\033[32m', 'orange': '\033[33m', 'yellow': '\033[93m', 'blue': '\033[34m', 'purple': '\033[35m', } class Secrets: '''Get secrets params from "secrets.json" file generated with "generator <PROJ_NAME>" ''' def __init__(self, SETTINGS_DIR, *args, **kwargs): self.SETTINGS_DIR = SETTINGS_DIR self.__dict__.update(self._get_secrets()) def __getattr__(self, attr): logger.warning(f'Secret param {attr} not found!') return None def _get_secrets(self): SECRET_FILE = os.path.join(self.SETTINGS_DIR, 'secrets.json') try: with open(SECRET_FILE, 'r') as file: SECRETS = json.load(file) except FileNotFoundError: logger.warning('File not found! "generator <PROJ_NAME>" first please!') SECRETS = {} return SECRETS # backwards compatibility get_secrets = Secrets
en
0.720103
Get secrets params from "secrets.json" file generated with "generator <PROJ_NAME>" # backwards compatibility
2.63482
3
migrations/versions/4af0e356f1d6_.py
chick0/dashboard
0
6613185
<filename>migrations/versions/4af0e356f1d6_.py """empty message Revision ID: 4af0e356f1d6 Revises: Create Date: 2021-08-13 13:37:39.946793 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '4af0e356f1d6' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( 'application', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=20), nullable=False), sa.Column('owner_idx', sa.Integer(), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.Column('homepage', sa.String(length=32), nullable=False), sa.Column('callback', sa.String(length=500), nullable=False), sa.Column('delete', sa.Boolean(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('idx') ) op.create_table( 'application_secret', sa.Column('target_idx', sa.Integer(), nullable=False), sa.Column('key', sa.String(length=64), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('target_idx') ) op.create_table( 'code', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('application_idx', sa.Integer(), nullable=False), sa.Column('target_idx', sa.Integer(), nullable=False), sa.Column('scope', sa.String(length=64), nullable=False), sa.Column('code', sa.String(length=32), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('idx') ) op.create_table( 'history', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('email', sa.String(length=128), nullable=False), sa.Column('is_failed', sa.Boolean(), nullable=False), sa.Column('ip', sa.String(length=64), nullable=False), sa.Column('user_agent', sa.String(length=200), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('idx') ) op.create_table( 'token', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('application_idx', sa.Integer(), nullable=False), sa.Column('target_idx', sa.Integer(), nullable=False), sa.Column('scope', sa.String(length=64), nullable=False), sa.Column('token', sa.String(length=128), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('idx') ) op.create_table( 'two_factor', sa.Column('user_idx', sa.Integer(), nullable=False), sa.Column('secret', sa.String(length=40), nullable=False), sa.PrimaryKeyConstraint('user_idx'), sa.UniqueConstraint('user_idx') ) op.create_table( 'user', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('email', sa.String(length=128), nullable=False), sa.Column('password', sa.String(length=128), nullable=False), sa.Column('nickname', sa.String(length=32), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('email'), sa.UniqueConstraint('idx') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('user') op.drop_table('two_factor') op.drop_table('token') op.drop_table('history') op.drop_table('code') op.drop_table('application_secret') op.drop_table('application') # ### end Alembic commands ###
<filename>migrations/versions/4af0e356f1d6_.py """empty message Revision ID: 4af0e356f1d6 Revises: Create Date: 2021-08-13 13:37:39.946793 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '4af0e356f1d6' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( 'application', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=20), nullable=False), sa.Column('owner_idx', sa.Integer(), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.Column('homepage', sa.String(length=32), nullable=False), sa.Column('callback', sa.String(length=500), nullable=False), sa.Column('delete', sa.Boolean(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('idx') ) op.create_table( 'application_secret', sa.Column('target_idx', sa.Integer(), nullable=False), sa.Column('key', sa.String(length=64), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('target_idx') ) op.create_table( 'code', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('application_idx', sa.Integer(), nullable=False), sa.Column('target_idx', sa.Integer(), nullable=False), sa.Column('scope', sa.String(length=64), nullable=False), sa.Column('code', sa.String(length=32), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('idx') ) op.create_table( 'history', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('email', sa.String(length=128), nullable=False), sa.Column('is_failed', sa.Boolean(), nullable=False), sa.Column('ip', sa.String(length=64), nullable=False), sa.Column('user_agent', sa.String(length=200), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('idx') ) op.create_table( 'token', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('application_idx', sa.Integer(), nullable=False), sa.Column('target_idx', sa.Integer(), nullable=False), sa.Column('scope', sa.String(length=64), nullable=False), sa.Column('token', sa.String(length=128), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('idx') ) op.create_table( 'two_factor', sa.Column('user_idx', sa.Integer(), nullable=False), sa.Column('secret', sa.String(length=40), nullable=False), sa.PrimaryKeyConstraint('user_idx'), sa.UniqueConstraint('user_idx') ) op.create_table( 'user', sa.Column('idx', sa.Integer(), nullable=False), sa.Column('email', sa.String(length=128), nullable=False), sa.Column('password', sa.String(length=128), nullable=False), sa.Column('nickname', sa.String(length=32), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('idx'), sa.UniqueConstraint('email'), sa.UniqueConstraint('idx') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('user') op.drop_table('two_factor') op.drop_table('token') op.drop_table('history') op.drop_table('code') op.drop_table('application_secret') op.drop_table('application') # ### end Alembic commands ###
en
0.477253
empty message Revision ID: 4af0e356f1d6 Revises: Create Date: 2021-08-13 13:37:39.946793 # revision identifiers, used by Alembic. # ### commands auto generated by Alembic - please adjust! ### # ### end Alembic commands ### # ### commands auto generated by Alembic - please adjust! ### # ### end Alembic commands ###
1.684075
2
example.py
plu9in/pyrepl
0
6613186
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from repl import * def completion(buffer, tty_completions): if buffer[0] == 'h': tty_add_completion(tty_completions, "hello") tty_add_completion(tty_completions, "hello there !") return tty_completions if __name__ == '__main__': tty_set_completion_callback(completion) prompt = "$> " line, result = command_line(prompt) while line is not None and result: print("{}".format(line)) line, result = command_line(prompt)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from repl import * def completion(buffer, tty_completions): if buffer[0] == 'h': tty_add_completion(tty_completions, "hello") tty_add_completion(tty_completions, "hello there !") return tty_completions if __name__ == '__main__': tty_set_completion_callback(completion) prompt = "$> " line, result = command_line(prompt) while line is not None and result: print("{}".format(line)) line, result = command_line(prompt)
en
0.308914
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
3.275639
3
backend/currency_exchanger/currencies/migrations/0001_initial.py
norbertcyran/currency-exchanger
0
6613187
# Generated by Django 3.1.2 on 2020-11-08 17:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Currency', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('code', models.CharField(max_length=3)), ('country', models.CharField(max_length=255)), ('rate', models.DecimalField(decimal_places=2, max_digits=10)), ], ), migrations.CreateModel( name='CurrencyExchange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.DecimalField(decimal_places=2, max_digits=12)), ('timestamp', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='CurrencyHistory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp', models.DateTimeField(auto_now_add=True)), ('rate', models.DecimalField(decimal_places=2, max_digits=10)), ], options={ 'ordering': ['-timestamp'], }, ), migrations.CreateModel( name='WalletCurrency', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.DecimalField(decimal_places=2, max_digits=12)), ('currency', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='currencies.currency')), ], ), ]
# Generated by Django 3.1.2 on 2020-11-08 17:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Currency', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('code', models.CharField(max_length=3)), ('country', models.CharField(max_length=255)), ('rate', models.DecimalField(decimal_places=2, max_digits=10)), ], ), migrations.CreateModel( name='CurrencyExchange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.DecimalField(decimal_places=2, max_digits=12)), ('timestamp', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='CurrencyHistory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp', models.DateTimeField(auto_now_add=True)), ('rate', models.DecimalField(decimal_places=2, max_digits=10)), ], options={ 'ordering': ['-timestamp'], }, ), migrations.CreateModel( name='WalletCurrency', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.DecimalField(decimal_places=2, max_digits=12)), ('currency', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='currencies.currency')), ], ), ]
en
0.852781
# Generated by Django 3.1.2 on 2020-11-08 17:01
1.730374
2
source/objects/wecSimPythonInputFile.py
THREDgroup/WEC-Sim-Python
2
6613188
import os import simulationClass import waveClass import bodyClass import constraintClass import ptoClass # class wecSimPythonInputFileClass: # # This class contains WEC-Sim simulation parameters and settings def setUpSimu(): # Simulation Data simu = simulationClass.SimulationClass() # Initialize simulationClass simu.startTime = 0 # Simulation Start Time [s] simu.rampTime = 100 # Wave Ramp Time [s] simu.endTime=400 # Simulation End Time [s] simu.dt = 0.1 # Simulation time-step [s] return(simu) def setUpWaves(): ## Wave Information # Regular Waves waves = waveClass.WaveClass('regular') # Initialize waveClass waves.T = 2.5 # Wave Period [s] waves.H = 8 # Wave Height [m] return(waves) def setUpBody(): ## Body Data # Float body_0 = bodyClass.BodyClass('rm3.h5') # Initialize bodyClass for Float body_0.geometryFile = 'float.stl' # Geomtry File body_0.mass = 'equilibrium' # Mass [kg] body_0.momOfInertia = [20907301, 21306090.66, 37085481.11] # Moment of Inertia [kg*m^2] # Spar/Plate body_1 = bodyClass.BodyClass('rm3.h5') # Initialize bodyClass for Spar/Plate body_1.geometryFile = 'plate.stl' # Geometry File body_1.mass = 'equilibrium' # Mass [kg] body_1.momOfInertia = [94419614.57, 94407091.24, 28542224.82] # Moment of Inertia [kg*m^2] return(body_0,body_1) def setUpConstraint(): ## PTO and Constraint Parameters # Floating (3DOF) Joint constraint_1 = constraintClass.ConstraintClass('Constraint1') # Initialize constraintClass for Constraint1 constraint_1.loc = [0, 0, 0] # Constraint Location [m] return(constraint_1) def setUpPto(): # Translational PTO pto_1 = ptoClass.PtoClass('PTO1') # Initialize ptoClass for PTO1 pto_1.k = 0 # PTO Stiffness [N/m] pto_1.c = 1200000 # PTO Damping [N/(m/s)] pto_1.loc = [0, 0, 0] # PTO Location [m] return(pto_1)
import os import simulationClass import waveClass import bodyClass import constraintClass import ptoClass # class wecSimPythonInputFileClass: # # This class contains WEC-Sim simulation parameters and settings def setUpSimu(): # Simulation Data simu = simulationClass.SimulationClass() # Initialize simulationClass simu.startTime = 0 # Simulation Start Time [s] simu.rampTime = 100 # Wave Ramp Time [s] simu.endTime=400 # Simulation End Time [s] simu.dt = 0.1 # Simulation time-step [s] return(simu) def setUpWaves(): ## Wave Information # Regular Waves waves = waveClass.WaveClass('regular') # Initialize waveClass waves.T = 2.5 # Wave Period [s] waves.H = 8 # Wave Height [m] return(waves) def setUpBody(): ## Body Data # Float body_0 = bodyClass.BodyClass('rm3.h5') # Initialize bodyClass for Float body_0.geometryFile = 'float.stl' # Geomtry File body_0.mass = 'equilibrium' # Mass [kg] body_0.momOfInertia = [20907301, 21306090.66, 37085481.11] # Moment of Inertia [kg*m^2] # Spar/Plate body_1 = bodyClass.BodyClass('rm3.h5') # Initialize bodyClass for Spar/Plate body_1.geometryFile = 'plate.stl' # Geometry File body_1.mass = 'equilibrium' # Mass [kg] body_1.momOfInertia = [94419614.57, 94407091.24, 28542224.82] # Moment of Inertia [kg*m^2] return(body_0,body_1) def setUpConstraint(): ## PTO and Constraint Parameters # Floating (3DOF) Joint constraint_1 = constraintClass.ConstraintClass('Constraint1') # Initialize constraintClass for Constraint1 constraint_1.loc = [0, 0, 0] # Constraint Location [m] return(constraint_1) def setUpPto(): # Translational PTO pto_1 = ptoClass.PtoClass('PTO1') # Initialize ptoClass for PTO1 pto_1.k = 0 # PTO Stiffness [N/m] pto_1.c = 1200000 # PTO Damping [N/(m/s)] pto_1.loc = [0, 0, 0] # PTO Location [m] return(pto_1)
en
0.569736
# class wecSimPythonInputFileClass: # # This class contains WEC-Sim simulation parameters and settings # Simulation Data # Initialize simulationClass # Simulation Start Time [s] # Wave Ramp Time [s] # Simulation End Time [s] # Simulation time-step [s] ## Wave Information # Regular Waves # Initialize waveClass # Wave Period [s] # Wave Height [m] ## Body Data # Float # Initialize bodyClass for Float # Geomtry File # Mass [kg] # Moment of Inertia [kg*m^2] # Spar/Plate # Initialize bodyClass for Spar/Plate # Geometry File # Mass [kg] # Moment of Inertia [kg*m^2] ## PTO and Constraint Parameters # Floating (3DOF) Joint # Initialize constraintClass for Constraint1 # Constraint Location [m] # Translational PTO # Initialize ptoClass for PTO1 # PTO Stiffness [N/m] # PTO Damping [N/(m/s)] # PTO Location [m]
2.562894
3
sjaandi/__init__.py
pechyonkin/sjaandi
3
6613189
from .usecases.mvp import VisualSearchEngine from .usecases.mvp import get_data
from .usecases.mvp import VisualSearchEngine from .usecases.mvp import get_data
none
1
1.066926
1
EECE5639-Computer-Vision/Project-1/libs/misc.py
tjyiiuan/Graduate-Courses
0
6613190
<reponame>tjyiiuan/Graduate-Courses<filename>EECE5639-Computer-Vision/Project-1/libs/misc.py # -*- coding: utf-8 -*- import glob import numpy as np import matplotlib.image as mpimg def EST_NOISE(images): """Implementation of EST_NOISE in Chapter 2 of Trucco and Verri.""" num = images.shape[0] m_e_bar = sum(images)/num m_sigma = np.sqrt(sum((images - m_e_bar)**2) / (num - 1)) return m_sigma def Load_Images(path, imgtype="*.jpg"): """Load frame images from folder. Parameters ---------- path: string Image path imgtype: string Type of images """ loadpath = f"{path}{imgtype}" all_img_path = glob.glob(loadpath) img_num = len(all_img_path) all_img = [0] * img_num for i in np.arange(img_num): one_img_path = all_img_path[i] all_img[i] = mpimg.imread(one_img_path) all_img = np.array(all_img) return all_img def Gen_Gaussian_Filter(dim, sigma, size=0): """Generate 1D or 2D Gaussian filter. Parameters ---------- dim: int Dimension of filter sigma: float Standard deviation n: int Size """ n = max(2 * np.ceil(2 * sigma) + 1, size) ovrlay = int(n / 2) inds = np.arange(-ovrlay, ovrlay + 1) gaussian_1d = np.exp(-inds**2/(2 * sigma**2)) mask = gaussian_1d /sum(gaussian_1d).reshape((-1, 1)) if dim == 2: mask = gaussian_1d * gaussian_1d.T return mask def Gen_Box_Filter(n): """Generate 1D or 2D Gaussian filter. Parameters ---------- n: int Size """ size = int(n) box_mask = np.ones((size, size)) / (size ** 2) return box_mask
# -*- coding: utf-8 -*- import glob import numpy as np import matplotlib.image as mpimg def EST_NOISE(images): """Implementation of EST_NOISE in Chapter 2 of Trucco and Verri.""" num = images.shape[0] m_e_bar = sum(images)/num m_sigma = np.sqrt(sum((images - m_e_bar)**2) / (num - 1)) return m_sigma def Load_Images(path, imgtype="*.jpg"): """Load frame images from folder. Parameters ---------- path: string Image path imgtype: string Type of images """ loadpath = f"{path}{imgtype}" all_img_path = glob.glob(loadpath) img_num = len(all_img_path) all_img = [0] * img_num for i in np.arange(img_num): one_img_path = all_img_path[i] all_img[i] = mpimg.imread(one_img_path) all_img = np.array(all_img) return all_img def Gen_Gaussian_Filter(dim, sigma, size=0): """Generate 1D or 2D Gaussian filter. Parameters ---------- dim: int Dimension of filter sigma: float Standard deviation n: int Size """ n = max(2 * np.ceil(2 * sigma) + 1, size) ovrlay = int(n / 2) inds = np.arange(-ovrlay, ovrlay + 1) gaussian_1d = np.exp(-inds**2/(2 * sigma**2)) mask = gaussian_1d /sum(gaussian_1d).reshape((-1, 1)) if dim == 2: mask = gaussian_1d * gaussian_1d.T return mask def Gen_Box_Filter(n): """Generate 1D or 2D Gaussian filter. Parameters ---------- n: int Size """ size = int(n) box_mask = np.ones((size, size)) / (size ** 2) return box_mask
en
0.432131
# -*- coding: utf-8 -*- Implementation of EST_NOISE in Chapter 2 of Trucco and Verri. Load frame images from folder. Parameters ---------- path: string Image path imgtype: string Type of images Generate 1D or 2D Gaussian filter. Parameters ---------- dim: int Dimension of filter sigma: float Standard deviation n: int Size Generate 1D or 2D Gaussian filter. Parameters ---------- n: int Size
2.977902
3
FCS/binFile2DataMP.py
VicidominiLab/spad-ffs
0
6613191
<reponame>VicidominiLab/spad-ffs<gh_stars>0 from readBinFile import readBinFile from u64ToCounts import u64ToCounts import numpy as np import os import multiprocessing as mp from multiprocessing import Pool from functools import partial def binFile2DataMP(fname, storePickle=False): """ Read a binary FCS data file, containing a list of U64 numbers that represent the photon counts per microtime bin of about 1 µs. ========== =============================================================== Input Meaning ---------- --------------------------------------------------------------- fname Binary file name ========== =============================================================== ========== =============================================================== Output Meaning ---------- --------------------------------------------------------------- countArray N x 26 array with for each row the number of photon counts for each channel and the sum of all channels per microbin ========== =============================================================== """ # Check number of cpu's Ncpu = mp.cpu_count() # User 75% of the cpu's Ncpu = int(np.floor(0.75 * Ncpu)) readLength = 8 * 65536 # Get file size [in bytes] fsize = os.path.getsize(fname) # Empty array to store photon counts # countArray = np.zeros((int(np.ceil(fsize/2/8)), 26), dtype='H') # multiprocessing function func = partial(f, fname, readLength) Nclust = np.ceil(fsize/readLength) with Pool(Ncpu) as p: countArray = p.map(func, (np.arange(Nclust)).tolist()) p.close() p.join() countArray = np.concatenate(countArray, axis=0) return countArray def f(fname, readLength, clustNumb): # Calculate photon counts in a chunck of data clustNumb = int(clustNumb) row = 0 startPos = clustNumb * readLength data = readBinFile(fname, startPos, readLength) countArrayClust = np.zeros((int(len(data) / 2), 26), dtype='H') for i in range(len(data)): counts = u64ToCounts(data[i]) # add counts to array countArrayClust[int(np.floor(row/2))][:] = np.add( countArrayClust[int(np.floor(row/2))][:], counts) row += 1 return countArrayClust
from readBinFile import readBinFile from u64ToCounts import u64ToCounts import numpy as np import os import multiprocessing as mp from multiprocessing import Pool from functools import partial def binFile2DataMP(fname, storePickle=False): """ Read a binary FCS data file, containing a list of U64 numbers that represent the photon counts per microtime bin of about 1 µs. ========== =============================================================== Input Meaning ---------- --------------------------------------------------------------- fname Binary file name ========== =============================================================== ========== =============================================================== Output Meaning ---------- --------------------------------------------------------------- countArray N x 26 array with for each row the number of photon counts for each channel and the sum of all channels per microbin ========== =============================================================== """ # Check number of cpu's Ncpu = mp.cpu_count() # User 75% of the cpu's Ncpu = int(np.floor(0.75 * Ncpu)) readLength = 8 * 65536 # Get file size [in bytes] fsize = os.path.getsize(fname) # Empty array to store photon counts # countArray = np.zeros((int(np.ceil(fsize/2/8)), 26), dtype='H') # multiprocessing function func = partial(f, fname, readLength) Nclust = np.ceil(fsize/readLength) with Pool(Ncpu) as p: countArray = p.map(func, (np.arange(Nclust)).tolist()) p.close() p.join() countArray = np.concatenate(countArray, axis=0) return countArray def f(fname, readLength, clustNumb): # Calculate photon counts in a chunck of data clustNumb = int(clustNumb) row = 0 startPos = clustNumb * readLength data = readBinFile(fname, startPos, readLength) countArrayClust = np.zeros((int(len(data) / 2), 26), dtype='H') for i in range(len(data)): counts = u64ToCounts(data[i]) # add counts to array countArrayClust[int(np.floor(row/2))][:] = np.add( countArrayClust[int(np.floor(row/2))][:], counts) row += 1 return countArrayClust
en
0.556957
Read a binary FCS data file, containing a list of U64 numbers that represent the photon counts per microtime bin of about 1 µs. ========== =============================================================== Input Meaning ---------- --------------------------------------------------------------- fname Binary file name ========== =============================================================== ========== =============================================================== Output Meaning ---------- --------------------------------------------------------------- countArray N x 26 array with for each row the number of photon counts for each channel and the sum of all channels per microbin ========== =============================================================== # Check number of cpu's # User 75% of the cpu's # Get file size [in bytes] # Empty array to store photon counts # countArray = np.zeros((int(np.ceil(fsize/2/8)), 26), dtype='H') # multiprocessing function # Calculate photon counts in a chunck of data # add counts to array
3.023342
3
day15/solution1.py
evanbrumley/aoc2021
0
6613192
<reponame>evanbrumley/aoc2021<gh_stars>0 class Cave: def __init__(self, rows): self.rows = rows self.cols = list(map(list, zip(*self.rows))) self.width = len(self.rows[0]) self.height = len(self.cols[0]) @classmethod def from_raw_lines(cls, lines): rows = [] for line in lines: if line.strip(): rows.append([int(c) for c in line]) return cls(rows) def search(self): q = [] dist = {} prev = {} for y, row in enumerate(self.rows): for x, cost in enumerate(row): q.append((x, y)) dist[(x, y)] = 999999999999999999999 prev[(x, y)] = None dist[(0, 0)] = 0 while q: u = None min_dist = None for k in q: if dist[k] is not None and (min_dist is None or dist[k] < min_dist): min_dist = dist[k] u = k q = [x for x in q if x != u] neighbours = ( (u[0] - 1, u[1]), (u[0] + 1, u[1]), (u[0], u[1] - 1), (u[0], u[1] + 1), ) valid_neighbours = [] for n in neighbours: if n not in q: continue if not (0 <= n[0] < self.width): continue if not (0 <= n[1] < self.height): continue valid_neighbours.append(n) for v in valid_neighbours: alt = dist[u] + self.rows[v[1]][v[0]] if alt <= dist[v]: dist[v] = alt prev[v] = u return dist, prev def main(): with open("input", "r") as f: lines = f.read().splitlines() cave = Cave.from_raw_lines(lines) dist, prev = cave.search() print(dist[(99, 99)]) if __name__ == "__main__": main()
class Cave: def __init__(self, rows): self.rows = rows self.cols = list(map(list, zip(*self.rows))) self.width = len(self.rows[0]) self.height = len(self.cols[0]) @classmethod def from_raw_lines(cls, lines): rows = [] for line in lines: if line.strip(): rows.append([int(c) for c in line]) return cls(rows) def search(self): q = [] dist = {} prev = {} for y, row in enumerate(self.rows): for x, cost in enumerate(row): q.append((x, y)) dist[(x, y)] = 999999999999999999999 prev[(x, y)] = None dist[(0, 0)] = 0 while q: u = None min_dist = None for k in q: if dist[k] is not None and (min_dist is None or dist[k] < min_dist): min_dist = dist[k] u = k q = [x for x in q if x != u] neighbours = ( (u[0] - 1, u[1]), (u[0] + 1, u[1]), (u[0], u[1] - 1), (u[0], u[1] + 1), ) valid_neighbours = [] for n in neighbours: if n not in q: continue if not (0 <= n[0] < self.width): continue if not (0 <= n[1] < self.height): continue valid_neighbours.append(n) for v in valid_neighbours: alt = dist[u] + self.rows[v[1]][v[0]] if alt <= dist[v]: dist[v] = alt prev[v] = u return dist, prev def main(): with open("input", "r") as f: lines = f.read().splitlines() cave = Cave.from_raw_lines(lines) dist, prev = cave.search() print(dist[(99, 99)]) if __name__ == "__main__": main()
none
1
2.925826
3
shopbycoupons/emails/urls.py
shopbycoupons/ShopByCoupons
0
6613193
<reponame>shopbycoupons/ShopByCoupons<filename>shopbycoupons/emails/urls.py from django.conf.urls import url from . import views app_name = 'emails' urlpatterns = [url(r'^$', views.index, name='index'), url(r'^email/$', views.email, name='email'), url(r'^subscribe/$', views.subscribe, name='subscribe'), url(r'^unsubscribe/$', views.unsubscribe, name='unsubscribe'), url(r'^aws/$', views.aws, name='aws')]
from django.conf.urls import url from . import views app_name = 'emails' urlpatterns = [url(r'^$', views.index, name='index'), url(r'^email/$', views.email, name='email'), url(r'^subscribe/$', views.subscribe, name='subscribe'), url(r'^unsubscribe/$', views.unsubscribe, name='unsubscribe'), url(r'^aws/$', views.aws, name='aws')]
none
1
1.603015
2
HackerRank/Python/Classes/Class2_Find_the_Torsional_Angle.py
TISparta/competitive-programming-solutions
1
6613194
import math class Point(): def __init__(self,_x,_y,_z): self.x, self.y, self.z = _x, _y, _z def __sub__(self,p): return Point(self.x-p.x,self.y-p.y,self.z-p.z) def __mul__(self,p): return Point(self.y*p.z-self.z*p.y,self.z*p.x-self.x*p.z,self.x*p.y-self.y*p.x) def dot(self,p): return self.x*p.x+self.y*p.y+self.z*p.z def mod(self): return math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z) A = Point(*map(float,input().split())) B = Point(*map(float,input().split())) C = Point(*map(float,input().split())) D = Point(*map(float,input().split())) AB, BC, CD = B-A, B-C, D-C X, Y = AB*BC, BC*CD print("%.2f" %math.degrees(math.acos(X.dot(Y)/(X.mod()*Y.mod()))))
import math class Point(): def __init__(self,_x,_y,_z): self.x, self.y, self.z = _x, _y, _z def __sub__(self,p): return Point(self.x-p.x,self.y-p.y,self.z-p.z) def __mul__(self,p): return Point(self.y*p.z-self.z*p.y,self.z*p.x-self.x*p.z,self.x*p.y-self.y*p.x) def dot(self,p): return self.x*p.x+self.y*p.y+self.z*p.z def mod(self): return math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z) A = Point(*map(float,input().split())) B = Point(*map(float,input().split())) C = Point(*map(float,input().split())) D = Point(*map(float,input().split())) AB, BC, CD = B-A, B-C, D-C X, Y = AB*BC, BC*CD print("%.2f" %math.degrees(math.acos(X.dot(Y)/(X.mod()*Y.mod()))))
none
1
3.804068
4
Toolkits/Discovery/meta/searx/searx/engines/doku.py
roscopecoltran/SniperKit-Core
4
6613195
# Doku Wiki # # @website https://www.dokuwiki.org/ # @provide-api yes # (https://www.dokuwiki.org/devel:xmlrpc) # # @using-api no # @results HTML # @stable yes # @parse (general) url, title, content from lxml.html import fromstring from searx.engines.xpath import extract_text from searx.url_utils import urlencode # engine dependent config categories = ['general'] # TODO , 'images', 'music', 'videos', 'files' paging = False language_support = False number_of_results = 5 # search-url # Doku is OpenSearch compatible base_url = 'http://localhost:8090' search_url = '/?do=search'\ '&{query}' # TODO '&startRecord={offset}'\ # TODO '&maximumRecords={limit}'\ # do search-request def request(query, params): params['url'] = base_url +\ search_url.format(query=urlencode({'id': query})) return params # get response from search-request def response(resp): results = [] doc = fromstring(resp.text) # parse results # Quickhits for r in doc.xpath('//div[@class="search_quickresult"]/ul/li'): try: res_url = r.xpath('.//a[@class="wikilink1"]/@href')[-1] except: continue if not res_url: continue title = extract_text(r.xpath('.//a[@class="wikilink1"]/@title')) # append result results.append({'title': title, 'content': "", 'url': base_url + res_url}) # Search results for r in doc.xpath('//dl[@class="search_results"]/*'): try: if r.tag == "dt": res_url = r.xpath('.//a[@class="wikilink1"]/@href')[-1] title = extract_text(r.xpath('.//a[@class="wikilink1"]/@title')) elif r.tag == "dd": content = extract_text(r.xpath('.')) # append result results.append({'title': title, 'content': content, 'url': base_url + res_url}) except: continue if not res_url: continue # return results return results
# Doku Wiki # # @website https://www.dokuwiki.org/ # @provide-api yes # (https://www.dokuwiki.org/devel:xmlrpc) # # @using-api no # @results HTML # @stable yes # @parse (general) url, title, content from lxml.html import fromstring from searx.engines.xpath import extract_text from searx.url_utils import urlencode # engine dependent config categories = ['general'] # TODO , 'images', 'music', 'videos', 'files' paging = False language_support = False number_of_results = 5 # search-url # Doku is OpenSearch compatible base_url = 'http://localhost:8090' search_url = '/?do=search'\ '&{query}' # TODO '&startRecord={offset}'\ # TODO '&maximumRecords={limit}'\ # do search-request def request(query, params): params['url'] = base_url +\ search_url.format(query=urlencode({'id': query})) return params # get response from search-request def response(resp): results = [] doc = fromstring(resp.text) # parse results # Quickhits for r in doc.xpath('//div[@class="search_quickresult"]/ul/li'): try: res_url = r.xpath('.//a[@class="wikilink1"]/@href')[-1] except: continue if not res_url: continue title = extract_text(r.xpath('.//a[@class="wikilink1"]/@title')) # append result results.append({'title': title, 'content': "", 'url': base_url + res_url}) # Search results for r in doc.xpath('//dl[@class="search_results"]/*'): try: if r.tag == "dt": res_url = r.xpath('.//a[@class="wikilink1"]/@href')[-1] title = extract_text(r.xpath('.//a[@class="wikilink1"]/@title')) elif r.tag == "dd": content = extract_text(r.xpath('.')) # append result results.append({'title': title, 'content': content, 'url': base_url + res_url}) except: continue if not res_url: continue # return results return results
en
0.323711
# Doku Wiki # # @website https://www.dokuwiki.org/ # @provide-api yes # (https://www.dokuwiki.org/devel:xmlrpc) # # @using-api no # @results HTML # @stable yes # @parse (general) url, title, content # engine dependent config # TODO , 'images', 'music', 'videos', 'files' # search-url # Doku is OpenSearch compatible # TODO '&startRecord={offset}'\ # TODO '&maximumRecords={limit}'\ # do search-request # get response from search-request # parse results # Quickhits # append result # Search results # append result # return results
2.541813
3
src/dispatch/plugins/kandbox_planner/util/kandbox_date_util.py
alibaba/easydispatch
11
6613196
import datetime # import pandas as pd # import numpy as np import json import math from dispatch import config import numpy as np def minutes_to_time_string(minutes): if 0 < minutes < 24 * 60: return ":".join(str(datetime.timedelta(minutes=minutes)).split(":")[0:2]) else: return ":".join(str(datetime.timedelta(minutes=minutes % (24 * 60))).split(":")[0:2]) def time_string_hhmm_to_minutes(time_str): return int(time_string_hhmm_to_seconds(time_str) / 60) def strp_minutes_from_datetime(input_date): return input_date.hour * 60 + input_date.minute def day_minutes_to_datetime(k_day="20191201", minutes=1): new_date = datetime.datetime.strptime(k_day, config.KANDBOX_DATE_FORMAT) + datetime.timedelta( minutes=minutes ) return new_date def extract_minutes_from_datetime(k_datetime): return time_string_hhmm_to_minutes(time_str=datetime.datetime.strftime(k_datetime, "%H:%M")) def datetime_to_google_calendar_date_str(k_date): return "{}-00:00".format(k_date.isoformat().split(".")[0]) def seconds_to_time_string(seconds): return str(datetime.timedelta(seconds=seconds)) def time_string_to_seconds(time_str): # t = "10:15:30" t = time_str sp = t.split(":") if len(sp) == 2: m, s = sp return int(datetime.timedelta(hours=0, minutes=int(m), seconds=int(s)).total_seconds()) else: h, m, s = sp return int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds()) def time_string_to_minutes(time_str): return int(time_string_to_seconds(time_str) / 60) def time_string_hhmm_to_seconds(time_str): t = "10:15" t = time_str try: sp = t.split(":") except: print("An exception occurred with value {}".format(time_str)) return 0 if len(sp) == 2: h, m = sp return int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=0).total_seconds()) else: h, m, s = sp return int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds()) def get_right_end_minutes(startDate, endDate): if startDate > endDate: return endDate + 1440 else: return endDate def int_hhmm_to_minutes(int_time_str): t = int(int_time_str) return math.floor(t / 100) * 60 + int(t % 100) def transform_weekly_worker_time_from_rhythm_v6(time_str): weekly_working_minutes = [] ws = time_str.split(";") for work_day in ws: if len(work_day) < 2: weekly_working_minutes.append([0, 0]) continue work_day_start = int_hhmm_to_minutes(work_day.split("_")[0]) work_day_end = int_hhmm_to_minutes(work_day.split("_")[1]) if work_day_end < work_day_start: work_day_end += 12 * 60 weekly_working_minutes.append([work_day_start, work_day_end]) return json.dumps(weekly_working_minutes) # print(transform_weekly_worker_time_from_rhythm_v6 ('0_0000_00;1_0830_0550;2_0830_0550;3_0830_0550;4_0830_0550;5_0830_0550;6_0830_0240')) def clip_time_period(p1, p2): # each P is [<=, <] if p1[0] >= p2[1]: return [] if p1[1] <= p2[0]: return [] if p1[0] < p2[0]: start = p2[0] else: start = p1[0] if p1[1] < p2[1]: end = p1[1] else: end = p2[1] return [start, end] # Inspired by https://www.geeksforgeeks.org/find-intersection-of-intervals-given-by-two-lists/ # Python3 implementation to find intersecting intervals # In fact not used so far, 2020-09-24 23:17:37 def intersect_time_periods(time_periods, minimum_length=0, first_minimum_length_match_only=False): """ Find intersect_time_periods. If minimum_length first 2020-09-22 10:18:58: I created this only because interval tree has not query of length_greater_than , https://github.com/chaimleib/intervaltree Parameters ---------- action : list(float) Input array of worker+day array. The rest of values in action_dict are discarded and re-calculated. minimum_length : int If not None and > 0, it returns maximum one time period which is longer than first_minimum_length_match Returns ------- time_period_list: list A list of time period """ # i and j pointers for arr1 # and arr2 respectively MININUM_TIME_POINT = -1 list_lengths = [len(x) for x in time_periods] nbr_of_all_time_periods = sum(list_lengths) time_period_indices = [0 for _ in range(len(time_periods))] result_list = [] # n = len(arr1) # m = len(arr2) # Loop through all intervals unless one # of the interval gets exhausted while sum(time_period_indices) < nbr_of_all_time_periods: current_time_periods = [] for idx, tp in enumerate(time_periods): current_time_periods.append(tp[time_period_indices[idx]]) # Left bound for intersecting segment left_points = [x[0] for x in current_time_periods] left_point_max = max(left_points) # Right bound for intersecting segment right_points = [ x[1] for x in current_time_periods ].copy() # no need to copy, new list anyway? right_point_min = min(right_points) # If segment is valid if right_point_min - left_point_max >= minimum_length: if first_minimum_length_match_only: return [[left_point_max, right_point_min]] else: result_list.append([left_point_max, right_point_min]) # If i-th interval's right bound is # smaller increment i else increment j found_index_to_step = False for _ in range(len(list_lengths)): right_min_index = np.argmin([x[1] for x in current_time_periods]) if time_period_indices[right_min_index] < list_lengths[right_min_index] - 1: time_period_indices[right_min_index] += 1 right_points[right_min_index] = MININUM_TIME_POINT found_index_to_step = True break if not found_index_to_step: break return result_list # Inspired by https://www.geeksforgeeks.org/find-intersection-of-intervals-given-by-two-lists/ # Python3 implementation to find intersecting intervals """ if __name__ == "__main__": # Test code arr1 = [[0, 4], [5, 10], [13, 20], [24, 25]] arr2 = [[1, 5], [8, 12], [15, 24], [25, 26]] arr3 = [[2, 3], [9, 12], [15, 16], [23, 24]] arr4 = [[9, 12], [23, 24]] print(intersect_time_periods([arr1, arr2])) # [[1, 4], [5, 5], [8, 10], [15, 20], [24, 24], [25, 25]] print(intersect_time_periods([arr1, arr2, arr3])) # [[2, 3], [9, 10], [15, 16], [24, 24]] print(intersect_time_periods([arr1, arr2, arr3, arr4])) # [[9, 10], [24, 24]] print( intersect_time_periods([arr1, arr2], minimum_length=2, first_minimum_length_match_only=True) ) # [[1, 4]] print(intersect_time_periods([arr1], minimum_length=2, first_minimum_length_match_only=True)) # [[0, 4]] """ def transform_kandbox_day_2_postgres_datetime(k_day=None): new_date = datetime.datetime.strftime( datetime.datetime.strptime(k_day, config.KANDBOX_DATE_FORMAT), config.KANDBOX_DATETIME_FORMAT_WITH_MS, ) return new_date def add_days_2_day_string(k_day=None, days=None): new_date = datetime.datetime.strptime(k_day, config.KANDBOX_DATE_FORMAT) + datetime.timedelta( days=days ) return datetime.datetime.strftime(new_date, config.KANDBOX_DATE_FORMAT) def days_between_2_day_string(start_day=None, end_day=None): start_date = datetime.datetime.strptime(start_day, config.KANDBOX_DATE_FORMAT) end_date = datetime.datetime.strptime(end_day, config.KANDBOX_DATE_FORMAT) return (end_date - start_date).days def get_current_day_string(): start_date = datetime.datetime.strptime(datetime.datetime.now(), "YYYYMMDD") return start_date
import datetime # import pandas as pd # import numpy as np import json import math from dispatch import config import numpy as np def minutes_to_time_string(minutes): if 0 < minutes < 24 * 60: return ":".join(str(datetime.timedelta(minutes=minutes)).split(":")[0:2]) else: return ":".join(str(datetime.timedelta(minutes=minutes % (24 * 60))).split(":")[0:2]) def time_string_hhmm_to_minutes(time_str): return int(time_string_hhmm_to_seconds(time_str) / 60) def strp_minutes_from_datetime(input_date): return input_date.hour * 60 + input_date.minute def day_minutes_to_datetime(k_day="20191201", minutes=1): new_date = datetime.datetime.strptime(k_day, config.KANDBOX_DATE_FORMAT) + datetime.timedelta( minutes=minutes ) return new_date def extract_minutes_from_datetime(k_datetime): return time_string_hhmm_to_minutes(time_str=datetime.datetime.strftime(k_datetime, "%H:%M")) def datetime_to_google_calendar_date_str(k_date): return "{}-00:00".format(k_date.isoformat().split(".")[0]) def seconds_to_time_string(seconds): return str(datetime.timedelta(seconds=seconds)) def time_string_to_seconds(time_str): # t = "10:15:30" t = time_str sp = t.split(":") if len(sp) == 2: m, s = sp return int(datetime.timedelta(hours=0, minutes=int(m), seconds=int(s)).total_seconds()) else: h, m, s = sp return int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds()) def time_string_to_minutes(time_str): return int(time_string_to_seconds(time_str) / 60) def time_string_hhmm_to_seconds(time_str): t = "10:15" t = time_str try: sp = t.split(":") except: print("An exception occurred with value {}".format(time_str)) return 0 if len(sp) == 2: h, m = sp return int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=0).total_seconds()) else: h, m, s = sp return int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds()) def get_right_end_minutes(startDate, endDate): if startDate > endDate: return endDate + 1440 else: return endDate def int_hhmm_to_minutes(int_time_str): t = int(int_time_str) return math.floor(t / 100) * 60 + int(t % 100) def transform_weekly_worker_time_from_rhythm_v6(time_str): weekly_working_minutes = [] ws = time_str.split(";") for work_day in ws: if len(work_day) < 2: weekly_working_minutes.append([0, 0]) continue work_day_start = int_hhmm_to_minutes(work_day.split("_")[0]) work_day_end = int_hhmm_to_minutes(work_day.split("_")[1]) if work_day_end < work_day_start: work_day_end += 12 * 60 weekly_working_minutes.append([work_day_start, work_day_end]) return json.dumps(weekly_working_minutes) # print(transform_weekly_worker_time_from_rhythm_v6 ('0_0000_00;1_0830_0550;2_0830_0550;3_0830_0550;4_0830_0550;5_0830_0550;6_0830_0240')) def clip_time_period(p1, p2): # each P is [<=, <] if p1[0] >= p2[1]: return [] if p1[1] <= p2[0]: return [] if p1[0] < p2[0]: start = p2[0] else: start = p1[0] if p1[1] < p2[1]: end = p1[1] else: end = p2[1] return [start, end] # Inspired by https://www.geeksforgeeks.org/find-intersection-of-intervals-given-by-two-lists/ # Python3 implementation to find intersecting intervals # In fact not used so far, 2020-09-24 23:17:37 def intersect_time_periods(time_periods, minimum_length=0, first_minimum_length_match_only=False): """ Find intersect_time_periods. If minimum_length first 2020-09-22 10:18:58: I created this only because interval tree has not query of length_greater_than , https://github.com/chaimleib/intervaltree Parameters ---------- action : list(float) Input array of worker+day array. The rest of values in action_dict are discarded and re-calculated. minimum_length : int If not None and > 0, it returns maximum one time period which is longer than first_minimum_length_match Returns ------- time_period_list: list A list of time period """ # i and j pointers for arr1 # and arr2 respectively MININUM_TIME_POINT = -1 list_lengths = [len(x) for x in time_periods] nbr_of_all_time_periods = sum(list_lengths) time_period_indices = [0 for _ in range(len(time_periods))] result_list = [] # n = len(arr1) # m = len(arr2) # Loop through all intervals unless one # of the interval gets exhausted while sum(time_period_indices) < nbr_of_all_time_periods: current_time_periods = [] for idx, tp in enumerate(time_periods): current_time_periods.append(tp[time_period_indices[idx]]) # Left bound for intersecting segment left_points = [x[0] for x in current_time_periods] left_point_max = max(left_points) # Right bound for intersecting segment right_points = [ x[1] for x in current_time_periods ].copy() # no need to copy, new list anyway? right_point_min = min(right_points) # If segment is valid if right_point_min - left_point_max >= minimum_length: if first_minimum_length_match_only: return [[left_point_max, right_point_min]] else: result_list.append([left_point_max, right_point_min]) # If i-th interval's right bound is # smaller increment i else increment j found_index_to_step = False for _ in range(len(list_lengths)): right_min_index = np.argmin([x[1] for x in current_time_periods]) if time_period_indices[right_min_index] < list_lengths[right_min_index] - 1: time_period_indices[right_min_index] += 1 right_points[right_min_index] = MININUM_TIME_POINT found_index_to_step = True break if not found_index_to_step: break return result_list # Inspired by https://www.geeksforgeeks.org/find-intersection-of-intervals-given-by-two-lists/ # Python3 implementation to find intersecting intervals """ if __name__ == "__main__": # Test code arr1 = [[0, 4], [5, 10], [13, 20], [24, 25]] arr2 = [[1, 5], [8, 12], [15, 24], [25, 26]] arr3 = [[2, 3], [9, 12], [15, 16], [23, 24]] arr4 = [[9, 12], [23, 24]] print(intersect_time_periods([arr1, arr2])) # [[1, 4], [5, 5], [8, 10], [15, 20], [24, 24], [25, 25]] print(intersect_time_periods([arr1, arr2, arr3])) # [[2, 3], [9, 10], [15, 16], [24, 24]] print(intersect_time_periods([arr1, arr2, arr3, arr4])) # [[9, 10], [24, 24]] print( intersect_time_periods([arr1, arr2], minimum_length=2, first_minimum_length_match_only=True) ) # [[1, 4]] print(intersect_time_periods([arr1], minimum_length=2, first_minimum_length_match_only=True)) # [[0, 4]] """ def transform_kandbox_day_2_postgres_datetime(k_day=None): new_date = datetime.datetime.strftime( datetime.datetime.strptime(k_day, config.KANDBOX_DATE_FORMAT), config.KANDBOX_DATETIME_FORMAT_WITH_MS, ) return new_date def add_days_2_day_string(k_day=None, days=None): new_date = datetime.datetime.strptime(k_day, config.KANDBOX_DATE_FORMAT) + datetime.timedelta( days=days ) return datetime.datetime.strftime(new_date, config.KANDBOX_DATE_FORMAT) def days_between_2_day_string(start_day=None, end_day=None): start_date = datetime.datetime.strptime(start_day, config.KANDBOX_DATE_FORMAT) end_date = datetime.datetime.strptime(end_day, config.KANDBOX_DATE_FORMAT) return (end_date - start_date).days def get_current_day_string(): start_date = datetime.datetime.strptime(datetime.datetime.now(), "YYYYMMDD") return start_date
en
0.69137
# import pandas as pd # import numpy as np # t = "10:15:30" # print(transform_weekly_worker_time_from_rhythm_v6 ('0_0000_00;1_0830_0550;2_0830_0550;3_0830_0550;4_0830_0550;5_0830_0550;6_0830_0240')) # each P is [<=, <] # Inspired by https://www.geeksforgeeks.org/find-intersection-of-intervals-given-by-two-lists/ # Python3 implementation to find intersecting intervals # In fact not used so far, 2020-09-24 23:17:37 Find intersect_time_periods. If minimum_length first 2020-09-22 10:18:58: I created this only because interval tree has not query of length_greater_than , https://github.com/chaimleib/intervaltree Parameters ---------- action : list(float) Input array of worker+day array. The rest of values in action_dict are discarded and re-calculated. minimum_length : int If not None and > 0, it returns maximum one time period which is longer than first_minimum_length_match Returns ------- time_period_list: list A list of time period # i and j pointers for arr1 # and arr2 respectively # n = len(arr1) # m = len(arr2) # Loop through all intervals unless one # of the interval gets exhausted # Left bound for intersecting segment # Right bound for intersecting segment # no need to copy, new list anyway? # If segment is valid # If i-th interval's right bound is # smaller increment i else increment j # Inspired by https://www.geeksforgeeks.org/find-intersection-of-intervals-given-by-two-lists/ # Python3 implementation to find intersecting intervals if __name__ == "__main__": # Test code arr1 = [[0, 4], [5, 10], [13, 20], [24, 25]] arr2 = [[1, 5], [8, 12], [15, 24], [25, 26]] arr3 = [[2, 3], [9, 12], [15, 16], [23, 24]] arr4 = [[9, 12], [23, 24]] print(intersect_time_periods([arr1, arr2])) # [[1, 4], [5, 5], [8, 10], [15, 20], [24, 24], [25, 25]] print(intersect_time_periods([arr1, arr2, arr3])) # [[2, 3], [9, 10], [15, 16], [24, 24]] print(intersect_time_periods([arr1, arr2, arr3, arr4])) # [[9, 10], [24, 24]] print( intersect_time_periods([arr1, arr2], minimum_length=2, first_minimum_length_match_only=True) ) # [[1, 4]] print(intersect_time_periods([arr1], minimum_length=2, first_minimum_length_match_only=True)) # [[0, 4]]
3.033136
3
.qt_for_python/uic/Tran_ui.py
wenboshicn/tools-box
0
6613197
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'e:\github\tools-box\tools-box\pythonGUI\Tran_ui.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Tran_ui(object): def setupUi(self, Tran_ui): Tran_ui.setObjectName("Tran_ui") Tran_ui.resize(792, 602) self.centralwidget = QtWidgets.QWidget(Tran_ui) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(280, 10, 221, 41)) self.label.setObjectName("label") self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(340, 80, 95, 391)) self.widget.setObjectName("widget") self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.pushButton = QtWidgets.QPushButton(self.widget) self.pushButton.setObjectName("pushButton") self.verticalLayout.addWidget(self.pushButton) self.pushButton_2 = QtWidgets.QPushButton(self.widget) self.pushButton_2.setObjectName("pushButton_2") self.verticalLayout.addWidget(self.pushButton_2) self.pushButton_3 = QtWidgets.QPushButton(self.widget) self.pushButton_3.setObjectName("pushButton_3") self.verticalLayout.addWidget(self.pushButton_3) Tran_ui.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(Tran_ui) self.menubar.setGeometry(QtCore.QRect(0, 0, 792, 26)) self.menubar.setObjectName("menubar") Tran_ui.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(Tran_ui) self.statusbar.setObjectName("statusbar") Tran_ui.setStatusBar(self.statusbar) self.retranslateUi(Tran_ui) QtCore.QMetaObject.connectSlotsByName(Tran_ui) def retranslateUi(self, Tran_ui): _translate = QtCore.QCoreApplication.translate Tran_ui.setWindowTitle(_translate("Tran_ui", "MainWindow")) self.label.setText(_translate("Tran_ui", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600;\">CSV-xlsx格式转换工具</span></p></body></html>")) self.pushButton.setText(_translate("Tran_ui", "文件转换")) self.pushButton_2.setText(_translate("Tran_ui", "文件读取")) self.pushButton_3.setText(_translate("Tran_ui", "退出程序"))
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'e:\github\tools-box\tools-box\pythonGUI\Tran_ui.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Tran_ui(object): def setupUi(self, Tran_ui): Tran_ui.setObjectName("Tran_ui") Tran_ui.resize(792, 602) self.centralwidget = QtWidgets.QWidget(Tran_ui) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(280, 10, 221, 41)) self.label.setObjectName("label") self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(340, 80, 95, 391)) self.widget.setObjectName("widget") self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.pushButton = QtWidgets.QPushButton(self.widget) self.pushButton.setObjectName("pushButton") self.verticalLayout.addWidget(self.pushButton) self.pushButton_2 = QtWidgets.QPushButton(self.widget) self.pushButton_2.setObjectName("pushButton_2") self.verticalLayout.addWidget(self.pushButton_2) self.pushButton_3 = QtWidgets.QPushButton(self.widget) self.pushButton_3.setObjectName("pushButton_3") self.verticalLayout.addWidget(self.pushButton_3) Tran_ui.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(Tran_ui) self.menubar.setGeometry(QtCore.QRect(0, 0, 792, 26)) self.menubar.setObjectName("menubar") Tran_ui.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(Tran_ui) self.statusbar.setObjectName("statusbar") Tran_ui.setStatusBar(self.statusbar) self.retranslateUi(Tran_ui) QtCore.QMetaObject.connectSlotsByName(Tran_ui) def retranslateUi(self, Tran_ui): _translate = QtCore.QCoreApplication.translate Tran_ui.setWindowTitle(_translate("Tran_ui", "MainWindow")) self.label.setText(_translate("Tran_ui", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600;\">CSV-xlsx格式转换工具</span></p></body></html>")) self.pushButton.setText(_translate("Tran_ui", "文件转换")) self.pushButton_2.setText(_translate("Tran_ui", "文件读取")) self.pushButton_3.setText(_translate("Tran_ui", "退出程序"))
en
0.814474
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'e:\github\tools-box\tools-box\pythonGUI\Tran_ui.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing.
2.209577
2
project/annotator/forms.py
jasmine95dn/flask_best_worst_scaling
0
6613198
<filename>project/annotator/forms.py # -*- coding: utf-8 -*- """ Forms ****** *Module* ``project.annotator.forms`` This module defines forms used inside of the Annotator-System. """ from flask_wtf import FlaskForm from wtforms import RadioField, PasswordField, StringField from wtforms.validators import InputRequired from ..validators import NotEqualTo, InputValid from ..models import Annotator class TupleForm(FlaskForm): """ Extend :fform:`FlaskForm <flask_wtf.FlaskForm>`. Define form for a tuple with two choices for **best** and **worst** item. Attributes: best_item (:field:`RadioField <wtforms.fields.RadioField>`): answer for the question of best item worst_item (:field:`RadioField <wtforms.fields.RadioField>`): answer for the question of worst item """ best_item = RadioField('Label', coerce=int, validators= [InputRequired(message=u'Choose one item!'), \ NotEqualTo('worst_item', message=u'Two questions for this tuple require 2 different answers') ]) worst_item = RadioField('Label', coerce=int, validators= [InputRequired(message=u'Choose one item!'), NotEqualTo('best_item', message=u'Two questions for this tuple require 2 different answers') ]) class AnnoCheckinForm(FlaskForm): """ Extend :fform:`FlaskForm <flask_wtf.FlaskForm>`. Define form for an annotator login-system. Attributes: keyword (:field:`PasswordField <wtforms.fields.PasswordField>`): keyword to log in name (:field:`StringField <wtforms.fields.StringField>`): pseudoname given by annotator """ keyword = PasswordField('Keyword as annotator', validators=[InputRequired(message=u''), InputValid(model=Annotator, field=Annotator.keyword, message=u'Invalid keyword!') ]) name = StringField('Specify your name', validators=[InputRequired(message=u'')]) def validate(self): """ Override :form:`validate() <wtforms.form.Form.validate>`. Check if the person using this keyword is the first one who logged in by checking his given (pseudo)name. """ if not FlaskForm.validate(self): return False if Annotator.query.filter(Annotator.keyword==self.keyword.data, Annotator.name.isnot(None), Annotator.name==self.name.data).first() \ or Annotator.query.filter(Annotator.keyword==self.keyword.data, Annotator.name==None).first(): return True self.name.errors.append(u'This name is not used for this keyword! Have you logged in with this keyword before? If not, someone has already used it!') return False
<filename>project/annotator/forms.py # -*- coding: utf-8 -*- """ Forms ****** *Module* ``project.annotator.forms`` This module defines forms used inside of the Annotator-System. """ from flask_wtf import FlaskForm from wtforms import RadioField, PasswordField, StringField from wtforms.validators import InputRequired from ..validators import NotEqualTo, InputValid from ..models import Annotator class TupleForm(FlaskForm): """ Extend :fform:`FlaskForm <flask_wtf.FlaskForm>`. Define form for a tuple with two choices for **best** and **worst** item. Attributes: best_item (:field:`RadioField <wtforms.fields.RadioField>`): answer for the question of best item worst_item (:field:`RadioField <wtforms.fields.RadioField>`): answer for the question of worst item """ best_item = RadioField('Label', coerce=int, validators= [InputRequired(message=u'Choose one item!'), \ NotEqualTo('worst_item', message=u'Two questions for this tuple require 2 different answers') ]) worst_item = RadioField('Label', coerce=int, validators= [InputRequired(message=u'Choose one item!'), NotEqualTo('best_item', message=u'Two questions for this tuple require 2 different answers') ]) class AnnoCheckinForm(FlaskForm): """ Extend :fform:`FlaskForm <flask_wtf.FlaskForm>`. Define form for an annotator login-system. Attributes: keyword (:field:`PasswordField <wtforms.fields.PasswordField>`): keyword to log in name (:field:`StringField <wtforms.fields.StringField>`): pseudoname given by annotator """ keyword = PasswordField('Keyword as annotator', validators=[InputRequired(message=u''), InputValid(model=Annotator, field=Annotator.keyword, message=u'Invalid keyword!') ]) name = StringField('Specify your name', validators=[InputRequired(message=u'')]) def validate(self): """ Override :form:`validate() <wtforms.form.Form.validate>`. Check if the person using this keyword is the first one who logged in by checking his given (pseudo)name. """ if not FlaskForm.validate(self): return False if Annotator.query.filter(Annotator.keyword==self.keyword.data, Annotator.name.isnot(None), Annotator.name==self.name.data).first() \ or Annotator.query.filter(Annotator.keyword==self.keyword.data, Annotator.name==None).first(): return True self.name.errors.append(u'This name is not used for this keyword! Have you logged in with this keyword before? If not, someone has already used it!') return False
en
0.564611
# -*- coding: utf-8 -*- Forms ****** *Module* ``project.annotator.forms`` This module defines forms used inside of the Annotator-System. Extend :fform:`FlaskForm <flask_wtf.FlaskForm>`. Define form for a tuple with two choices for **best** and **worst** item. Attributes: best_item (:field:`RadioField <wtforms.fields.RadioField>`): answer for the question of best item worst_item (:field:`RadioField <wtforms.fields.RadioField>`): answer for the question of worst item Extend :fform:`FlaskForm <flask_wtf.FlaskForm>`. Define form for an annotator login-system. Attributes: keyword (:field:`PasswordField <wtforms.fields.PasswordField>`): keyword to log in name (:field:`StringField <wtforms.fields.StringField>`): pseudoname given by annotator Override :form:`validate() <wtforms.form.Form.validate>`. Check if the person using this keyword is the first one who logged in by checking his given (pseudo)name.
3.015868
3
2017/06/py/run.py
Bigsby/aoc
1
6613199
<filename>2017/06/py/run.py #! /usr/bin/python3 import sys import os import time from typing import List, Tuple def solve(numbers: List[int]) -> Tuple[int, int]: numbers_length = len(numbers) previous_lists: List[List[int]] = [] cycles = 0 current_list = list(numbers) while True: if current_list in previous_lists: return cycles, cycles - previous_lists.index(current_list) cycles += 1 previous_lists.append(list(current_list)) update_index = -1 max_number = 0 for index, number in enumerate(current_list): if number > max_number: max_number = number update_index = index current_list[update_index] = 0 while max_number: update_index += 1 current_list[update_index % numbers_length] += 1 max_number -= 1 def get_input(file_path: str) -> List[int]: if not os.path.isfile(file_path): raise FileNotFoundError(file_path) with open(file_path, "r") as file: return [int(i) for i in file.read().split("\t")] def main(): if len(sys.argv) != 2: raise Exception("Please, add input file path as parameter") start = time.perf_counter() part1_result, part2_result = solve(get_input(sys.argv[1])) end = time.perf_counter() print("P1:", part1_result) print("P2:", part2_result) print() print(f"Time: {end - start:.7f}") if __name__ == "__main__": main()
<filename>2017/06/py/run.py #! /usr/bin/python3 import sys import os import time from typing import List, Tuple def solve(numbers: List[int]) -> Tuple[int, int]: numbers_length = len(numbers) previous_lists: List[List[int]] = [] cycles = 0 current_list = list(numbers) while True: if current_list in previous_lists: return cycles, cycles - previous_lists.index(current_list) cycles += 1 previous_lists.append(list(current_list)) update_index = -1 max_number = 0 for index, number in enumerate(current_list): if number > max_number: max_number = number update_index = index current_list[update_index] = 0 while max_number: update_index += 1 current_list[update_index % numbers_length] += 1 max_number -= 1 def get_input(file_path: str) -> List[int]: if not os.path.isfile(file_path): raise FileNotFoundError(file_path) with open(file_path, "r") as file: return [int(i) for i in file.read().split("\t")] def main(): if len(sys.argv) != 2: raise Exception("Please, add input file path as parameter") start = time.perf_counter() part1_result, part2_result = solve(get_input(sys.argv[1])) end = time.perf_counter() print("P1:", part1_result) print("P2:", part2_result) print() print(f"Time: {end - start:.7f}") if __name__ == "__main__": main()
fr
0.498849
#! /usr/bin/python3
3.506759
4
app/crud/analysis.py
chenyg0911/hxa-gloin
0
6613200
<filename>app/crud/analysis.py from motor.motor_asyncio import AsyncIOMotorClient from typing import Optional from app.core.config import database_name, analysis_collection_name from app.models.analysis import AnalysisModel async def get_one_analysis_by_query(conn: AsyncIOMotorClient, query: Optional[dict]): result = await conn[database_name][analysis_collection_name].find_one(query) return AnalysisModel(**result) if result else None async def update_analysis_by_query_with_item(conn: AsyncIOMotorClient, query: Optional[dict], item: Optional[dict]): conn[database_name][analysis_collection_name].update_one(query, {'$set': item}) return True async def get_analysis_list_by_query(conn: AsyncIOMotorClient, query: Optional[dict]): result = conn[database_name][analysis_collection_name].find(query) return [AnalysisModel(**x) async for x in result]
<filename>app/crud/analysis.py from motor.motor_asyncio import AsyncIOMotorClient from typing import Optional from app.core.config import database_name, analysis_collection_name from app.models.analysis import AnalysisModel async def get_one_analysis_by_query(conn: AsyncIOMotorClient, query: Optional[dict]): result = await conn[database_name][analysis_collection_name].find_one(query) return AnalysisModel(**result) if result else None async def update_analysis_by_query_with_item(conn: AsyncIOMotorClient, query: Optional[dict], item: Optional[dict]): conn[database_name][analysis_collection_name].update_one(query, {'$set': item}) return True async def get_analysis_list_by_query(conn: AsyncIOMotorClient, query: Optional[dict]): result = conn[database_name][analysis_collection_name].find(query) return [AnalysisModel(**x) async for x in result]
none
1
2.381112
2
workflow/functional/structure_map.py
Aiwizo/ml-workflow
4
6613201
def structure_map(fn, x): if type(x) is tuple: return tuple(structure_map(fn, value) for value in x) elif type(x) is list: return [structure_map(fn, value) for value in x] elif type(x) is dict: return {key: structure_map(fn, value) for key, value in x.items()} else: return fn(x)
def structure_map(fn, x): if type(x) is tuple: return tuple(structure_map(fn, value) for value in x) elif type(x) is list: return [structure_map(fn, value) for value in x] elif type(x) is dict: return {key: structure_map(fn, value) for key, value in x.items()} else: return fn(x)
none
1
3.827584
4
avidashboard/dashboards/project/loadbalancers/workflows.py
ypraveen/avi-horizon-dashboard
4
6613202
# Copyright 2015, Avi Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from django.utils.translation import ugettext_lazy as _ from django.utils.text import normalize_newlines # noqa from horizon import exceptions from horizon import forms from horizon import workflows from horizon import messages from avidashboard import api LOG = logging.getLogger(__name__) class AddCertificateAction(workflows.Action): multipart = True name = forms.CharField(max_length=255, label=_("Name")) key_source_choices = [('', _('Select Key Source')), ('raw', _('Direct Input')), ('file', _('File'))] cert_source_choices = [('', _('Select Certificate Source')), ('raw', _('Direct Input')), ('file', _('File'))] attributes = {'class': 'switchable', 'data-slug': 'keysource'} key_source = forms.ChoiceField(label=_('Key Source'), choices=key_source_choices, widget=forms.Select(attrs=attributes), required=True) key_file_help = _("Choose a file containing your private key.") key_paste_help = _("Paste a private key (max 16kb).") key_upload = forms.FileField( label=_('Key File'), help_text=key_file_help, widget=forms.FileInput(attrs={ 'class': 'switched', 'data-switch-on': 'keysource', 'data-keysource-file': _('Key File')}), required=False) key_data = forms.CharField( label=_('Key Data'), help_text=key_paste_help, widget=forms.widgets.Textarea(attrs={ 'class': 'switched', 'data-switch-on': 'keysource', 'data-keysource-raw': _('Key Data')}), required=False) passphrase = forms.CharField(max_length=255, widget=forms.PasswordInput(), label=_("Key Passphrase"), required=False) attributes = {'class': 'switchable', 'data-slug': 'certsource'} cert_source = forms.ChoiceField(label=_('Cert Source'), choices=cert_source_choices, widget=forms.Select(attrs=attributes), required=True) cert_file_help = _("Choose a file containing your certificate.") cert_paste_help = _("Paste a certificate (max 16kb).") cert_upload = forms.FileField( label=_('Cert File'), help_text=cert_file_help, widget=forms.FileInput(attrs={ 'class': 'switched', 'data-switch-on': 'certsource', 'data-certsource-file': _('Cert File')}), required=False) cert_data = forms.CharField( label=_('Cert Data'), help_text=cert_paste_help, widget=forms.widgets.Textarea(attrs={ 'class': 'switched', 'data-switch-on': 'certsource', 'data-certsource-raw': _('Cert Data')}), required=False) def __init__(self, request, *args, **kwargs): super(AddCertificateAction, self).__init__(request, *args, **kwargs) def clean(self): cleaned_data = super(AddCertificateAction, self).clean() files = self.request.FILES LOG.info("In cleanup files %s cleaned_date %s", files, cleaned_data) key = self.clean_uploaded_files('key', files) LOG.info("key: %s", key) if key is not None: cleaned_data['key_data'] = key cert = self.clean_uploaded_files('cert', files) LOG.info("cert: %s", cert) if cert is not None: cleaned_data['cert_data'] = cert return cleaned_data def clean_uploaded_files(self, prefix, files): upload_str = prefix + "_upload" has_upload = upload_str in files if has_upload: upload_file = files[upload_str] log_script_name = upload_file.name LOG.info('got upload %s' % log_script_name) if upload_file._size > 16 * 1024: # 16kb msg = _('File exceeds maximum size (16kb)') raise forms.ValidationError(msg) else: script = upload_file.read() LOG.info("script: %s", script) if script != "": try: normalize_newlines(script) except Exception as e: msg = _('There was a problem parsing the' ' %(prefix)s: %(error)s') msg = msg % {'prefix': prefix, 'error': e} raise forms.ValidationError(msg) return script else: return None class Meta(object): name = _("Add New Certificate") permissions = ('openstack.services.network',) help_text = _("Use PEM for key and certificate format") class AddCertificateStep(workflows.Step): action_class = AddCertificateAction contributes = ("name", "key_data", "passphrase", "cert_data") def contribute(self, data, context): context = super(AddCertificateStep, self).contribute(data, context) if data: return context class AddCertificate(workflows.Workflow): multipart = True slug = "addcertificate" name = _("Add Certificate") finalize_button_name = _("Add") success_message = _('Added certificate') failure_message = _('Unable to add certificate') success_url = "horizon:project:loadbalancers:index" default_steps = (AddCertificateStep,) def handle(self, request, context): try: context['certificate_id'] = api.avi.add_cert( request, **context).get('id') return True except Exception as e: messages.error(request, _("Unable to add certificate: %s" % e)) #exceptions.handle(request, _("Unable to add certificate.")) return False class AssociateCertificateAction(workflows.Action): vip_cert = forms.ChoiceField(label=_("VIP Certificate")) pool_cert = forms.ChoiceField(label=_("Pool Certificate"), required=False) pool_proto = forms.CharField(widget=forms.HiddenInput()) choices = [('no', 'No'), ('yes', 'Yes')] redirect_attrs = {'class': 'switchable', 'data-slug': 'redirect'} redirect_choice = forms.ChoiceField( label=_("Support and redirect HTTP traffic?"), required=True, choices=choices, widget=forms.Select(attrs=redirect_attrs)) http_port = forms.IntegerField( label=_("HTTP Port"), required=False, widget=forms.widgets.NumberInput(attrs={ 'class': 'switched', 'data-switch-on': 'redirect', 'data-redirect-yes': 'Port Number', }), initial=80) def __init__(self, request, *args, **kwargs): # print "request %s args %s kwargs %s" % (request, args, kwargs) super(AssociateCertificateAction, self).__init__(request, *args, **kwargs) certs = api.avi.certs_list(request, request.user.tenant_name) pool_cert_choices = [("", _("Select a Certificate"))] [pool_cert_choices.append((cert.name, cert.name)) for cert in certs] if args[0].has_key('pool_id') and args[0]['pool_id']: self.fields["pool_cert"].choices = pool_cert_choices self.fields["pool_cert"].initial = api.avi.get_pool_cert(request, args[0]["pool_id"]) self.fields["pool_cert"].help_text = _( "Pool Certificate (optional):\n" "A certificate that the load-balancer, as a client, " "presents to the backend servers (members) for " "authentication. Leave this field empty unless the " "backend servers are configured for client " "certificate authentication.") else: del self.fields["pool_cert"] self.fields["vip_cert"].choices = pool_cert_choices avi_vip = api.avi.get_vip(request, args[0]["vip_id"]) self.fields["vip_cert"].initial = api.avi.get_vip_cert(avi_vip) self.fields["vip_cert"].help_text = _( "VIP Certificate:\n" "A certificate that the load-balancer, as a server, " "presents to an end-user (or browser)\n\n" ) self.fields["http_port"].help_text = _( "HTTP Port:\n" "If you want to support HTTP traffic on the same VIP, " "please specify " "a port for the HTTP Traffic. The HTTP requests are " "automatically redirected to the HTTPS urls." ) self.fields["pool_proto"].initial = args[0]["pool_proto"] return def clean(self): cleaned_data = super(AssociateCertificateAction, self).clean() return cleaned_data class Meta(object): name = _("Associate Certificates") permissions = ('openstack.services.network',) help_text = _("Associate certificates.\n\n" "Specify certificates to associate.") class AssociateCertificateStep(workflows.Step): action_class = AssociateCertificateAction contributes = ("pool_cert", "vip_cert", "pool_proto", "redirect_choice", "http_port") depends_on = ("pool_id", "vip_id", "pool_proto", "redirect_choice", "http_port") def contribute(self, data, context): context = super(AssociateCertificateStep, self).contribute(data, context) if data: return context class AssociateCertificate(workflows.Workflow): slug = "associatecertificate" name = _("Associate Certificates") finalize_button_name = _("Associate") success_message = _('Associated certificates') failure_message = _('Unable to associate certificates') success_url = "horizon:project:loadbalancers:index" default_steps = (AssociateCertificateStep,) def handle(self, request, context): try: api.avi.associate_certs(request, **context) return True except Exception: messages.error(request, _("Unable to associate certificates.")) #exceptions.handle(request, _("Unable to associate certificates.")) return False class DisassociateCertificateAction(workflows.Action): vip_cert = forms.ChoiceField(label=_("VIP Certificate")) pool_cert = forms.ChoiceField(label=_("Pool Certificate"), required=False) pool_proto = forms.CharField(widget=forms.HiddenInput()) def __init__(self, request, *args, **kwargs): #print "request %s args %s kwargs %s" % (request, args, kwargs) super(DisassociateCertificateAction, self).__init__(request, *args, **kwargs) pcert = None if args[0].has_key('pool_id') and args[0]['pool_id']: pcert = api.avi.get_pool_cert(request, args[0]["pool_id"]) if pcert: self.fields["pool_cert"].choices = [(pcert, pcert)] self.fields["pool_cert"].initial = pcert if not pcert: del self.fields["pool_cert"] vip = api.avi.get_vip(request, args[0]["vip_id"]) vcert = api.avi.get_vip_cert(vip) self.fields["vip_cert"].choices = [(vcert, vcert)] self.fields["vip_cert"].initial = vcert self.fields["pool_proto"].initial = args[0]["pool_proto"] return def clean(self): cleaned_data = super(DisassociateCertificateAction, self).clean() return cleaned_data class Meta(object): name = _("Disassociate Certificates") permissions = ('openstack.services.network',) help_text = _("Disassociate certificates.\n\n" "Specify certificates to disassociate") class DisassociateCertificateStep(workflows.Step): action_class = DisassociateCertificateAction contributes = ("pool_cert", "vip_cert", "pool_proto") depends_on = ("pool_id", "vip_id", "pool_proto") def contribute(self, data, context): context = super(DisassociateCertificateStep, self).contribute(data, context) if data: return context class DisassociateCertificate(workflows.Workflow): slug = "disassociatecertificate" name = _("Disassociate Certificates") finalize_button_name = _("Disassociate") success_message = _('Disassociated certificates') failure_message = _('Unable to disassociate certificates') success_url = "horizon:project:loadbalancers:index" default_steps = (DisassociateCertificateStep,) def handle(self, request, context): try: api.avi.disassociate_certs(request, **context) return True except Exception: messages.error(request, _("Unable to disassociate certificates.")) #exceptions.handle(request, _("Unable to disassociate certificates.")) return False
# Copyright 2015, Avi Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from django.utils.translation import ugettext_lazy as _ from django.utils.text import normalize_newlines # noqa from horizon import exceptions from horizon import forms from horizon import workflows from horizon import messages from avidashboard import api LOG = logging.getLogger(__name__) class AddCertificateAction(workflows.Action): multipart = True name = forms.CharField(max_length=255, label=_("Name")) key_source_choices = [('', _('Select Key Source')), ('raw', _('Direct Input')), ('file', _('File'))] cert_source_choices = [('', _('Select Certificate Source')), ('raw', _('Direct Input')), ('file', _('File'))] attributes = {'class': 'switchable', 'data-slug': 'keysource'} key_source = forms.ChoiceField(label=_('Key Source'), choices=key_source_choices, widget=forms.Select(attrs=attributes), required=True) key_file_help = _("Choose a file containing your private key.") key_paste_help = _("Paste a private key (max 16kb).") key_upload = forms.FileField( label=_('Key File'), help_text=key_file_help, widget=forms.FileInput(attrs={ 'class': 'switched', 'data-switch-on': 'keysource', 'data-keysource-file': _('Key File')}), required=False) key_data = forms.CharField( label=_('Key Data'), help_text=key_paste_help, widget=forms.widgets.Textarea(attrs={ 'class': 'switched', 'data-switch-on': 'keysource', 'data-keysource-raw': _('Key Data')}), required=False) passphrase = forms.CharField(max_length=255, widget=forms.PasswordInput(), label=_("Key Passphrase"), required=False) attributes = {'class': 'switchable', 'data-slug': 'certsource'} cert_source = forms.ChoiceField(label=_('Cert Source'), choices=cert_source_choices, widget=forms.Select(attrs=attributes), required=True) cert_file_help = _("Choose a file containing your certificate.") cert_paste_help = _("Paste a certificate (max 16kb).") cert_upload = forms.FileField( label=_('Cert File'), help_text=cert_file_help, widget=forms.FileInput(attrs={ 'class': 'switched', 'data-switch-on': 'certsource', 'data-certsource-file': _('Cert File')}), required=False) cert_data = forms.CharField( label=_('Cert Data'), help_text=cert_paste_help, widget=forms.widgets.Textarea(attrs={ 'class': 'switched', 'data-switch-on': 'certsource', 'data-certsource-raw': _('Cert Data')}), required=False) def __init__(self, request, *args, **kwargs): super(AddCertificateAction, self).__init__(request, *args, **kwargs) def clean(self): cleaned_data = super(AddCertificateAction, self).clean() files = self.request.FILES LOG.info("In cleanup files %s cleaned_date %s", files, cleaned_data) key = self.clean_uploaded_files('key', files) LOG.info("key: %s", key) if key is not None: cleaned_data['key_data'] = key cert = self.clean_uploaded_files('cert', files) LOG.info("cert: %s", cert) if cert is not None: cleaned_data['cert_data'] = cert return cleaned_data def clean_uploaded_files(self, prefix, files): upload_str = prefix + "_upload" has_upload = upload_str in files if has_upload: upload_file = files[upload_str] log_script_name = upload_file.name LOG.info('got upload %s' % log_script_name) if upload_file._size > 16 * 1024: # 16kb msg = _('File exceeds maximum size (16kb)') raise forms.ValidationError(msg) else: script = upload_file.read() LOG.info("script: %s", script) if script != "": try: normalize_newlines(script) except Exception as e: msg = _('There was a problem parsing the' ' %(prefix)s: %(error)s') msg = msg % {'prefix': prefix, 'error': e} raise forms.ValidationError(msg) return script else: return None class Meta(object): name = _("Add New Certificate") permissions = ('openstack.services.network',) help_text = _("Use PEM for key and certificate format") class AddCertificateStep(workflows.Step): action_class = AddCertificateAction contributes = ("name", "key_data", "passphrase", "cert_data") def contribute(self, data, context): context = super(AddCertificateStep, self).contribute(data, context) if data: return context class AddCertificate(workflows.Workflow): multipart = True slug = "addcertificate" name = _("Add Certificate") finalize_button_name = _("Add") success_message = _('Added certificate') failure_message = _('Unable to add certificate') success_url = "horizon:project:loadbalancers:index" default_steps = (AddCertificateStep,) def handle(self, request, context): try: context['certificate_id'] = api.avi.add_cert( request, **context).get('id') return True except Exception as e: messages.error(request, _("Unable to add certificate: %s" % e)) #exceptions.handle(request, _("Unable to add certificate.")) return False class AssociateCertificateAction(workflows.Action): vip_cert = forms.ChoiceField(label=_("VIP Certificate")) pool_cert = forms.ChoiceField(label=_("Pool Certificate"), required=False) pool_proto = forms.CharField(widget=forms.HiddenInput()) choices = [('no', 'No'), ('yes', 'Yes')] redirect_attrs = {'class': 'switchable', 'data-slug': 'redirect'} redirect_choice = forms.ChoiceField( label=_("Support and redirect HTTP traffic?"), required=True, choices=choices, widget=forms.Select(attrs=redirect_attrs)) http_port = forms.IntegerField( label=_("HTTP Port"), required=False, widget=forms.widgets.NumberInput(attrs={ 'class': 'switched', 'data-switch-on': 'redirect', 'data-redirect-yes': 'Port Number', }), initial=80) def __init__(self, request, *args, **kwargs): # print "request %s args %s kwargs %s" % (request, args, kwargs) super(AssociateCertificateAction, self).__init__(request, *args, **kwargs) certs = api.avi.certs_list(request, request.user.tenant_name) pool_cert_choices = [("", _("Select a Certificate"))] [pool_cert_choices.append((cert.name, cert.name)) for cert in certs] if args[0].has_key('pool_id') and args[0]['pool_id']: self.fields["pool_cert"].choices = pool_cert_choices self.fields["pool_cert"].initial = api.avi.get_pool_cert(request, args[0]["pool_id"]) self.fields["pool_cert"].help_text = _( "Pool Certificate (optional):\n" "A certificate that the load-balancer, as a client, " "presents to the backend servers (members) for " "authentication. Leave this field empty unless the " "backend servers are configured for client " "certificate authentication.") else: del self.fields["pool_cert"] self.fields["vip_cert"].choices = pool_cert_choices avi_vip = api.avi.get_vip(request, args[0]["vip_id"]) self.fields["vip_cert"].initial = api.avi.get_vip_cert(avi_vip) self.fields["vip_cert"].help_text = _( "VIP Certificate:\n" "A certificate that the load-balancer, as a server, " "presents to an end-user (or browser)\n\n" ) self.fields["http_port"].help_text = _( "HTTP Port:\n" "If you want to support HTTP traffic on the same VIP, " "please specify " "a port for the HTTP Traffic. The HTTP requests are " "automatically redirected to the HTTPS urls." ) self.fields["pool_proto"].initial = args[0]["pool_proto"] return def clean(self): cleaned_data = super(AssociateCertificateAction, self).clean() return cleaned_data class Meta(object): name = _("Associate Certificates") permissions = ('openstack.services.network',) help_text = _("Associate certificates.\n\n" "Specify certificates to associate.") class AssociateCertificateStep(workflows.Step): action_class = AssociateCertificateAction contributes = ("pool_cert", "vip_cert", "pool_proto", "redirect_choice", "http_port") depends_on = ("pool_id", "vip_id", "pool_proto", "redirect_choice", "http_port") def contribute(self, data, context): context = super(AssociateCertificateStep, self).contribute(data, context) if data: return context class AssociateCertificate(workflows.Workflow): slug = "associatecertificate" name = _("Associate Certificates") finalize_button_name = _("Associate") success_message = _('Associated certificates') failure_message = _('Unable to associate certificates') success_url = "horizon:project:loadbalancers:index" default_steps = (AssociateCertificateStep,) def handle(self, request, context): try: api.avi.associate_certs(request, **context) return True except Exception: messages.error(request, _("Unable to associate certificates.")) #exceptions.handle(request, _("Unable to associate certificates.")) return False class DisassociateCertificateAction(workflows.Action): vip_cert = forms.ChoiceField(label=_("VIP Certificate")) pool_cert = forms.ChoiceField(label=_("Pool Certificate"), required=False) pool_proto = forms.CharField(widget=forms.HiddenInput()) def __init__(self, request, *args, **kwargs): #print "request %s args %s kwargs %s" % (request, args, kwargs) super(DisassociateCertificateAction, self).__init__(request, *args, **kwargs) pcert = None if args[0].has_key('pool_id') and args[0]['pool_id']: pcert = api.avi.get_pool_cert(request, args[0]["pool_id"]) if pcert: self.fields["pool_cert"].choices = [(pcert, pcert)] self.fields["pool_cert"].initial = pcert if not pcert: del self.fields["pool_cert"] vip = api.avi.get_vip(request, args[0]["vip_id"]) vcert = api.avi.get_vip_cert(vip) self.fields["vip_cert"].choices = [(vcert, vcert)] self.fields["vip_cert"].initial = vcert self.fields["pool_proto"].initial = args[0]["pool_proto"] return def clean(self): cleaned_data = super(DisassociateCertificateAction, self).clean() return cleaned_data class Meta(object): name = _("Disassociate Certificates") permissions = ('openstack.services.network',) help_text = _("Disassociate certificates.\n\n" "Specify certificates to disassociate") class DisassociateCertificateStep(workflows.Step): action_class = DisassociateCertificateAction contributes = ("pool_cert", "vip_cert", "pool_proto") depends_on = ("pool_id", "vip_id", "pool_proto") def contribute(self, data, context): context = super(DisassociateCertificateStep, self).contribute(data, context) if data: return context class DisassociateCertificate(workflows.Workflow): slug = "disassociatecertificate" name = _("Disassociate Certificates") finalize_button_name = _("Disassociate") success_message = _('Disassociated certificates') failure_message = _('Unable to disassociate certificates') success_url = "horizon:project:loadbalancers:index" default_steps = (DisassociateCertificateStep,) def handle(self, request, context): try: api.avi.disassociate_certs(request, **context) return True except Exception: messages.error(request, _("Unable to disassociate certificates.")) #exceptions.handle(request, _("Unable to disassociate certificates.")) return False
en
0.716876
# Copyright 2015, Avi Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # noqa # 16kb #exceptions.handle(request, _("Unable to add certificate.")) # print "request %s args %s kwargs %s" % (request, args, kwargs) #exceptions.handle(request, _("Unable to associate certificates.")) #print "request %s args %s kwargs %s" % (request, args, kwargs) #exceptions.handle(request, _("Unable to disassociate certificates."))
1.853376
2
iso8583/decoder.py
ondiekisteven/pyiso8583
11
6613203
from typing import Any, Dict, Mapping, Set, Tuple, Type, Union __all__ = ["decode", "DecodeError"] DecodedDict = Dict[str, str] EncodedDict = Dict[str, Dict[str, bytes]] SpecDict = Mapping[str, Mapping[str, Any]] class DecodeError(ValueError): r"""Subclass of ValueError that describes ISO8583 decoding error. Attributes ---------- msg : str The unformatted error message s : bytes or bytearray The ISO8583 bytes instance being parsed doc_dec : dict Dict containing partially decoded ISO8583 data doc_enc : dict Dict containing partially encoded ISO8583 data pos : int The start index where ISO8583 bytes data failed parsing field : str The ISO8583 field where parsing failed """ def __init__( self, msg: str, s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, pos: int, field: str, ): errmsg = f"{msg}: field {field} pos {pos}" ValueError.__init__(self, errmsg) self.msg = msg self.s = s self.doc_dec = doc_dec self.doc_enc = doc_enc self.field = field self.pos = pos def __reduce__( self, ) -> Tuple[ Type["DecodeError"], Tuple[str, Union[bytes, bytearray], DecodedDict, EncodedDict, int, str], ]: return ( self.__class__, (self.msg, self.s, self.doc_dec, self.doc_enc, self.pos, self.field), ) def decode( s: Union[bytes, bytearray], spec: SpecDict ) -> Tuple[DecodedDict, EncodedDict]: r"""Deserialize a bytes or bytearray instance containing ISO8583 data to a Python dict. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data Raises ------ DecodeError An error decoding ISO8583 bytearray TypeError `s` must be a bytes or bytearray instance Examples -------- >>> import pprint >>> import iso8583 >>> from iso8583.specs import default_ascii as spec >>> s = b"02004010100000000000161234567890123456123456111" >>> doc_dec, doc_enc = iso8583.decode(s, spec) >>> pprint.pprint(doc_dec) {'12': '123456', '2': '1234567890123456', '20': '111', 'p': '4010100000000000', 't': '0200'} """ if not isinstance(s, (bytes, bytearray)): raise TypeError( f"Encoded ISO8583 data must be bytes or bytearray, not {s.__class__.__name__}" ) doc_dec: DecodedDict = {} doc_enc: EncodedDict = {} fields: Set[int] = set() idx = 0 idx = _decode_header(s, doc_dec, doc_enc, idx, spec) idx = _decode_type(s, doc_dec, doc_enc, idx, spec) idx = _decode_bitmaps(s, doc_dec, doc_enc, idx, spec, fields) # `field_key` can be used to throw an exception after the loop. # So, create it here in case the `fields` set is empty # and never enters the loop to create the variable. # Set `field_key` to the last mandatory one: primary bitmap. field_key = "p" for field_key in [str(i) for i in sorted(fields)]: # Secondary bitmap is already decoded in _decode_bitmaps if field_key == "1": continue idx = _decode_field(s, doc_dec, doc_enc, idx, field_key, spec) if idx != len(s): raise DecodeError( "Extra data after last field", s, doc_dec, doc_enc, idx, field_key ) return doc_dec, doc_enc # # Private interface # def _decode_header( s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, idx: int, spec: SpecDict, ) -> int: r"""Decode ISO8583 header data if present. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of the header ended Raises ------ DecodeError An error decoding ISO8583 bytearray. """ # Header is not expected according to specifications if spec["h"]["max_len"] <= 0: return idx return _decode_field(s, doc_dec, doc_enc, idx, "h", spec) def _decode_type( s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, idx: int, spec: SpecDict, ) -> int: r"""Decode ISO8583 message type. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of message type ended Raises ------ DecodeError An error decoding ISO8583 bytearray. """ # Message type is a set length in ISO8583 if spec["t"]["data_enc"] == "b": f_len = 2 else: f_len = 4 doc_dec["t"] = "" doc_enc["t"] = {"len": b"", "data": bytes(s[idx : idx + f_len])} if len(s[idx : idx + f_len]) != f_len: raise DecodeError( f"Field data is {len(s[idx:idx + f_len])} bytes, expecting {f_len}", s, doc_dec, doc_enc, idx, "t", ) if spec["t"]["data_enc"] == "b": doc_dec["t"] = s[idx : idx + f_len].hex().upper() else: try: doc_dec["t"] = s[idx : idx + f_len].decode(spec["t"]["data_enc"]) except LookupError: raise DecodeError( "Failed to decode field, unknown encoding specified", s, doc_dec, doc_enc, idx, "t", ) from None except Exception: raise DecodeError( "Failed to decode field, invalid data", s, doc_dec, doc_enc, idx, "t", ) from None return idx + f_len def _decode_bitmaps( s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, idx: int, spec: SpecDict, fields: Set[int], ) -> int: r"""Decode ISO8583 primary and secondary bitmaps. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. fields: set Will be populated with enabled field numbers Returns ------- int Index in ISO8583 byte array where parsing of bitmaps ended Raises ------ DecodeError An error decoding ISO8583 bytearray. """ # Primary bitmap is a set length in ISO8583 if spec["p"]["data_enc"] == "b": f_len = 8 else: f_len = 16 doc_dec["p"] = "" doc_enc["p"] = {"len": b"", "data": bytes(s[idx : idx + f_len])} if len(s[idx : idx + f_len]) != f_len: raise DecodeError( f"Field data is {len(s[idx:idx + f_len])} bytes, expecting {f_len}", s, doc_dec, doc_enc, idx, "p", ) if spec["p"]["data_enc"] == "b": doc_dec["p"] = s[idx : idx + f_len].hex().upper() bm = s[idx : idx + f_len] else: try: doc_dec["p"] = s[idx : idx + f_len].decode(spec["p"]["data_enc"]) except LookupError: raise DecodeError( "Failed to decode field, unknown encoding specified", s, doc_dec, doc_enc, idx, "p", ) from None except Exception: raise DecodeError( "Failed to decode field, invalid data", s, doc_dec, doc_enc, idx, "p", ) from None try: bm = bytes.fromhex(doc_dec["p"]) except Exception: raise DecodeError( "Failed to decode field, non-hex data", s, doc_dec, doc_enc, idx, "p", ) from None fields.update( [ byte_idx * 8 + bit for bit in range(1, 9) for byte_idx, byte in enumerate(bm) if byte >> (8 - bit) & 1 ] ) idx += f_len # No need to produce secondary bitmap if it's not required if 1 not in fields: return idx # Decode secondary bitmap # Secondary bitmap is a set length in ISO8583 if spec["1"]["data_enc"] == "b": f_len = 8 else: f_len = 16 doc_dec["1"] = "" doc_enc["1"] = {"len": b"", "data": bytes(s[idx : idx + f_len])} if len(s[idx : idx + f_len]) != f_len: raise DecodeError( f"Field data is {len(s[idx:idx + f_len])} bytes, expecting {f_len}", s, doc_dec, doc_enc, idx, "1", ) if spec["1"]["data_enc"] == "b": doc_dec["1"] = s[idx : idx + f_len].hex().upper() bm = s[idx : idx + f_len] else: try: doc_dec["1"] = s[idx : idx + f_len].decode(spec["1"]["data_enc"]) except LookupError: raise DecodeError( "Failed to decode field, unknown encoding specified", s, doc_dec, doc_enc, idx, "1", ) from None except Exception: raise DecodeError( "Failed to decode field, invalid data", s, doc_dec, doc_enc, idx, "1", ) from None try: bm = bytes.fromhex(doc_dec["1"]) except Exception: raise DecodeError( "Failed to decode field, non-hex data", s, doc_dec, doc_enc, idx, "1", ) from None fields.update( [ 64 + byte_idx * 8 + bit for bit in range(1, 9) for byte_idx, byte in enumerate(bm) if byte >> (8 - bit) & 1 ] ) return idx + f_len def _decode_field( s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, idx: int, field_key: str, spec: SpecDict, ) -> int: r"""Decode ISO8583 individual fields. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array field_key : str Field ID to be decoded spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of the field ended Raises ------ DecodeError An error decoding ISO8583 bytearray. """ len_type = spec[field_key]["len_type"] # Optional field added in v2.1. Prior specs do not have it. len_count = spec[field_key].get("len_count", "bytes") doc_dec[field_key] = "" doc_enc[field_key] = {"len": bytes(s[idx : idx + len_type]), "data": b""} if len(s[idx : idx + len_type]) != len_type: raise DecodeError( f"Field length is {len(s[idx:idx + len_type])} bytes wide, expecting {len_type}", s, doc_dec, doc_enc, idx, field_key, ) # Parse field length if present. # For fixed-length fields max_len is the length. if len_type == 0: enc_field_len: int = spec[field_key]["max_len"] # Variable field length else: # BCD length if spec[field_key]["len_enc"] in {"b", "bcd"}: try: enc_field_len = int(s[idx : idx + len_type].hex(), 10) except Exception: raise DecodeError( "Failed to decode field length, invalid BCD data", s, doc_dec, doc_enc, idx, field_key, ) from None # Text length else: try: decoded_length = s[idx : idx + len_type].decode( spec[field_key]["len_enc"] ) except LookupError: raise DecodeError( "Failed to decode field length, unknown encoding specified", s, doc_dec, doc_enc, idx, field_key, ) from None except Exception: raise DecodeError( "Failed to decode field length, invalid data", s, doc_dec, doc_enc, idx, field_key, ) from None try: enc_field_len = int(decoded_length) except Exception: raise DecodeError( "Failed to decode field length, non-numeric data", s, doc_dec, doc_enc, idx, field_key, ) from None if enc_field_len > spec[field_key]["max_len"]: raise DecodeError( f"Field data is {enc_field_len} {len_count}, larger than maximum {spec[field_key]['max_len']}", s, doc_dec, doc_enc, idx, field_key, ) idx += len_type # Do not parse zero-length field if enc_field_len == 0: return idx # Encoded field length can be in bytes or half bytes (nibbles) # Convert nibbles to bytes if needed if len_count == "nibbles": if enc_field_len & 1: byte_field_len = (enc_field_len + 1) // 2 else: byte_field_len = enc_field_len // 2 else: byte_field_len = enc_field_len # Parse field data doc_enc[field_key]["data"] = bytes(s[idx : idx + byte_field_len]) if len(doc_enc[field_key]["data"]) != byte_field_len: if len_count == "nibbles": actual_field_len = len(doc_enc[field_key]["data"]) * 2 else: actual_field_len = len(doc_enc[field_key]["data"]) raise DecodeError( f"Field data is {actual_field_len} {len_count}, expecting {enc_field_len}", s, doc_dec, doc_enc, idx, field_key, ) if spec[field_key]["data_enc"] == "b": doc_dec[field_key] = doc_enc[field_key]["data"].hex().upper() if len_count == "nibbles" and enc_field_len & 1: doc_dec[field_key] = _remove_pad_field( s, idx, doc_dec, doc_enc, field_key, spec, enc_field_len ) else: try: doc_dec[field_key] = doc_enc[field_key]["data"].decode( spec[field_key]["data_enc"] ) except LookupError: raise DecodeError( "Failed to decode field, unknown encoding specified", s, doc_dec, doc_enc, idx, field_key, ) from None except Exception: raise DecodeError( "Failed to decode field, invalid data", s, doc_dec, doc_enc, idx, field_key, ) from None return idx + byte_field_len def _remove_pad_field( s: Union[bytes, bytearray], idx: int, doc_dec: DecodedDict, doc_enc: EncodedDict, field_key: str, spec: SpecDict, enc_field_len: int, ) -> str: r"""Remove left or right pad from a BCD or hex field. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data idx : int Current index in ISO8583 byte array doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data field_key : str Field ID to remove pad from spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. enc_field_len : int Number of nibbles expected in the field Returns ------- str Field data without pad Raises ------ DecodeError An error decoding ISO8583 bytearray. """ pad: str = spec[field_key].get("left_pad", "")[:1] if len(pad) > 0 and doc_dec[field_key][:1] == pad: return doc_dec[field_key][1:] pad = spec[field_key].get("right_pad", "")[:1] if len(pad) > 0 and doc_dec[field_key][-1:] == pad: return doc_dec[field_key][:-1] raise DecodeError( f"Field data is {len(doc_dec[field_key])} nibbles, expecting {enc_field_len}", s, doc_dec, doc_enc, idx, field_key, )
from typing import Any, Dict, Mapping, Set, Tuple, Type, Union __all__ = ["decode", "DecodeError"] DecodedDict = Dict[str, str] EncodedDict = Dict[str, Dict[str, bytes]] SpecDict = Mapping[str, Mapping[str, Any]] class DecodeError(ValueError): r"""Subclass of ValueError that describes ISO8583 decoding error. Attributes ---------- msg : str The unformatted error message s : bytes or bytearray The ISO8583 bytes instance being parsed doc_dec : dict Dict containing partially decoded ISO8583 data doc_enc : dict Dict containing partially encoded ISO8583 data pos : int The start index where ISO8583 bytes data failed parsing field : str The ISO8583 field where parsing failed """ def __init__( self, msg: str, s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, pos: int, field: str, ): errmsg = f"{msg}: field {field} pos {pos}" ValueError.__init__(self, errmsg) self.msg = msg self.s = s self.doc_dec = doc_dec self.doc_enc = doc_enc self.field = field self.pos = pos def __reduce__( self, ) -> Tuple[ Type["DecodeError"], Tuple[str, Union[bytes, bytearray], DecodedDict, EncodedDict, int, str], ]: return ( self.__class__, (self.msg, self.s, self.doc_dec, self.doc_enc, self.pos, self.field), ) def decode( s: Union[bytes, bytearray], spec: SpecDict ) -> Tuple[DecodedDict, EncodedDict]: r"""Deserialize a bytes or bytearray instance containing ISO8583 data to a Python dict. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data Raises ------ DecodeError An error decoding ISO8583 bytearray TypeError `s` must be a bytes or bytearray instance Examples -------- >>> import pprint >>> import iso8583 >>> from iso8583.specs import default_ascii as spec >>> s = b"02004010100000000000161234567890123456123456111" >>> doc_dec, doc_enc = iso8583.decode(s, spec) >>> pprint.pprint(doc_dec) {'12': '123456', '2': '1234567890123456', '20': '111', 'p': '4010100000000000', 't': '0200'} """ if not isinstance(s, (bytes, bytearray)): raise TypeError( f"Encoded ISO8583 data must be bytes or bytearray, not {s.__class__.__name__}" ) doc_dec: DecodedDict = {} doc_enc: EncodedDict = {} fields: Set[int] = set() idx = 0 idx = _decode_header(s, doc_dec, doc_enc, idx, spec) idx = _decode_type(s, doc_dec, doc_enc, idx, spec) idx = _decode_bitmaps(s, doc_dec, doc_enc, idx, spec, fields) # `field_key` can be used to throw an exception after the loop. # So, create it here in case the `fields` set is empty # and never enters the loop to create the variable. # Set `field_key` to the last mandatory one: primary bitmap. field_key = "p" for field_key in [str(i) for i in sorted(fields)]: # Secondary bitmap is already decoded in _decode_bitmaps if field_key == "1": continue idx = _decode_field(s, doc_dec, doc_enc, idx, field_key, spec) if idx != len(s): raise DecodeError( "Extra data after last field", s, doc_dec, doc_enc, idx, field_key ) return doc_dec, doc_enc # # Private interface # def _decode_header( s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, idx: int, spec: SpecDict, ) -> int: r"""Decode ISO8583 header data if present. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of the header ended Raises ------ DecodeError An error decoding ISO8583 bytearray. """ # Header is not expected according to specifications if spec["h"]["max_len"] <= 0: return idx return _decode_field(s, doc_dec, doc_enc, idx, "h", spec) def _decode_type( s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, idx: int, spec: SpecDict, ) -> int: r"""Decode ISO8583 message type. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of message type ended Raises ------ DecodeError An error decoding ISO8583 bytearray. """ # Message type is a set length in ISO8583 if spec["t"]["data_enc"] == "b": f_len = 2 else: f_len = 4 doc_dec["t"] = "" doc_enc["t"] = {"len": b"", "data": bytes(s[idx : idx + f_len])} if len(s[idx : idx + f_len]) != f_len: raise DecodeError( f"Field data is {len(s[idx:idx + f_len])} bytes, expecting {f_len}", s, doc_dec, doc_enc, idx, "t", ) if spec["t"]["data_enc"] == "b": doc_dec["t"] = s[idx : idx + f_len].hex().upper() else: try: doc_dec["t"] = s[idx : idx + f_len].decode(spec["t"]["data_enc"]) except LookupError: raise DecodeError( "Failed to decode field, unknown encoding specified", s, doc_dec, doc_enc, idx, "t", ) from None except Exception: raise DecodeError( "Failed to decode field, invalid data", s, doc_dec, doc_enc, idx, "t", ) from None return idx + f_len def _decode_bitmaps( s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, idx: int, spec: SpecDict, fields: Set[int], ) -> int: r"""Decode ISO8583 primary and secondary bitmaps. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. fields: set Will be populated with enabled field numbers Returns ------- int Index in ISO8583 byte array where parsing of bitmaps ended Raises ------ DecodeError An error decoding ISO8583 bytearray. """ # Primary bitmap is a set length in ISO8583 if spec["p"]["data_enc"] == "b": f_len = 8 else: f_len = 16 doc_dec["p"] = "" doc_enc["p"] = {"len": b"", "data": bytes(s[idx : idx + f_len])} if len(s[idx : idx + f_len]) != f_len: raise DecodeError( f"Field data is {len(s[idx:idx + f_len])} bytes, expecting {f_len}", s, doc_dec, doc_enc, idx, "p", ) if spec["p"]["data_enc"] == "b": doc_dec["p"] = s[idx : idx + f_len].hex().upper() bm = s[idx : idx + f_len] else: try: doc_dec["p"] = s[idx : idx + f_len].decode(spec["p"]["data_enc"]) except LookupError: raise DecodeError( "Failed to decode field, unknown encoding specified", s, doc_dec, doc_enc, idx, "p", ) from None except Exception: raise DecodeError( "Failed to decode field, invalid data", s, doc_dec, doc_enc, idx, "p", ) from None try: bm = bytes.fromhex(doc_dec["p"]) except Exception: raise DecodeError( "Failed to decode field, non-hex data", s, doc_dec, doc_enc, idx, "p", ) from None fields.update( [ byte_idx * 8 + bit for bit in range(1, 9) for byte_idx, byte in enumerate(bm) if byte >> (8 - bit) & 1 ] ) idx += f_len # No need to produce secondary bitmap if it's not required if 1 not in fields: return idx # Decode secondary bitmap # Secondary bitmap is a set length in ISO8583 if spec["1"]["data_enc"] == "b": f_len = 8 else: f_len = 16 doc_dec["1"] = "" doc_enc["1"] = {"len": b"", "data": bytes(s[idx : idx + f_len])} if len(s[idx : idx + f_len]) != f_len: raise DecodeError( f"Field data is {len(s[idx:idx + f_len])} bytes, expecting {f_len}", s, doc_dec, doc_enc, idx, "1", ) if spec["1"]["data_enc"] == "b": doc_dec["1"] = s[idx : idx + f_len].hex().upper() bm = s[idx : idx + f_len] else: try: doc_dec["1"] = s[idx : idx + f_len].decode(spec["1"]["data_enc"]) except LookupError: raise DecodeError( "Failed to decode field, unknown encoding specified", s, doc_dec, doc_enc, idx, "1", ) from None except Exception: raise DecodeError( "Failed to decode field, invalid data", s, doc_dec, doc_enc, idx, "1", ) from None try: bm = bytes.fromhex(doc_dec["1"]) except Exception: raise DecodeError( "Failed to decode field, non-hex data", s, doc_dec, doc_enc, idx, "1", ) from None fields.update( [ 64 + byte_idx * 8 + bit for bit in range(1, 9) for byte_idx, byte in enumerate(bm) if byte >> (8 - bit) & 1 ] ) return idx + f_len def _decode_field( s: Union[bytes, bytearray], doc_dec: DecodedDict, doc_enc: EncodedDict, idx: int, field_key: str, spec: SpecDict, ) -> int: r"""Decode ISO8583 individual fields. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array field_key : str Field ID to be decoded spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of the field ended Raises ------ DecodeError An error decoding ISO8583 bytearray. """ len_type = spec[field_key]["len_type"] # Optional field added in v2.1. Prior specs do not have it. len_count = spec[field_key].get("len_count", "bytes") doc_dec[field_key] = "" doc_enc[field_key] = {"len": bytes(s[idx : idx + len_type]), "data": b""} if len(s[idx : idx + len_type]) != len_type: raise DecodeError( f"Field length is {len(s[idx:idx + len_type])} bytes wide, expecting {len_type}", s, doc_dec, doc_enc, idx, field_key, ) # Parse field length if present. # For fixed-length fields max_len is the length. if len_type == 0: enc_field_len: int = spec[field_key]["max_len"] # Variable field length else: # BCD length if spec[field_key]["len_enc"] in {"b", "bcd"}: try: enc_field_len = int(s[idx : idx + len_type].hex(), 10) except Exception: raise DecodeError( "Failed to decode field length, invalid BCD data", s, doc_dec, doc_enc, idx, field_key, ) from None # Text length else: try: decoded_length = s[idx : idx + len_type].decode( spec[field_key]["len_enc"] ) except LookupError: raise DecodeError( "Failed to decode field length, unknown encoding specified", s, doc_dec, doc_enc, idx, field_key, ) from None except Exception: raise DecodeError( "Failed to decode field length, invalid data", s, doc_dec, doc_enc, idx, field_key, ) from None try: enc_field_len = int(decoded_length) except Exception: raise DecodeError( "Failed to decode field length, non-numeric data", s, doc_dec, doc_enc, idx, field_key, ) from None if enc_field_len > spec[field_key]["max_len"]: raise DecodeError( f"Field data is {enc_field_len} {len_count}, larger than maximum {spec[field_key]['max_len']}", s, doc_dec, doc_enc, idx, field_key, ) idx += len_type # Do not parse zero-length field if enc_field_len == 0: return idx # Encoded field length can be in bytes or half bytes (nibbles) # Convert nibbles to bytes if needed if len_count == "nibbles": if enc_field_len & 1: byte_field_len = (enc_field_len + 1) // 2 else: byte_field_len = enc_field_len // 2 else: byte_field_len = enc_field_len # Parse field data doc_enc[field_key]["data"] = bytes(s[idx : idx + byte_field_len]) if len(doc_enc[field_key]["data"]) != byte_field_len: if len_count == "nibbles": actual_field_len = len(doc_enc[field_key]["data"]) * 2 else: actual_field_len = len(doc_enc[field_key]["data"]) raise DecodeError( f"Field data is {actual_field_len} {len_count}, expecting {enc_field_len}", s, doc_dec, doc_enc, idx, field_key, ) if spec[field_key]["data_enc"] == "b": doc_dec[field_key] = doc_enc[field_key]["data"].hex().upper() if len_count == "nibbles" and enc_field_len & 1: doc_dec[field_key] = _remove_pad_field( s, idx, doc_dec, doc_enc, field_key, spec, enc_field_len ) else: try: doc_dec[field_key] = doc_enc[field_key]["data"].decode( spec[field_key]["data_enc"] ) except LookupError: raise DecodeError( "Failed to decode field, unknown encoding specified", s, doc_dec, doc_enc, idx, field_key, ) from None except Exception: raise DecodeError( "Failed to decode field, invalid data", s, doc_dec, doc_enc, idx, field_key, ) from None return idx + byte_field_len def _remove_pad_field( s: Union[bytes, bytearray], idx: int, doc_dec: DecodedDict, doc_enc: EncodedDict, field_key: str, spec: SpecDict, enc_field_len: int, ) -> str: r"""Remove left or right pad from a BCD or hex field. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data idx : int Current index in ISO8583 byte array doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data field_key : str Field ID to remove pad from spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. enc_field_len : int Number of nibbles expected in the field Returns ------- str Field data without pad Raises ------ DecodeError An error decoding ISO8583 bytearray. """ pad: str = spec[field_key].get("left_pad", "")[:1] if len(pad) > 0 and doc_dec[field_key][:1] == pad: return doc_dec[field_key][1:] pad = spec[field_key].get("right_pad", "")[:1] if len(pad) > 0 and doc_dec[field_key][-1:] == pad: return doc_dec[field_key][:-1] raise DecodeError( f"Field data is {len(doc_dec[field_key])} nibbles, expecting {enc_field_len}", s, doc_dec, doc_enc, idx, field_key, )
en
0.370267
Subclass of ValueError that describes ISO8583 decoding error. Attributes ---------- msg : str The unformatted error message s : bytes or bytearray The ISO8583 bytes instance being parsed doc_dec : dict Dict containing partially decoded ISO8583 data doc_enc : dict Dict containing partially encoded ISO8583 data pos : int The start index where ISO8583 bytes data failed parsing field : str The ISO8583 field where parsing failed Deserialize a bytes or bytearray instance containing ISO8583 data to a Python dict. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data Raises ------ DecodeError An error decoding ISO8583 bytearray TypeError `s` must be a bytes or bytearray instance Examples -------- >>> import pprint >>> import iso8583 >>> from iso8583.specs import default_ascii as spec >>> s = b"02004010100000000000161234567890123456123456111" >>> doc_dec, doc_enc = iso8583.decode(s, spec) >>> pprint.pprint(doc_dec) {'12': '123456', '2': '1234567890123456', '20': '111', 'p': '4010100000000000', 't': '0200'} # `field_key` can be used to throw an exception after the loop. # So, create it here in case the `fields` set is empty # and never enters the loop to create the variable. # Set `field_key` to the last mandatory one: primary bitmap. # Secondary bitmap is already decoded in _decode_bitmaps # # Private interface # Decode ISO8583 header data if present. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of the header ended Raises ------ DecodeError An error decoding ISO8583 bytearray. # Header is not expected according to specifications Decode ISO8583 message type. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of message type ended Raises ------ DecodeError An error decoding ISO8583 bytearray. # Message type is a set length in ISO8583 Decode ISO8583 primary and secondary bitmaps. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. fields: set Will be populated with enabled field numbers Returns ------- int Index in ISO8583 byte array where parsing of bitmaps ended Raises ------ DecodeError An error decoding ISO8583 bytearray. # Primary bitmap is a set length in ISO8583 # No need to produce secondary bitmap if it's not required # Decode secondary bitmap # Secondary bitmap is a set length in ISO8583 Decode ISO8583 individual fields. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data idx : int Current index in ISO8583 byte array field_key : str Field ID to be decoded spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. Returns ------- int Index in ISO8583 byte array where parsing of the field ended Raises ------ DecodeError An error decoding ISO8583 bytearray. # Optional field added in v2.1. Prior specs do not have it. # Parse field length if present. # For fixed-length fields max_len is the length. # Variable field length # BCD length # Text length # Do not parse zero-length field # Encoded field length can be in bytes or half bytes (nibbles) # Convert nibbles to bytes if needed # Parse field data Remove left or right pad from a BCD or hex field. Parameters ---------- s : bytes or bytearray Encoded ISO8583 data idx : int Current index in ISO8583 byte array doc_dec : dict Dict containing decoded ISO8583 data doc_enc : dict Dict containing encoded ISO8583 data field_key : str Field ID to remove pad from spec : dict A Python dict defining ISO8583 specification. See :mod:`iso8583.specs` module for examples. enc_field_len : int Number of nibbles expected in the field Returns ------- str Field data without pad Raises ------ DecodeError An error decoding ISO8583 bytearray.
2.690535
3
cc_server/services/master/scheduling_strategies/container_allocation.py
curious-containers/cc-server
4
6613204
<reponame>curious-containers/cc-server def binpack(nodes, minimum_ram): node_list = [(node['free_ram'], name) for name, node in nodes.items() if node['free_ram'] >= minimum_ram] if not node_list: return None node_list.sort(reverse=False) return node_list[0][1] def spread(nodes, minimum_ram): node_list = [(node['free_ram'], name) for name, node in nodes.items() if node['free_ram'] >= minimum_ram] if not node_list: return None node_list.sort(reverse=True) return node_list[0][1]
def binpack(nodes, minimum_ram): node_list = [(node['free_ram'], name) for name, node in nodes.items() if node['free_ram'] >= minimum_ram] if not node_list: return None node_list.sort(reverse=False) return node_list[0][1] def spread(nodes, minimum_ram): node_list = [(node['free_ram'], name) for name, node in nodes.items() if node['free_ram'] >= minimum_ram] if not node_list: return None node_list.sort(reverse=True) return node_list[0][1]
none
1
3.139162
3
NN_HW.py
samonuall/Logistic_Regression_Practice
0
6613205
#!/usr/bin/env python # coding: utf-8 # In[44]: import numpy as np import matplotlib.pyplot as plt from scipy import stats from PIL import Image from scipy import ndimage get_ipython().run_line_magic('matplotlib', 'inline') # In[81]: #Dataset from https://www.kaggle.com/shaunthesheep/microsoft-catsvsdogs-dataset root_dir = 'PetImages/' num_cats = 100 num_dogs = 100 num_test = 60 #number of test images in all, half will be cat and half will be dog img_size = 200 #dimension for square cropout of images from top left cat_train, cat_end = get_images('Cat', num_cats, img_size) #make last pixel 0 or 1 as a way to label images for later shuffling cat_train[:, 0, -1, -1, :] = np.array([1, 1, 1]) dog_train, dog_end = get_images('Dog', num_dogs, img_size) dog_train[:, 0, -1, -1, :] = np.array([0, 0, 0]) train_set = np.concatenate((cat_train, dog_train)) #shuffle order of images, keeping labels and pixels intact np.random.shuffle(train_set) cat_test, _ = get_images('Cat', num_test // 2, img_size, counter=cat_end) cat_test[:, 0, -1, -1, :] = np.array([1, 1, 1]) dog_test, _ = get_images('Dog', num_test // 2, img_size, counter=dog_end) dog_test[:, 0, -1, -1, :] = np.array([0, 0, 0]) test_set = np.concatenate((cat_test, dog_test)) np.random.shuffle(test_set) #Make label vector and then delete the last pixel that had the label to stop #model from learning that that pixel is the label. train_labels = train_set[:, 0, -1, -1, 0].reshape(num_cats+num_dogs, 1) train_set = train_set[:, :, :-1, :-1, :] test_labels = test_set[:, 0, -1, -1, 0].reshape((num_test // 2)*2, 1) test_set = test_set[:, :, :-1, :-1, :] # In[82]: #Flatten images so they're a column of R G and B vals, then transpose labels to match their shape flattened_train = train_set.reshape(train_set.shape[0], -1).T flattened_test = test_set.reshape(test_set.shape[0], -1).T train_labels = train_labels.T test_labels = test_labels.T #Standardize data, new variable names so previous cell doesn't mess stuff up train = flattened_train / 255. test = flattened_test / 255. # In[77]: #Maybe can somehow vectorize the while loop, later try doing cropping from middle to see the change in effectiveness def get_images(folder_name, num_images, img_size, counter=0): """ Inputs: folder_name: name of folder in archive, has to be Cat or Dog num_images: number of images to be extracted img_size: minimum dimension of an image to be added to list, same number for row and column counter: where to start image search, defaults to 0 Returns: column vector of np.array images that were cropped from top left, shape = (num_images, 1, img_size, img_size, 3), and the other part of the tuple is the index of the last used image so that test sets can know where the training set left off in order to have unique images """ imgs = np.array([0]) #initialize with any number while imgs.shape[0] < num_images: img = np.array(Image.open(root_dir+'{}/{}.jpg'.format(folder_name, counter))) #for some reason some image is corrupted and only is shape (_, _), so have to check for that #before indexing in the next step to avoid errors if len(img.shape) < 3: counter += 1 continue img = img.reshape(1, 1, img.shape[0], img.shape[1], img.shape[2]) if img.dtype is not object and img.shape[2] >= img_size and img.shape[3] >= img_size: #if imgs hasn't been set to an image yet, set it to the first image so #other images can now be appended to the array if len(imgs.shape) < 3: imgs = img[:, :, :img_size, :img_size, :] imgs = imgs.reshape(1, 1, img_size, img_size, 3) else: #append along rows so end result is a column vector of images imgs = np.append(imgs, img[:, :, :img_size, :img_size, :], axis=0) counter += 1 return (imgs, counter) def sigmoid(x): s = 1 / (1 + np.exp(-x)) return s def relu(x): x[x < 0] = 0 return x def init_with_zeros(dim): """ Inputs: dim: number of weights to be intialized Returns: w: numpy array of zeros with size (dim, 1) b: 0, bias """ w = np.zeros(dim).reshape(dim, 1) w += .01 b = 0 assert(w.shape == (dim, 1)) assert(isinstance(b, float) or isinstance(b, int)) return w, b def propagate(w, b, X, Y, activation=sigmoid): """ Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples) Return: cost -- negative log-likelihood cost for logistic regression dw -- gradient of the loss with respect to w, thus same shape as w db -- gradient of the loss with respect to b, thus same shape as b """ z = w.T @ X + b #row vector of weighted sums, X.shape[0] is num_images a = activation(z) #activation function, apply given function to each weighted sum cost = -np.sum(Y*np.log(a) + (1 - Y) * np.log(1-a)) / X.shape[1] dw = np.matmul(X, (a - Y).T) / X.shape[1] dw = dw.reshape(w.shape) db = np.sum(a - Y) / X.shape[1] assert(dw.shape == w.shape) assert(db.dtype == float) cost = np.squeeze(cost) assert(cost.shape == ()) grads = {"dw": dw, "db": db} return grads, cost def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples) num_iterations -- number of iterations of the optimization loop learning_rate -- learning rate of the gradient descent update rule print_cost -- True to print the loss every 100 steps Returns: params -- dictionary containing the weights w and bias b grads -- dictionary containing the gradients of the weights and bias with respect to the cost function costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve. Tips: You basically need to write down two steps and iterate through them: 1) Calculate the cost and the gradient for the current parameters. Use propagate(). 2) Update the parameters using gradient descent rule for w and b. """ costs = [] for i in range(num_iterations): grads, cost = propagate(w, b, X, Y) dw = grads['dw'] db = grads['db'] w = w - learning_rate * dw b = b - learning_rate * db if i % 100 == 0: costs.append(cost) if print_cost: print ("Cost after iteration %i: %f" %(i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs def predict(w, b, X, activation=sigmoid): ''' Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Returns: Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X ''' z = w.T @ X + b #row vector of weighted sums, X.shape[0] is num_images a = activation(z) #activation function, apply sigmoid function to each weighted sum a[np.where(a > .5)] = 1 a[np.where(a <= .5)] = 0 Y_prediction = a.reshape(1, X.shape[1]) return Y_prediction def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): """ Builds the logistic regression model by calling the function you've implemented previously Arguments: X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train) Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train) X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test) Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test) num_iterations -- hyperparameter representing the number of iterations to optimize the parameters learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize() print_cost -- Set to true to print the cost every 100 iterations Returns: d -- dictionary containing information about the model. """ w, b = init_with_zeros(X_train.shape[0]) params, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) w, b = params['w'], params['b'] Y_prediction_train = predict(w, b, X_train) Y_prediction_test = predict(w, b, X_test) print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": Y_prediction_test, "Y_prediction_train" : Y_prediction_train, "w" : w, "b" : b, "learning_rate" : learning_rate, "num_iterations": num_iterations} return d # In[91]: d = model(train, train_labels, test, test_labels, num_iterations = 700, learning_rate = 0.01, print_cost = True) # In[ ]: # In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[44]: import numpy as np import matplotlib.pyplot as plt from scipy import stats from PIL import Image from scipy import ndimage get_ipython().run_line_magic('matplotlib', 'inline') # In[81]: #Dataset from https://www.kaggle.com/shaunthesheep/microsoft-catsvsdogs-dataset root_dir = 'PetImages/' num_cats = 100 num_dogs = 100 num_test = 60 #number of test images in all, half will be cat and half will be dog img_size = 200 #dimension for square cropout of images from top left cat_train, cat_end = get_images('Cat', num_cats, img_size) #make last pixel 0 or 1 as a way to label images for later shuffling cat_train[:, 0, -1, -1, :] = np.array([1, 1, 1]) dog_train, dog_end = get_images('Dog', num_dogs, img_size) dog_train[:, 0, -1, -1, :] = np.array([0, 0, 0]) train_set = np.concatenate((cat_train, dog_train)) #shuffle order of images, keeping labels and pixels intact np.random.shuffle(train_set) cat_test, _ = get_images('Cat', num_test // 2, img_size, counter=cat_end) cat_test[:, 0, -1, -1, :] = np.array([1, 1, 1]) dog_test, _ = get_images('Dog', num_test // 2, img_size, counter=dog_end) dog_test[:, 0, -1, -1, :] = np.array([0, 0, 0]) test_set = np.concatenate((cat_test, dog_test)) np.random.shuffle(test_set) #Make label vector and then delete the last pixel that had the label to stop #model from learning that that pixel is the label. train_labels = train_set[:, 0, -1, -1, 0].reshape(num_cats+num_dogs, 1) train_set = train_set[:, :, :-1, :-1, :] test_labels = test_set[:, 0, -1, -1, 0].reshape((num_test // 2)*2, 1) test_set = test_set[:, :, :-1, :-1, :] # In[82]: #Flatten images so they're a column of R G and B vals, then transpose labels to match their shape flattened_train = train_set.reshape(train_set.shape[0], -1).T flattened_test = test_set.reshape(test_set.shape[0], -1).T train_labels = train_labels.T test_labels = test_labels.T #Standardize data, new variable names so previous cell doesn't mess stuff up train = flattened_train / 255. test = flattened_test / 255. # In[77]: #Maybe can somehow vectorize the while loop, later try doing cropping from middle to see the change in effectiveness def get_images(folder_name, num_images, img_size, counter=0): """ Inputs: folder_name: name of folder in archive, has to be Cat or Dog num_images: number of images to be extracted img_size: minimum dimension of an image to be added to list, same number for row and column counter: where to start image search, defaults to 0 Returns: column vector of np.array images that were cropped from top left, shape = (num_images, 1, img_size, img_size, 3), and the other part of the tuple is the index of the last used image so that test sets can know where the training set left off in order to have unique images """ imgs = np.array([0]) #initialize with any number while imgs.shape[0] < num_images: img = np.array(Image.open(root_dir+'{}/{}.jpg'.format(folder_name, counter))) #for some reason some image is corrupted and only is shape (_, _), so have to check for that #before indexing in the next step to avoid errors if len(img.shape) < 3: counter += 1 continue img = img.reshape(1, 1, img.shape[0], img.shape[1], img.shape[2]) if img.dtype is not object and img.shape[2] >= img_size and img.shape[3] >= img_size: #if imgs hasn't been set to an image yet, set it to the first image so #other images can now be appended to the array if len(imgs.shape) < 3: imgs = img[:, :, :img_size, :img_size, :] imgs = imgs.reshape(1, 1, img_size, img_size, 3) else: #append along rows so end result is a column vector of images imgs = np.append(imgs, img[:, :, :img_size, :img_size, :], axis=0) counter += 1 return (imgs, counter) def sigmoid(x): s = 1 / (1 + np.exp(-x)) return s def relu(x): x[x < 0] = 0 return x def init_with_zeros(dim): """ Inputs: dim: number of weights to be intialized Returns: w: numpy array of zeros with size (dim, 1) b: 0, bias """ w = np.zeros(dim).reshape(dim, 1) w += .01 b = 0 assert(w.shape == (dim, 1)) assert(isinstance(b, float) or isinstance(b, int)) return w, b def propagate(w, b, X, Y, activation=sigmoid): """ Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples) Return: cost -- negative log-likelihood cost for logistic regression dw -- gradient of the loss with respect to w, thus same shape as w db -- gradient of the loss with respect to b, thus same shape as b """ z = w.T @ X + b #row vector of weighted sums, X.shape[0] is num_images a = activation(z) #activation function, apply given function to each weighted sum cost = -np.sum(Y*np.log(a) + (1 - Y) * np.log(1-a)) / X.shape[1] dw = np.matmul(X, (a - Y).T) / X.shape[1] dw = dw.reshape(w.shape) db = np.sum(a - Y) / X.shape[1] assert(dw.shape == w.shape) assert(db.dtype == float) cost = np.squeeze(cost) assert(cost.shape == ()) grads = {"dw": dw, "db": db} return grads, cost def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples) num_iterations -- number of iterations of the optimization loop learning_rate -- learning rate of the gradient descent update rule print_cost -- True to print the loss every 100 steps Returns: params -- dictionary containing the weights w and bias b grads -- dictionary containing the gradients of the weights and bias with respect to the cost function costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve. Tips: You basically need to write down two steps and iterate through them: 1) Calculate the cost and the gradient for the current parameters. Use propagate(). 2) Update the parameters using gradient descent rule for w and b. """ costs = [] for i in range(num_iterations): grads, cost = propagate(w, b, X, Y) dw = grads['dw'] db = grads['db'] w = w - learning_rate * dw b = b - learning_rate * db if i % 100 == 0: costs.append(cost) if print_cost: print ("Cost after iteration %i: %f" %(i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs def predict(w, b, X, activation=sigmoid): ''' Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Returns: Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X ''' z = w.T @ X + b #row vector of weighted sums, X.shape[0] is num_images a = activation(z) #activation function, apply sigmoid function to each weighted sum a[np.where(a > .5)] = 1 a[np.where(a <= .5)] = 0 Y_prediction = a.reshape(1, X.shape[1]) return Y_prediction def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): """ Builds the logistic regression model by calling the function you've implemented previously Arguments: X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train) Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train) X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test) Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test) num_iterations -- hyperparameter representing the number of iterations to optimize the parameters learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize() print_cost -- Set to true to print the cost every 100 iterations Returns: d -- dictionary containing information about the model. """ w, b = init_with_zeros(X_train.shape[0]) params, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) w, b = params['w'], params['b'] Y_prediction_train = predict(w, b, X_train) Y_prediction_test = predict(w, b, X_test) print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": Y_prediction_test, "Y_prediction_train" : Y_prediction_train, "w" : w, "b" : b, "learning_rate" : learning_rate, "num_iterations": num_iterations} return d # In[91]: d = model(train, train_labels, test, test_labels, num_iterations = 700, learning_rate = 0.01, print_cost = True) # In[ ]: # In[ ]:
en
0.805165
#!/usr/bin/env python # coding: utf-8 # In[44]: # In[81]: #Dataset from https://www.kaggle.com/shaunthesheep/microsoft-catsvsdogs-dataset #number of test images in all, half will be cat and half will be dog #dimension for square cropout of images from top left #make last pixel 0 or 1 as a way to label images for later shuffling #shuffle order of images, keeping labels and pixels intact #Make label vector and then delete the last pixel that had the label to stop #model from learning that that pixel is the label. # In[82]: #Flatten images so they're a column of R G and B vals, then transpose labels to match their shape #Standardize data, new variable names so previous cell doesn't mess stuff up # In[77]: #Maybe can somehow vectorize the while loop, later try doing cropping from middle to see the change in effectiveness Inputs: folder_name: name of folder in archive, has to be Cat or Dog num_images: number of images to be extracted img_size: minimum dimension of an image to be added to list, same number for row and column counter: where to start image search, defaults to 0 Returns: column vector of np.array images that were cropped from top left, shape = (num_images, 1, img_size, img_size, 3), and the other part of the tuple is the index of the last used image so that test sets can know where the training set left off in order to have unique images #initialize with any number #for some reason some image is corrupted and only is shape (_, _), so have to check for that #before indexing in the next step to avoid errors #if imgs hasn't been set to an image yet, set it to the first image so #other images can now be appended to the array #append along rows so end result is a column vector of images Inputs: dim: number of weights to be intialized Returns: w: numpy array of zeros with size (dim, 1) b: 0, bias Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples) Return: cost -- negative log-likelihood cost for logistic regression dw -- gradient of the loss with respect to w, thus same shape as w db -- gradient of the loss with respect to b, thus same shape as b #row vector of weighted sums, X.shape[0] is num_images #activation function, apply given function to each weighted sum This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples) num_iterations -- number of iterations of the optimization loop learning_rate -- learning rate of the gradient descent update rule print_cost -- True to print the loss every 100 steps Returns: params -- dictionary containing the weights w and bias b grads -- dictionary containing the gradients of the weights and bias with respect to the cost function costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve. Tips: You basically need to write down two steps and iterate through them: 1) Calculate the cost and the gradient for the current parameters. Use propagate(). 2) Update the parameters using gradient descent rule for w and b. Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Returns: Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X #row vector of weighted sums, X.shape[0] is num_images #activation function, apply sigmoid function to each weighted sum Builds the logistic regression model by calling the function you've implemented previously Arguments: X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train) Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train) X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test) Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test) num_iterations -- hyperparameter representing the number of iterations to optimize the parameters learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize() print_cost -- Set to true to print the cost every 100 iterations Returns: d -- dictionary containing information about the model. # In[91]: # In[ ]: # In[ ]:
3.01366
3
app/models/counselors_workload.py
run-nerver/performance-management-backend
20
6613206
import time from app import db year = time.strftime("%Y", time.localtime()) class CounselorsWorkload(db.Model): __tablename__ = 'counselorsworkload' id = db.Column(db.Integer, primary_key=True) total_people = db.Column(db.Integer) # 带学生总人数 beyond_workload_people = db.Column(db.Integer) # 超工作量人数 months = db.Column(db.Integer) # 月数 counselors_beyond_workload = db.Column(db.DECIMAL(20, 2)) # 超工作量 counselors_beyond_workload_score = db.Column(db.DECIMAL(20, 2)) # 超工作量分值 counselors_beyond_workload_money = db.Column(db.DECIMAL(20, 2)) # 超工作量金额 students_money = db.Column(db.DECIMAL(20, 2)) # 带学生金额 total_money = db.Column(db.DECIMAL(20, 2)) # 总金额 year = db.Column(db.String(4), default=year) notes = db.Column(db.Text) # 备注 user_id = db.Column(db.Integer, db.ForeignKey('user.id')) # 外键
import time from app import db year = time.strftime("%Y", time.localtime()) class CounselorsWorkload(db.Model): __tablename__ = 'counselorsworkload' id = db.Column(db.Integer, primary_key=True) total_people = db.Column(db.Integer) # 带学生总人数 beyond_workload_people = db.Column(db.Integer) # 超工作量人数 months = db.Column(db.Integer) # 月数 counselors_beyond_workload = db.Column(db.DECIMAL(20, 2)) # 超工作量 counselors_beyond_workload_score = db.Column(db.DECIMAL(20, 2)) # 超工作量分值 counselors_beyond_workload_money = db.Column(db.DECIMAL(20, 2)) # 超工作量金额 students_money = db.Column(db.DECIMAL(20, 2)) # 带学生金额 total_money = db.Column(db.DECIMAL(20, 2)) # 总金额 year = db.Column(db.String(4), default=year) notes = db.Column(db.Text) # 备注 user_id = db.Column(db.Integer, db.ForeignKey('user.id')) # 外键
zh
0.810096
# 带学生总人数 # 超工作量人数 # 月数 # 超工作量 # 超工作量分值 # 超工作量金额 # 带学生金额 # 总金额 # 备注 # 外键
2.744112
3
course/views/oj.py
scintiller/OnlineJudge
0
6613207
<reponame>scintiller/OnlineJudge import os import logging from django.conf import settings from django.http import FileResponse from utils.api import CSRFExemptAPIView, APIView from video.api import MediaAPIView from account.serializers import ImageUploadForm, FileUploadForm from account.decorators import login_required from utils.shortcuts import rand_str from ..models import Course, PowerPoint from problem.models import Problem from problem.serializers import ProblemSerializer from ..serializers import CourseSerializer, PowerPointSerializer, FileDownloadSerializer logger = logging.getLogger(__name__) class CourseAPI(APIView): def extend_problems(self, problems, request): if not problems or len(problems) == 0: return [] result = [] for id_str in problems: p = Problem.objects.get(_id=int(id_str), contest_id__isnull=True, visible=True) problem = ProblemSerializer(p).data profile = request.user.userprofile oi_problems_status = profile.oi_problems_status.get("problems", {}) problem["my_status"] = oi_problems_status.get(id_str, {}).get("status") result.append(problem) return result @login_required def get(self, request): # 判断user权限 user = request.user if not user.is_super_admin() and not user.is_admin_role() and not user.paid: return self.error("没有查看课程权限") # 课程详情页 course_id = request.GET.get("id") if course_id: try: course = Course.objects.select_related("created_by")\ .get(id=course_id) data = CourseSerializer(course).data on_class_problems = data.get("on_class_problems") after_class_problems = data.get("after_class_problems") data["on_class_problems"] = self.extend_problems(on_class_problems, request) data["after_class_problems"] = self.extend_problems(after_class_problems, request) return self.success(data) except Course.DoesNotExist: return self.error("课程不存在") # 课程列表 # limit = request.GET.get("limit") # if not limit: # return self.error("需要给出每页的课程数限制!") courses = Course.objects.select_related("created_by") # data = self.paginate_data(request, courses, CourseSerializer) return self.success(CourseSerializer(courses, many=True).data) class PowerPointAPI(MediaAPIView): # 普通用户获取ppt @login_required def get(self, request): course_id = request.GET.get("course_id") if course_id: # str[str.rfind("/")+1:] # 从数据库中找ppt try: ppt = PowerPoint.objects.filter(course=course_id)[0] url = PowerPointSerializer(ppt).data['ppt'] ppt_name = {"file_type": "ppt", "file_name": url[url.rfind("/")+1:]} return self.success(FileDownloadSerializer(ppt_name).data) except PowerPoint.DoesNotExist: return self.error("ppt不存在") else: return self.error("请求中需要参数course_id") ########################### File Download / File Upload ########################### class FileDownloadAPI(APIView): # @login_required def get(self, request): file_type = request.GET.get("file_type").lower() if self.check_file_type(file_type) == False: return self.error("该文件类型不存在:"+ file_type + ", file_type参数只接受ppt/image/video/software") file_name = request.GET.get("file_name") file_address = os.path.join(settings.MEDIA_ROOT, file_type, file_name) print("[DEBUG DOWNLOAD] MEDIA_ROOT: ", settings.MEDIA_ROOT, "\nfile address: ", file_address, "\n") try: open_file = open(file_address,'rb') except IOError: return self.error("文件不存在") response = FileResponse(open_file) response['Content-Type']='application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name) # print("response:", response) return response def check_file_type(self, file_type): if file_type == "ppt" or file_type == "image" or file_type == "video" or file_type == "software": return True return False # 上传图片 class ImageUploadAPIView(CSRFExemptAPIView): request_parsers = () def post(self, request): form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): img = form.cleaned_data["image"] else: return self.response({ "success": False, "msg": "Upload failed" }) suffix = os.path.splitext(img.name)[-1].lower() if suffix not in [".gif", ".jpg", ".jpeg", ".bmp", ".png"]: return self.response({ "success": False, "msg": "Unsupported file format" }) img_name = rand_str(10) + suffix file_address = os.path.join(settings.MEDIA_ROOT, "image", img_name) # print("file_address: ", file_address) try: with open(file_address, "wb") as imgFile: for chunk in img: imgFile.write(chunk) except IOError as e: logger.error(e) return self.response({ "success": False, "msg": "Upload Error" }) return self.response({ "success": True, "msg": "Success" }) # 上传文件 class FileUploadAPIView(CSRFExemptAPIView): request_parsers = () def post(self, request): form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): file = form.cleaned_data["file"] else: return self.response({ "success": False, "msg": "Upload failed" }) suffix = os.path.splitext(file.name)[-1].lower() file_name = rand_str(10) + suffix file_address = os.path.join(settings.MEDIA_ROOT, "file", file_name) try: with open(file_address, "wb") as f: for chunk in file: f.write(chunk) except IOError as e: logger.error(e) return self.response({ "success": False, "msg": "Upload Error"}) return self.response({ "success": True, "msg": "Success", })
import os import logging from django.conf import settings from django.http import FileResponse from utils.api import CSRFExemptAPIView, APIView from video.api import MediaAPIView from account.serializers import ImageUploadForm, FileUploadForm from account.decorators import login_required from utils.shortcuts import rand_str from ..models import Course, PowerPoint from problem.models import Problem from problem.serializers import ProblemSerializer from ..serializers import CourseSerializer, PowerPointSerializer, FileDownloadSerializer logger = logging.getLogger(__name__) class CourseAPI(APIView): def extend_problems(self, problems, request): if not problems or len(problems) == 0: return [] result = [] for id_str in problems: p = Problem.objects.get(_id=int(id_str), contest_id__isnull=True, visible=True) problem = ProblemSerializer(p).data profile = request.user.userprofile oi_problems_status = profile.oi_problems_status.get("problems", {}) problem["my_status"] = oi_problems_status.get(id_str, {}).get("status") result.append(problem) return result @login_required def get(self, request): # 判断user权限 user = request.user if not user.is_super_admin() and not user.is_admin_role() and not user.paid: return self.error("没有查看课程权限") # 课程详情页 course_id = request.GET.get("id") if course_id: try: course = Course.objects.select_related("created_by")\ .get(id=course_id) data = CourseSerializer(course).data on_class_problems = data.get("on_class_problems") after_class_problems = data.get("after_class_problems") data["on_class_problems"] = self.extend_problems(on_class_problems, request) data["after_class_problems"] = self.extend_problems(after_class_problems, request) return self.success(data) except Course.DoesNotExist: return self.error("课程不存在") # 课程列表 # limit = request.GET.get("limit") # if not limit: # return self.error("需要给出每页的课程数限制!") courses = Course.objects.select_related("created_by") # data = self.paginate_data(request, courses, CourseSerializer) return self.success(CourseSerializer(courses, many=True).data) class PowerPointAPI(MediaAPIView): # 普通用户获取ppt @login_required def get(self, request): course_id = request.GET.get("course_id") if course_id: # str[str.rfind("/")+1:] # 从数据库中找ppt try: ppt = PowerPoint.objects.filter(course=course_id)[0] url = PowerPointSerializer(ppt).data['ppt'] ppt_name = {"file_type": "ppt", "file_name": url[url.rfind("/")+1:]} return self.success(FileDownloadSerializer(ppt_name).data) except PowerPoint.DoesNotExist: return self.error("ppt不存在") else: return self.error("请求中需要参数course_id") ########################### File Download / File Upload ########################### class FileDownloadAPI(APIView): # @login_required def get(self, request): file_type = request.GET.get("file_type").lower() if self.check_file_type(file_type) == False: return self.error("该文件类型不存在:"+ file_type + ", file_type参数只接受ppt/image/video/software") file_name = request.GET.get("file_name") file_address = os.path.join(settings.MEDIA_ROOT, file_type, file_name) print("[DEBUG DOWNLOAD] MEDIA_ROOT: ", settings.MEDIA_ROOT, "\nfile address: ", file_address, "\n") try: open_file = open(file_address,'rb') except IOError: return self.error("文件不存在") response = FileResponse(open_file) response['Content-Type']='application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name) # print("response:", response) return response def check_file_type(self, file_type): if file_type == "ppt" or file_type == "image" or file_type == "video" or file_type == "software": return True return False # 上传图片 class ImageUploadAPIView(CSRFExemptAPIView): request_parsers = () def post(self, request): form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): img = form.cleaned_data["image"] else: return self.response({ "success": False, "msg": "Upload failed" }) suffix = os.path.splitext(img.name)[-1].lower() if suffix not in [".gif", ".jpg", ".jpeg", ".bmp", ".png"]: return self.response({ "success": False, "msg": "Unsupported file format" }) img_name = rand_str(10) + suffix file_address = os.path.join(settings.MEDIA_ROOT, "image", img_name) # print("file_address: ", file_address) try: with open(file_address, "wb") as imgFile: for chunk in img: imgFile.write(chunk) except IOError as e: logger.error(e) return self.response({ "success": False, "msg": "Upload Error" }) return self.response({ "success": True, "msg": "Success" }) # 上传文件 class FileUploadAPIView(CSRFExemptAPIView): request_parsers = () def post(self, request): form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): file = form.cleaned_data["file"] else: return self.response({ "success": False, "msg": "Upload failed" }) suffix = os.path.splitext(file.name)[-1].lower() file_name = rand_str(10) + suffix file_address = os.path.join(settings.MEDIA_ROOT, "file", file_name) try: with open(file_address, "wb") as f: for chunk in file: f.write(chunk) except IOError as e: logger.error(e) return self.response({ "success": False, "msg": "Upload Error"}) return self.response({ "success": True, "msg": "Success", })
zh
0.19237
# 判断user权限 # 课程详情页 # 课程列表 # limit = request.GET.get("limit") # if not limit: # return self.error("需要给出每页的课程数限制!") # data = self.paginate_data(request, courses, CourseSerializer) # 普通用户获取ppt # str[str.rfind("/")+1:] # 从数据库中找ppt ########################### File Download / File Upload ########################### # @login_required # print("response:", response) # 上传图片 # print("file_address: ", file_address) # 上传文件
2.053532
2
home/authentication.py
alliswell2day/xsa
1
6613208
<reponame>alliswell2day/xsa<gh_stars>1-10 #!/usr/bin/env python # -*- coding:utf-8 -*- ''' @author: ‘wang_pc‘ @site: @software: PyCharm @file: authentication.py @time: 2017/3/1 21:19 ''' from user.models import User from django.contrib.auth.backends import ModelBackend class EmailUsernameAuthBackend(ModelBackend): def authenticate(self, user_auth_field, password, **kwargs): try: if '@' in user_auth_field: user = User.objects.get(email= user_auth_field) else: user = User.objects.get(username= user_auth_field) except User.DoesNotExist: pass except User.MultipleObjectsReturned: pass else: if user.check_password(password): return user
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' @author: ‘wang_pc‘ @site: @software: PyCharm @file: authentication.py @time: 2017/3/1 21:19 ''' from user.models import User from django.contrib.auth.backends import ModelBackend class EmailUsernameAuthBackend(ModelBackend): def authenticate(self, user_auth_field, password, **kwargs): try: if '@' in user_auth_field: user = User.objects.get(email= user_auth_field) else: user = User.objects.get(username= user_auth_field) except User.DoesNotExist: pass except User.MultipleObjectsReturned: pass else: if user.check_password(password): return user
en
0.304463
#!/usr/bin/env python # -*- coding:utf-8 -*- @author: ‘wang_pc‘ @site: @software: PyCharm @file: authentication.py @time: 2017/3/1 21:19
2.500073
3
sustainableCityManagement/main_project/Parkings_Recreational_Places_API/store_recreational_locations_in_db.py
Josh-repository/Dashboard-CityManager-
0
6613209
# -*- coding: utf-8 -*- import sys from mongoengine import * import csv import json import math from ..Logs.service_logs import parkings_log from ..Parkings_Recreational_Places_API.recreational_places_parkings_collections_db import Parks, Cinemas, PlayingPitches, Beaches class StoreRecreationalPlacesParkingsData: def __init__(self): self.logger = parkings_log() # Method reads the csv file containing the information of beaches and return the list of details of beaches def read_beaches_locations(self): readfile = [] self.logger.info("Reading Beaches file") with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/Beaches.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) return readfile # Method stores the relevant beaches information in Database def store_beaches_locations(self): readfile = self.read_beaches_locations() self.logger.info("Storing Beaches Data in DB") for i in range(1, len(readfile)): parkings=self.get_parkings(float(readfile[i][2]),float(readfile[i][3])) beaches = Beaches(beach_id=readfile[i][0], beach_name=readfile[i][1], beach_lat=readfile[i][2], beach_lon=readfile[i][3], beach_parkings=parkings) try: beaches.save() except: pass # Method fetches the beaches information from Database and returns it def fetch_beaches_location(self, locationName="all"): q_set = Beaches.objects() # Fetch Data from DB # Converts the Beach Data from DB into JSON format json_data = q_set.to_json() beaches = json.loads(json_data) if beaches is None: self.logger.error('Beach data not retrieved from DB') else: self.logger.info("Retrieved Beaches from DB") for b in beaches: del b["_id"] return beaches # Method reads the csv file containing the information of playing pitches and return the list of details of fplaying pitches def read_playing_pitches_locations(self): readfile = [] self.logger.info("Reading Playing Pitches file") with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/PlayingPitches.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) return readfile # Method stores the relevant playing pitches information in Database def store_playing_pitches_locations(self): readfile = self.read_playing_pitches_locations() self.logger.info("Storing Playing Pitches Data in DB") for i in range(1, len(readfile)): parkings=self.get_parkings(float(readfile[i][3]),float(readfile[i][4])) playing_pitches = PlayingPitches(facility_type=readfile[i][0], facility_name=readfile[i][1], facility_location=readfile[i][2], facility_lat=readfile[i][3], facility_lon=readfile[i][4], facility_parkings=parkings) try: playing_pitches.save() except: pass # Method fetches the playing pitches information from Database and returns it def fetch_playing_pitches_location(self, locationName="all"): q_set = PlayingPitches.objects() # Fetch Data from DB json_data = q_set.to_json() playing_pitches = json.loads(json_data) if playing_pitches is None: self.logger.error('Playing Pitch data not retrieved from DB') else: self.logger.info("Retrieved Playing Pitches from DB") for p in playing_pitches: del p["_id"] return playing_pitches # Method reads the csv file containing the information of parks and return the list of details of parks def read_parks_locations(self): readfile = [] self.logger.info("Reading Parks file") with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/Parks.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) return readfile # Method stores the relevant parks information in Database def store_parks_locations(self): readfile = self.read_parks_locations() self.logger.info("Storing Parks Data in DB") for i in range(1, len(readfile)): parkings=self.get_parkings(float(readfile[i][3]),float(readfile[i][4])) parks = Parks(park_name=readfile[i][0], park_address=readfile[i][1], park_area=readfile[i][2], park_lat=readfile[i][3], park_lon=readfile[i][4], park_parkings=parkings) try: parks.save() except: pass # Method fetches the parks information from Database and returns it def fetch_parks_location(self, locationName="all"): q_set = Parks.objects() # Fetch Data from DB # Converts the Parks Data from DB into JSON format json_data = q_set.to_json() parks = json.loads(json_data) if parks is None: self.logger.error('Parks data not retrieved from DB') else: self.logger.info("Retrieved Parks from DB") for p in parks: del p["_id"] return parks # Method reads the csv file containing the information of cinemas and return the list of details of cinemas def read_cinemas_locations(self): readfile = [] self.logger.info("Reading Cinemas file") with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/Cinemas.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) return readfile # Method stores the relevant cinemas information in Database def store_cinemas_locations(self): readfile = self.read_cinemas_locations() self.logger.info("Storing Cinemas Data in DB") for i in range(1, len(readfile)): parkings=self.get_parkings(float(readfile[i][2]),float(readfile[i][3])) cinemas = Cinemas(cinema_name=readfile[i][0], cinema_address=readfile[i][1], cinema_lat=readfile[i][2], cinema_lon=readfile[i][3], cinema_parkings=parkings) try: cinemas.save() except: pass # Method fetches the cinemas information from Database and returns it def fetch_cinemas_location(self, locationName="all"): q_set = Cinemas.objects() # Fetch Data from DB # Converts the Cinemas Data from DB into JSON format json_data = q_set.to_json() cinemas = json.loads(json_data) if cinemas is None: self.logger.error('Cinemas data not retrieved from DB') else: self.logger.info("Retrieved Cinemas from DB") for c in cinemas: del c["_id"] return cinemas # Method to get the five nearest parkings to a particular location. def get_parkings(self,lat,lon): with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/disabledparkings.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) loc_parkings=[] for i in range(1, len(readfile)): lat_parkings = float(readfile[i][2]) lon_parkings = float(readfile[i][3]) R = 6371e3; # metres phi1 = lat_parkings * math.pi/180 phi2 = lat * math.pi/180 delta_phi = (lat-lat_parkings) * math.pi/180 delta_lambda = (lon-lon_parkings) * math.pi/180 a = math.sin(delta_phi/2) * math.sin(delta_phi/2) + math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda/2) * math.sin(delta_lambda/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = R * c if d < 2000.0: loc_parkings.append({ "road": readfile[i][1], "lat": readfile[i][2], "lng": readfile[i][3], "distance": d }) if len(loc_parkings)>5: loc_parkings=sorted(loc_parkings, key=lambda d: d['distance'], reverse=False) return loc_parkings[:5] else: return loc_parkings
# -*- coding: utf-8 -*- import sys from mongoengine import * import csv import json import math from ..Logs.service_logs import parkings_log from ..Parkings_Recreational_Places_API.recreational_places_parkings_collections_db import Parks, Cinemas, PlayingPitches, Beaches class StoreRecreationalPlacesParkingsData: def __init__(self): self.logger = parkings_log() # Method reads the csv file containing the information of beaches and return the list of details of beaches def read_beaches_locations(self): readfile = [] self.logger.info("Reading Beaches file") with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/Beaches.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) return readfile # Method stores the relevant beaches information in Database def store_beaches_locations(self): readfile = self.read_beaches_locations() self.logger.info("Storing Beaches Data in DB") for i in range(1, len(readfile)): parkings=self.get_parkings(float(readfile[i][2]),float(readfile[i][3])) beaches = Beaches(beach_id=readfile[i][0], beach_name=readfile[i][1], beach_lat=readfile[i][2], beach_lon=readfile[i][3], beach_parkings=parkings) try: beaches.save() except: pass # Method fetches the beaches information from Database and returns it def fetch_beaches_location(self, locationName="all"): q_set = Beaches.objects() # Fetch Data from DB # Converts the Beach Data from DB into JSON format json_data = q_set.to_json() beaches = json.loads(json_data) if beaches is None: self.logger.error('Beach data not retrieved from DB') else: self.logger.info("Retrieved Beaches from DB") for b in beaches: del b["_id"] return beaches # Method reads the csv file containing the information of playing pitches and return the list of details of fplaying pitches def read_playing_pitches_locations(self): readfile = [] self.logger.info("Reading Playing Pitches file") with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/PlayingPitches.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) return readfile # Method stores the relevant playing pitches information in Database def store_playing_pitches_locations(self): readfile = self.read_playing_pitches_locations() self.logger.info("Storing Playing Pitches Data in DB") for i in range(1, len(readfile)): parkings=self.get_parkings(float(readfile[i][3]),float(readfile[i][4])) playing_pitches = PlayingPitches(facility_type=readfile[i][0], facility_name=readfile[i][1], facility_location=readfile[i][2], facility_lat=readfile[i][3], facility_lon=readfile[i][4], facility_parkings=parkings) try: playing_pitches.save() except: pass # Method fetches the playing pitches information from Database and returns it def fetch_playing_pitches_location(self, locationName="all"): q_set = PlayingPitches.objects() # Fetch Data from DB json_data = q_set.to_json() playing_pitches = json.loads(json_data) if playing_pitches is None: self.logger.error('Playing Pitch data not retrieved from DB') else: self.logger.info("Retrieved Playing Pitches from DB") for p in playing_pitches: del p["_id"] return playing_pitches # Method reads the csv file containing the information of parks and return the list of details of parks def read_parks_locations(self): readfile = [] self.logger.info("Reading Parks file") with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/Parks.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) return readfile # Method stores the relevant parks information in Database def store_parks_locations(self): readfile = self.read_parks_locations() self.logger.info("Storing Parks Data in DB") for i in range(1, len(readfile)): parkings=self.get_parkings(float(readfile[i][3]),float(readfile[i][4])) parks = Parks(park_name=readfile[i][0], park_address=readfile[i][1], park_area=readfile[i][2], park_lat=readfile[i][3], park_lon=readfile[i][4], park_parkings=parkings) try: parks.save() except: pass # Method fetches the parks information from Database and returns it def fetch_parks_location(self, locationName="all"): q_set = Parks.objects() # Fetch Data from DB # Converts the Parks Data from DB into JSON format json_data = q_set.to_json() parks = json.loads(json_data) if parks is None: self.logger.error('Parks data not retrieved from DB') else: self.logger.info("Retrieved Parks from DB") for p in parks: del p["_id"] return parks # Method reads the csv file containing the information of cinemas and return the list of details of cinemas def read_cinemas_locations(self): readfile = [] self.logger.info("Reading Cinemas file") with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/Cinemas.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) return readfile # Method stores the relevant cinemas information in Database def store_cinemas_locations(self): readfile = self.read_cinemas_locations() self.logger.info("Storing Cinemas Data in DB") for i in range(1, len(readfile)): parkings=self.get_parkings(float(readfile[i][2]),float(readfile[i][3])) cinemas = Cinemas(cinema_name=readfile[i][0], cinema_address=readfile[i][1], cinema_lat=readfile[i][2], cinema_lon=readfile[i][3], cinema_parkings=parkings) try: cinemas.save() except: pass # Method fetches the cinemas information from Database and returns it def fetch_cinemas_location(self, locationName="all"): q_set = Cinemas.objects() # Fetch Data from DB # Converts the Cinemas Data from DB into JSON format json_data = q_set.to_json() cinemas = json.loads(json_data) if cinemas is None: self.logger.error('Cinemas data not retrieved from DB') else: self.logger.info("Retrieved Cinemas from DB") for c in cinemas: del c["_id"] return cinemas # Method to get the five nearest parkings to a particular location. def get_parkings(self,lat,lon): with open("../sustainableCityManagement/main_project/Parkings_Recreational_Places_API/resources/disabledparkings.csv", "r", encoding="utf8") as f: readfile = list(csv.reader(f)) loc_parkings=[] for i in range(1, len(readfile)): lat_parkings = float(readfile[i][2]) lon_parkings = float(readfile[i][3]) R = 6371e3; # metres phi1 = lat_parkings * math.pi/180 phi2 = lat * math.pi/180 delta_phi = (lat-lat_parkings) * math.pi/180 delta_lambda = (lon-lon_parkings) * math.pi/180 a = math.sin(delta_phi/2) * math.sin(delta_phi/2) + math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda/2) * math.sin(delta_lambda/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = R * c if d < 2000.0: loc_parkings.append({ "road": readfile[i][1], "lat": readfile[i][2], "lng": readfile[i][3], "distance": d }) if len(loc_parkings)>5: loc_parkings=sorted(loc_parkings, key=lambda d: d['distance'], reverse=False) return loc_parkings[:5] else: return loc_parkings
en
0.81171
# -*- coding: utf-8 -*- # Method reads the csv file containing the information of beaches and return the list of details of beaches # Method stores the relevant beaches information in Database # Method fetches the beaches information from Database and returns it # Fetch Data from DB # Converts the Beach Data from DB into JSON format # Method reads the csv file containing the information of playing pitches and return the list of details of fplaying pitches # Method stores the relevant playing pitches information in Database # Method fetches the playing pitches information from Database and returns it # Fetch Data from DB # Method reads the csv file containing the information of parks and return the list of details of parks # Method stores the relevant parks information in Database # Method fetches the parks information from Database and returns it # Fetch Data from DB # Converts the Parks Data from DB into JSON format # Method reads the csv file containing the information of cinemas and return the list of details of cinemas # Method stores the relevant cinemas information in Database # Method fetches the cinemas information from Database and returns it # Fetch Data from DB # Converts the Cinemas Data from DB into JSON format # Method to get the five nearest parkings to a particular location. # metres
2.994387
3
telemetry/telemetry/internal/platform/gpu_device.py
tingshao/catapult
1,894
6613210
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class GPUDevice(object): """Provides information about an individual GPU device. On platforms which support them, the vendor_id and device_id are PCI IDs. On other platforms, the vendor_string and device_string are platform-dependent strings. """ _VENDOR_ID_MAP = { 0x1002: 'ATI', 0x8086: 'Intel', 0x10de: 'Nvidia', } def __init__(self, vendor_id, device_id, sub_sys_id, revision, vendor_string, device_string, driver_vendor, driver_version): """Initialize GPUDevice with GPU and driver information. Args: vendor_id: The GPU's 16-bit vendor ID. Zero on Android. device_id: The GPU's 16-bit devcie ID. Zero on Android. sus_sys_id: The GPU's 32-bit sub system ID. Available on Windows. revision: The GPU's 16-bit revision. Available on Windows. vendor_string: The GPU's vendor name string. device_string: The GPU's device name string. driver_vendor: The GPU's driver vendor name string. driver_version: The GPU's driver version string. """ self._vendor_id = vendor_id self._device_id = device_id self._sub_sys_id = sub_sys_id self._revision = revision self._vendor_string = vendor_string self._device_string = device_string self._driver_vendor = driver_vendor self._driver_version = driver_version def __str__(self): vendor = 'VENDOR = 0x%x' % self._vendor_id vendor_string = self._vendor_string if not vendor_string and self._vendor_id in self._VENDOR_ID_MAP: vendor_string = self._VENDOR_ID_MAP[self._vendor_id] if vendor_string: vendor += ' (%s)' % vendor_string device = 'DEVICE = 0x%x' % self._device_id if self._device_string: device += ' (%s)' % self._device_string summary = '%s, %s' % (vendor, device) if self._sub_sys_id or self._revision: summary += ', SUBSYS = 0x%x, REV = %u' % (self._sub_sys_id, self._revision) summary += ', DRIVER_VENDOR = %s, DRIVER_VERSION = %s' % ( self._driver_vendor, self._driver_version) return summary @classmethod def FromDict(cls, attrs): """Constructs a GPUDevice from a dictionary. Requires the following attributes to be present in the dictionary: vendor_id device_id vendor_string device_string Raises an exception if any attributes are missing. The following attributes are optional: sub_sys_id revision driver_vendor driver_version """ return cls( attrs['vendor_id'], attrs['device_id'], # --browser=reference may use an old build of Chrome # where sub_sys_id, revision, driver_vendor or driver_version # aren't part of the dict. # sub_sys_id and revision are available on Windows only. attrs.get('sub_sys_id', 0), attrs.get('revision', 0), attrs['vendor_string'], attrs['device_string'], attrs.get('driver_vendor', ''), attrs.get('driver_version', '')) @property def vendor_id(self): """The GPU vendor's PCI ID as a number, or 0 if not available. Most desktop machines supply this information rather than the vendor and device strings.""" return self._vendor_id @property def device_id(self): """The GPU device's PCI ID as a number, or 0 if not available. Most desktop machines supply this information rather than the vendor and device strings.""" return self._device_id @property def sub_sys_id(self): """The GPU device's sub sys ID as a number, or 0 if not available. Only available on Windows platforms.""" return self._sub_sys_id @property def revision(self): """The GPU device's revision as a number, or 0 if not available. Only available on Windows platforms.""" return self._revision @property def vendor_string(self): """The GPU vendor's name as a string, or the empty string if not available. Most mobile devices supply this information rather than the PCI IDs.""" return self._vendor_string @property def device_string(self): """The GPU device's name as a string, or the empty string if not available. Most mobile devices supply this information rather than the PCI IDs.""" return self._device_string @property def driver_vendor(self): """The GPU driver vendor as a string, or the empty string if not available.""" return self._driver_vendor @property def driver_version(self): """The GPU driver version as a string, or the empty string if not available.""" return self._driver_version
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class GPUDevice(object): """Provides information about an individual GPU device. On platforms which support them, the vendor_id and device_id are PCI IDs. On other platforms, the vendor_string and device_string are platform-dependent strings. """ _VENDOR_ID_MAP = { 0x1002: 'ATI', 0x8086: 'Intel', 0x10de: 'Nvidia', } def __init__(self, vendor_id, device_id, sub_sys_id, revision, vendor_string, device_string, driver_vendor, driver_version): """Initialize GPUDevice with GPU and driver information. Args: vendor_id: The GPU's 16-bit vendor ID. Zero on Android. device_id: The GPU's 16-bit devcie ID. Zero on Android. sus_sys_id: The GPU's 32-bit sub system ID. Available on Windows. revision: The GPU's 16-bit revision. Available on Windows. vendor_string: The GPU's vendor name string. device_string: The GPU's device name string. driver_vendor: The GPU's driver vendor name string. driver_version: The GPU's driver version string. """ self._vendor_id = vendor_id self._device_id = device_id self._sub_sys_id = sub_sys_id self._revision = revision self._vendor_string = vendor_string self._device_string = device_string self._driver_vendor = driver_vendor self._driver_version = driver_version def __str__(self): vendor = 'VENDOR = 0x%x' % self._vendor_id vendor_string = self._vendor_string if not vendor_string and self._vendor_id in self._VENDOR_ID_MAP: vendor_string = self._VENDOR_ID_MAP[self._vendor_id] if vendor_string: vendor += ' (%s)' % vendor_string device = 'DEVICE = 0x%x' % self._device_id if self._device_string: device += ' (%s)' % self._device_string summary = '%s, %s' % (vendor, device) if self._sub_sys_id or self._revision: summary += ', SUBSYS = 0x%x, REV = %u' % (self._sub_sys_id, self._revision) summary += ', DRIVER_VENDOR = %s, DRIVER_VERSION = %s' % ( self._driver_vendor, self._driver_version) return summary @classmethod def FromDict(cls, attrs): """Constructs a GPUDevice from a dictionary. Requires the following attributes to be present in the dictionary: vendor_id device_id vendor_string device_string Raises an exception if any attributes are missing. The following attributes are optional: sub_sys_id revision driver_vendor driver_version """ return cls( attrs['vendor_id'], attrs['device_id'], # --browser=reference may use an old build of Chrome # where sub_sys_id, revision, driver_vendor or driver_version # aren't part of the dict. # sub_sys_id and revision are available on Windows only. attrs.get('sub_sys_id', 0), attrs.get('revision', 0), attrs['vendor_string'], attrs['device_string'], attrs.get('driver_vendor', ''), attrs.get('driver_version', '')) @property def vendor_id(self): """The GPU vendor's PCI ID as a number, or 0 if not available. Most desktop machines supply this information rather than the vendor and device strings.""" return self._vendor_id @property def device_id(self): """The GPU device's PCI ID as a number, or 0 if not available. Most desktop machines supply this information rather than the vendor and device strings.""" return self._device_id @property def sub_sys_id(self): """The GPU device's sub sys ID as a number, or 0 if not available. Only available on Windows platforms.""" return self._sub_sys_id @property def revision(self): """The GPU device's revision as a number, or 0 if not available. Only available on Windows platforms.""" return self._revision @property def vendor_string(self): """The GPU vendor's name as a string, or the empty string if not available. Most mobile devices supply this information rather than the PCI IDs.""" return self._vendor_string @property def device_string(self): """The GPU device's name as a string, or the empty string if not available. Most mobile devices supply this information rather than the PCI IDs.""" return self._device_string @property def driver_vendor(self): """The GPU driver vendor as a string, or the empty string if not available.""" return self._driver_vendor @property def driver_version(self): """The GPU driver version as a string, or the empty string if not available.""" return self._driver_version
en
0.783201
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. Provides information about an individual GPU device. On platforms which support them, the vendor_id and device_id are PCI IDs. On other platforms, the vendor_string and device_string are platform-dependent strings. Initialize GPUDevice with GPU and driver information. Args: vendor_id: The GPU's 16-bit vendor ID. Zero on Android. device_id: The GPU's 16-bit devcie ID. Zero on Android. sus_sys_id: The GPU's 32-bit sub system ID. Available on Windows. revision: The GPU's 16-bit revision. Available on Windows. vendor_string: The GPU's vendor name string. device_string: The GPU's device name string. driver_vendor: The GPU's driver vendor name string. driver_version: The GPU's driver version string. Constructs a GPUDevice from a dictionary. Requires the following attributes to be present in the dictionary: vendor_id device_id vendor_string device_string Raises an exception if any attributes are missing. The following attributes are optional: sub_sys_id revision driver_vendor driver_version # --browser=reference may use an old build of Chrome # where sub_sys_id, revision, driver_vendor or driver_version # aren't part of the dict. # sub_sys_id and revision are available on Windows only. The GPU vendor's PCI ID as a number, or 0 if not available. Most desktop machines supply this information rather than the vendor and device strings. The GPU device's PCI ID as a number, or 0 if not available. Most desktop machines supply this information rather than the vendor and device strings. The GPU device's sub sys ID as a number, or 0 if not available. Only available on Windows platforms. The GPU device's revision as a number, or 0 if not available. Only available on Windows platforms. The GPU vendor's name as a string, or the empty string if not available. Most mobile devices supply this information rather than the PCI IDs. The GPU device's name as a string, or the empty string if not available. Most mobile devices supply this information rather than the PCI IDs. The GPU driver vendor as a string, or the empty string if not available. The GPU driver version as a string, or the empty string if not available.
2.343746
2
sentences.py
syoch/py-conv
0
6613211
#Defines analyze of ast sentence functions import ast from exprs import expr_args, expr_call, expr_name import os import util import datamgr import libnames def sent_import(sentence:ast.Import,f=""): tmp="" for a in sentence.names: name=a.name name=name.replace(".","/") if os.path.exists(name+".py"): tmp+=f+"#include \""+name+".cpp"+"\"\n" if not os.path.abspath(name+".py") in datamgr.dictmgr.get("internal","converted"): datamgr.queuemgr.put("srcs",os.path.abspath(name+".py")) else: if name.split("/")[0] in libnames.names: tmp+=f+"#include <"+name+".cpp"+">\n" else: tmp+=f+"#include <"+name+">\n" if a.asname: tmp+=f+f"#define {a.asname} {name}\n" return tmp def sent_importfrom(sentence:ast.ImportFrom,f=""): tmp="" name=sentence.module name=name.replace(".","/") if os.path.exists(name+".py"): tmp+=f+"#include \""+name+".cpp"+"\"\n" datamgr.queuemgr.put("srcs",os.path.abspath(name+".py")) else: if name.split("/")[0] in libnames.names: tmp+=f+"#include <"+name+".cpp"+">\n" else: tmp+=f+"#include <"+name+">\n" for a in sentence.names: if a.asname: tmp+=f+f"#define {a.asname} {a.name}\n" return tmp def sent_funcdef(sentence:ast.FunctionDef,f=""): if type(sentence.body[0]) == ast.Expr and type(sentence.body[0].value) == ast.Constant: body=sentence.body[1:] else: body=sentence.body return \ f+"Any "+sentence.name+"("+expr_args(sentence.args)+")"+"{\n"+\ util.walk_shallow(body,f+" ")+\ f+"}\n" def sent_ret(sentence:ast.Return,f=""): return f+"return "+util.conv(sentence.value,mode=util.modes.EXPR)+";\n" def sent_assign(sentence:ast.Assign,f=""): ret="" value=util.conv(sentence.value,mode=util.modes.EXPR) for i,target in enumerate(sentence.targets): ret+=f #if util.conv(target,mode=util.modes.EXPR) not in datamgr.dictmgr.get("session","definedVariables"): if type(target) != ast.Attribute: ret+="Any " ret+=util.conv(target,mode=util.modes.EXPR) ret+=" = "+value if len(sentence.targets)!=1: ret+="["+str(i)+"]" ret+=";\n" return ret def sent_for(sentence:ast.For,f=""): return \ f+"for ("+"auto "+util.conv(sentence.target,mode=util.modes.EXPR)+" : "+util.conv(sentence.iter,mode=util.modes.EXPR)+"){\n"+\ util.walk_shallow(sentence.body,f+" ")+\ f+"}\n" def sent_while(sentence:ast.While,f=""): return \ f+"while ("+util.conv(sentence.test,mode=util.modes.EXPR)+"){\n"+\ util.walk_shallow(sentence.body,f+" ")+\ f+"}\n" def sent_if(sentence:ast.If,f=""): elif_list=[] #Make Elif Block list tmp=sentence.orelse while len(tmp)!=0 and type(tmp[0])==ast.If and len(tmp[0].orelse)!=0: elif_list.append(tmp) tmp=tmp[0].orelse blocks=[a[0] for a in elif_list] elseblock=tmp tmp="" #If Block tmp+="if("+util.conv(sentence.test,mode=util.modes.EXPR)+"){\n" tmp+= util.walk_shallow(sentence.body,f=f+" ") tmp+="}" #Elif Blocks for block in blocks: tmp+=f+"else if("+util.conv(block.test,mode=util.modes.EXPR)+"){\n" tmp+= util.walk_shallow(block.body,f+" ") tmp+=f+"}" #Else Block if len(elseblock)!=0: tmp+=f+"else{\n" tmp+= util.walk_shallow(elseblock,f+" ") tmp+=f+"}" return tmp+"\n" def sent_with(sentence:ast.With,f=""): tmp="" tmp+=f+"\n" for item in sentence.items: tmp+=f+util.conv(item.optional_vars,mode=util.modes.EXPR)+" = "+util.conv(item.context_expr,mode=util.modes.EXPR)+".__enter__();\n" tmp+=util.walk_shallow(sentence.body,f) for item in sentence.items: tmp+=f+util.conv(item.optional_vars,mode=util.modes.EXPR)+" = "+util.conv(item.context_expr,mode=util.modes.EXPR)+".__exit__(nullptr,nullptr,nullptr);\n" tmp+=f+"\n" return tmp def sent_classdef(sentence:ast.ClassDef,f=""): tmp="" tmp+=f+"class _"+sentence.name if len(sentence.bases) != 0: tmp+=": " tmp+=", ".join(["public "+util.conv(base,mode=util.modes.EXPR) for base in sentence.bases]) tmp+="\n" tmp+="{\n" tmp+=util.walk_shallow(sentence.body,f=f+" ") tmp+="}\n" decor_proc="_"+sentence.name decors=[util.conv(a,mode=util.modes.EXPR) for a in sentence.decorator_list] decors.reverse() for decor in decors: decor_proc=f"{decor}({decor_proc})" tmp+=f"#define {sentence.name} {decor_proc}\n" return tmp def sent_augAssign(sentence:ast.AugAssign,f=""): return f+util.conv(sentence.target,mode=util.modes.EXPR)+util.conv(sentence.op,mode=util.modes.EXPR)+"="+util.conv(sentence.value,mode=util.modes.EXPR)+";\n" def sent_raise(sentence:ast.Raise,f=""): return f+"throw "+util.conv(sentence.exc,mode=util.modes.EXPR)+";\n" def sent_delete(sentence:ast.Delete,f=""): return f+"delete" + ", ".join([util.conv(a,mode=util.modes.EXPR) for a in sentence.targets])+";\n" def sent_try(sentence:ast.Try,f=""): s="" s+=f+"try{\n" s+= util.walk_shallow(sentence.body,f+" ") s+= util.walk_shallow(sentence.finalbody,f+" ") s+=f+"}" for handler in sentence.handlers: name=handler.name if not name: name="ex" s+=f+"catch("+util.conv(handler.type,mode=util.modes.EXPR)+" "+name+"){\n" s+= util.walk_shallow(handler.body,f+" ") s+= util.walk_shallow(sentence.finalbody,f+" ") s+=f+"}" if len(sentence.orelse)!=0: s+= util.walk_shallow(sentence.orelse,f) return s def sent_assert(sentence:ast.Assert,f=""): return f+"Core::assert("+util.conv(sentence.test,mode=util.modes.EXPR)+","+util.conv(sentence.msg,mode=util.modes.EXPR)+");\n" def sent_YieldFrom(sentence:ast.YieldFrom,f=""): s="" s+=f+"for(Any value:"+util.conv(sentence.value,mode=util.modes.EXPR)+"){" s+=f+" yield value" s+=f+"}\n" return s def sent_nonlocal(sentence:ast.Nonlocal,f=""): return "" def sent_global(sentence:ast.Global,f=""): return "" def sent_AnnAssign(sentence:ast.AnnAssign,f=""): value="" if sentence.value: value="="+util.conv(sentence.value,mode=util.modes.EXPR) annotation=util.conv(sentence.annotation,mode=util.modes.EXPR) name=util.conv(sentence.target,mode=util.modes.EXPR) return annotation+" "+name+value+";\n" table={ "Import":sent_import, "ImportFrom":sent_importfrom, "FunctionDef":sent_funcdef, "Return":sent_ret, "Assign":sent_assign, "For":sent_for, "While":sent_while, "If":sent_if, "With":sent_with, "Expr":lambda a,f="":util.conv(a.value,f=f)+";\n", "Call":lambda val,f="":f+expr_call(val)+";\n", "Pass":lambda a,f="": f+"pass\n", "ClassDef":sent_classdef, "AugAssign":sent_augAssign, "Raise":sent_raise, "Delete":sent_delete, "Break":lambda a,f="":f+"break\n", "Try":sent_try, "Assert":sent_assert, "Continue":lambda a,f="":f+"Continue\n", "YieldFrom":sent_YieldFrom, "Nonlocal":sent_nonlocal, "Global":sent_global, "AsyncFunctionDef":sent_funcdef, "AnnAssign":sent_AnnAssign }
#Defines analyze of ast sentence functions import ast from exprs import expr_args, expr_call, expr_name import os import util import datamgr import libnames def sent_import(sentence:ast.Import,f=""): tmp="" for a in sentence.names: name=a.name name=name.replace(".","/") if os.path.exists(name+".py"): tmp+=f+"#include \""+name+".cpp"+"\"\n" if not os.path.abspath(name+".py") in datamgr.dictmgr.get("internal","converted"): datamgr.queuemgr.put("srcs",os.path.abspath(name+".py")) else: if name.split("/")[0] in libnames.names: tmp+=f+"#include <"+name+".cpp"+">\n" else: tmp+=f+"#include <"+name+">\n" if a.asname: tmp+=f+f"#define {a.asname} {name}\n" return tmp def sent_importfrom(sentence:ast.ImportFrom,f=""): tmp="" name=sentence.module name=name.replace(".","/") if os.path.exists(name+".py"): tmp+=f+"#include \""+name+".cpp"+"\"\n" datamgr.queuemgr.put("srcs",os.path.abspath(name+".py")) else: if name.split("/")[0] in libnames.names: tmp+=f+"#include <"+name+".cpp"+">\n" else: tmp+=f+"#include <"+name+">\n" for a in sentence.names: if a.asname: tmp+=f+f"#define {a.asname} {a.name}\n" return tmp def sent_funcdef(sentence:ast.FunctionDef,f=""): if type(sentence.body[0]) == ast.Expr and type(sentence.body[0].value) == ast.Constant: body=sentence.body[1:] else: body=sentence.body return \ f+"Any "+sentence.name+"("+expr_args(sentence.args)+")"+"{\n"+\ util.walk_shallow(body,f+" ")+\ f+"}\n" def sent_ret(sentence:ast.Return,f=""): return f+"return "+util.conv(sentence.value,mode=util.modes.EXPR)+";\n" def sent_assign(sentence:ast.Assign,f=""): ret="" value=util.conv(sentence.value,mode=util.modes.EXPR) for i,target in enumerate(sentence.targets): ret+=f #if util.conv(target,mode=util.modes.EXPR) not in datamgr.dictmgr.get("session","definedVariables"): if type(target) != ast.Attribute: ret+="Any " ret+=util.conv(target,mode=util.modes.EXPR) ret+=" = "+value if len(sentence.targets)!=1: ret+="["+str(i)+"]" ret+=";\n" return ret def sent_for(sentence:ast.For,f=""): return \ f+"for ("+"auto "+util.conv(sentence.target,mode=util.modes.EXPR)+" : "+util.conv(sentence.iter,mode=util.modes.EXPR)+"){\n"+\ util.walk_shallow(sentence.body,f+" ")+\ f+"}\n" def sent_while(sentence:ast.While,f=""): return \ f+"while ("+util.conv(sentence.test,mode=util.modes.EXPR)+"){\n"+\ util.walk_shallow(sentence.body,f+" ")+\ f+"}\n" def sent_if(sentence:ast.If,f=""): elif_list=[] #Make Elif Block list tmp=sentence.orelse while len(tmp)!=0 and type(tmp[0])==ast.If and len(tmp[0].orelse)!=0: elif_list.append(tmp) tmp=tmp[0].orelse blocks=[a[0] for a in elif_list] elseblock=tmp tmp="" #If Block tmp+="if("+util.conv(sentence.test,mode=util.modes.EXPR)+"){\n" tmp+= util.walk_shallow(sentence.body,f=f+" ") tmp+="}" #Elif Blocks for block in blocks: tmp+=f+"else if("+util.conv(block.test,mode=util.modes.EXPR)+"){\n" tmp+= util.walk_shallow(block.body,f+" ") tmp+=f+"}" #Else Block if len(elseblock)!=0: tmp+=f+"else{\n" tmp+= util.walk_shallow(elseblock,f+" ") tmp+=f+"}" return tmp+"\n" def sent_with(sentence:ast.With,f=""): tmp="" tmp+=f+"\n" for item in sentence.items: tmp+=f+util.conv(item.optional_vars,mode=util.modes.EXPR)+" = "+util.conv(item.context_expr,mode=util.modes.EXPR)+".__enter__();\n" tmp+=util.walk_shallow(sentence.body,f) for item in sentence.items: tmp+=f+util.conv(item.optional_vars,mode=util.modes.EXPR)+" = "+util.conv(item.context_expr,mode=util.modes.EXPR)+".__exit__(nullptr,nullptr,nullptr);\n" tmp+=f+"\n" return tmp def sent_classdef(sentence:ast.ClassDef,f=""): tmp="" tmp+=f+"class _"+sentence.name if len(sentence.bases) != 0: tmp+=": " tmp+=", ".join(["public "+util.conv(base,mode=util.modes.EXPR) for base in sentence.bases]) tmp+="\n" tmp+="{\n" tmp+=util.walk_shallow(sentence.body,f=f+" ") tmp+="}\n" decor_proc="_"+sentence.name decors=[util.conv(a,mode=util.modes.EXPR) for a in sentence.decorator_list] decors.reverse() for decor in decors: decor_proc=f"{decor}({decor_proc})" tmp+=f"#define {sentence.name} {decor_proc}\n" return tmp def sent_augAssign(sentence:ast.AugAssign,f=""): return f+util.conv(sentence.target,mode=util.modes.EXPR)+util.conv(sentence.op,mode=util.modes.EXPR)+"="+util.conv(sentence.value,mode=util.modes.EXPR)+";\n" def sent_raise(sentence:ast.Raise,f=""): return f+"throw "+util.conv(sentence.exc,mode=util.modes.EXPR)+";\n" def sent_delete(sentence:ast.Delete,f=""): return f+"delete" + ", ".join([util.conv(a,mode=util.modes.EXPR) for a in sentence.targets])+";\n" def sent_try(sentence:ast.Try,f=""): s="" s+=f+"try{\n" s+= util.walk_shallow(sentence.body,f+" ") s+= util.walk_shallow(sentence.finalbody,f+" ") s+=f+"}" for handler in sentence.handlers: name=handler.name if not name: name="ex" s+=f+"catch("+util.conv(handler.type,mode=util.modes.EXPR)+" "+name+"){\n" s+= util.walk_shallow(handler.body,f+" ") s+= util.walk_shallow(sentence.finalbody,f+" ") s+=f+"}" if len(sentence.orelse)!=0: s+= util.walk_shallow(sentence.orelse,f) return s def sent_assert(sentence:ast.Assert,f=""): return f+"Core::assert("+util.conv(sentence.test,mode=util.modes.EXPR)+","+util.conv(sentence.msg,mode=util.modes.EXPR)+");\n" def sent_YieldFrom(sentence:ast.YieldFrom,f=""): s="" s+=f+"for(Any value:"+util.conv(sentence.value,mode=util.modes.EXPR)+"){" s+=f+" yield value" s+=f+"}\n" return s def sent_nonlocal(sentence:ast.Nonlocal,f=""): return "" def sent_global(sentence:ast.Global,f=""): return "" def sent_AnnAssign(sentence:ast.AnnAssign,f=""): value="" if sentence.value: value="="+util.conv(sentence.value,mode=util.modes.EXPR) annotation=util.conv(sentence.annotation,mode=util.modes.EXPR) name=util.conv(sentence.target,mode=util.modes.EXPR) return annotation+" "+name+value+";\n" table={ "Import":sent_import, "ImportFrom":sent_importfrom, "FunctionDef":sent_funcdef, "Return":sent_ret, "Assign":sent_assign, "For":sent_for, "While":sent_while, "If":sent_if, "With":sent_with, "Expr":lambda a,f="":util.conv(a.value,f=f)+";\n", "Call":lambda val,f="":f+expr_call(val)+";\n", "Pass":lambda a,f="": f+"pass\n", "ClassDef":sent_classdef, "AugAssign":sent_augAssign, "Raise":sent_raise, "Delete":sent_delete, "Break":lambda a,f="":f+"break\n", "Try":sent_try, "Assert":sent_assert, "Continue":lambda a,f="":f+"Continue\n", "YieldFrom":sent_YieldFrom, "Nonlocal":sent_nonlocal, "Global":sent_global, "AsyncFunctionDef":sent_funcdef, "AnnAssign":sent_AnnAssign }
en
0.432254
#Defines analyze of ast sentence functions #if util.conv(target,mode=util.modes.EXPR) not in datamgr.dictmgr.get("session","definedVariables"): #Make Elif Block list #If Block #Elif Blocks #Else Block
2.544352
3
carbrain/geneticAlgorithm.py
jocelynthiojaya/Self-Learning-Cars
0
6613212
<gh_stars>0 import random import numpy as np class geneticAlgorithm: def __init__(self, parents1, parents2): self.parents1 = parents1 self.parents2 = parents2 self.child1 = [] self.child2 = [] def crossover(self, alt=False): """ Crossover genetic function. alt is for alternative random splicing """ if len(self.parents1) == len(self.parents2): #check the size of the parents. #get the size of parents sizeParents = len(self.parents1) if alt: #generate random numbers to slice the parents into several parts. slice_parents = random.randint(2, sizeParents-1) #determine the crossover point. Generate random number to determine the bound for crossover point crossover_array = np.array([random.randint(1,(sizeParents-1)) for _ in range(slice_parents)]) crossover_array.sort() #remove duplicate numbers crossover_array = list(dict.fromkeys(crossover_array)) #count the number of slices again. slice_parents = len(crossover_array) #do the crossover for i in range(slice_parents): bounds_top = crossover_array[i] #print(bounds_top) bounds_low = crossover_array[i-1] if len(self.child1) == 0 : self.child1 = np.concatenate([self.child1, self.parents1[0:bounds_top]]) self.child2 = np.concatenate([self.child2, self.parents2[0:bounds_top]]) flag_parents = 1 # if the flag is 1, it will take the value from parents 2 for child 1 and parents 1 for child 2 elif flag_parents == 1: self.child1 = np.concatenate([self.child1, self.parents2[bounds_low:bounds_top]]) self.child2 = np.concatenate([self.child2, self.parents1[bounds_low:bounds_top]]) flag_parents = 0 # if the flag is 0, it will take the value from parents 1 for child 1 and parents 2 for child 2 elif flag_parents == 0 and len(self.child1) != 0: self.child1 = np.concatenate([self.child1, self.parents1[bounds_low:bounds_top]]) self.child2 = np.concatenate([self.child2, self.parents2[bounds_low:bounds_top]]) flag_parents = 1 #ini buat yg belakangnya. if flag_parents == 0: self.child1 = np.concatenate([self.child1, self.parents1[bounds_top:]]) self.child2 = np.concatenate([self.child2, self.parents2[bounds_top:]]) elif flag_parents == 1: self.child1 = np.concatenate([self.child1, self.parents2[bounds_top:]]) self.child2 = np.concatenate([self.child2, self.parents1[bounds_top:]]) else: crossover_point = random.randint(1,(sizeParents - 1)) self.child1 = list(np.concatenate([self.parents1[0:crossover_point], self.parents2[crossover_point:]])) self.child2 = list(np.concatenate([self.parents2[0:crossover_point], self.parents1[crossover_point:]])) return self.child1, self.child2 def mutation(self, percentage=0.1, alt=False): """ Percentage dictates how many value will be mutated. (0.0-1.0) """ self.crossover(alt) #generate the random numbers to find the gene that we want to swap. for _ in range(int(38*percentage)): random_numbers = random.randint(0,37) self.child1[random_numbers] = random.random() self.child2[random_numbers] = random.random() return self.child1, self.child2 # parents1 = np.array([1 for _ in range(38)]) # parents2 = np.array([0 for _ in range(38)]) # #print("parents1 = " , parents1) # #print("parents2 = " , parents2) # g1 = geneticAlgorithm(parents1,parents2) # print(list(g1.mutation()[1]))
import random import numpy as np class geneticAlgorithm: def __init__(self, parents1, parents2): self.parents1 = parents1 self.parents2 = parents2 self.child1 = [] self.child2 = [] def crossover(self, alt=False): """ Crossover genetic function. alt is for alternative random splicing """ if len(self.parents1) == len(self.parents2): #check the size of the parents. #get the size of parents sizeParents = len(self.parents1) if alt: #generate random numbers to slice the parents into several parts. slice_parents = random.randint(2, sizeParents-1) #determine the crossover point. Generate random number to determine the bound for crossover point crossover_array = np.array([random.randint(1,(sizeParents-1)) for _ in range(slice_parents)]) crossover_array.sort() #remove duplicate numbers crossover_array = list(dict.fromkeys(crossover_array)) #count the number of slices again. slice_parents = len(crossover_array) #do the crossover for i in range(slice_parents): bounds_top = crossover_array[i] #print(bounds_top) bounds_low = crossover_array[i-1] if len(self.child1) == 0 : self.child1 = np.concatenate([self.child1, self.parents1[0:bounds_top]]) self.child2 = np.concatenate([self.child2, self.parents2[0:bounds_top]]) flag_parents = 1 # if the flag is 1, it will take the value from parents 2 for child 1 and parents 1 for child 2 elif flag_parents == 1: self.child1 = np.concatenate([self.child1, self.parents2[bounds_low:bounds_top]]) self.child2 = np.concatenate([self.child2, self.parents1[bounds_low:bounds_top]]) flag_parents = 0 # if the flag is 0, it will take the value from parents 1 for child 1 and parents 2 for child 2 elif flag_parents == 0 and len(self.child1) != 0: self.child1 = np.concatenate([self.child1, self.parents1[bounds_low:bounds_top]]) self.child2 = np.concatenate([self.child2, self.parents2[bounds_low:bounds_top]]) flag_parents = 1 #ini buat yg belakangnya. if flag_parents == 0: self.child1 = np.concatenate([self.child1, self.parents1[bounds_top:]]) self.child2 = np.concatenate([self.child2, self.parents2[bounds_top:]]) elif flag_parents == 1: self.child1 = np.concatenate([self.child1, self.parents2[bounds_top:]]) self.child2 = np.concatenate([self.child2, self.parents1[bounds_top:]]) else: crossover_point = random.randint(1,(sizeParents - 1)) self.child1 = list(np.concatenate([self.parents1[0:crossover_point], self.parents2[crossover_point:]])) self.child2 = list(np.concatenate([self.parents2[0:crossover_point], self.parents1[crossover_point:]])) return self.child1, self.child2 def mutation(self, percentage=0.1, alt=False): """ Percentage dictates how many value will be mutated. (0.0-1.0) """ self.crossover(alt) #generate the random numbers to find the gene that we want to swap. for _ in range(int(38*percentage)): random_numbers = random.randint(0,37) self.child1[random_numbers] = random.random() self.child2[random_numbers] = random.random() return self.child1, self.child2 # parents1 = np.array([1 for _ in range(38)]) # parents2 = np.array([0 for _ in range(38)]) # #print("parents1 = " , parents1) # #print("parents2 = " , parents2) # g1 = geneticAlgorithm(parents1,parents2) # print(list(g1.mutation()[1]))
en
0.719166
Crossover genetic function. alt is for alternative random splicing #check the size of the parents. #get the size of parents #generate random numbers to slice the parents into several parts. #determine the crossover point. Generate random number to determine the bound for crossover point #remove duplicate numbers #count the number of slices again. #do the crossover #print(bounds_top) # if the flag is 1, it will take the value from parents 2 for child 1 and parents 1 for child 2 # if the flag is 0, it will take the value from parents 1 for child 1 and parents 2 for child 2 #ini buat yg belakangnya. Percentage dictates how many value will be mutated. (0.0-1.0) #generate the random numbers to find the gene that we want to swap. # parents1 = np.array([1 for _ in range(38)]) # parents2 = np.array([0 for _ in range(38)]) # #print("parents1 = " , parents1) # #print("parents2 = " , parents2) # g1 = geneticAlgorithm(parents1,parents2) # print(list(g1.mutation()[1]))
3.446619
3
train.py
samux87/Image_Classifier
0
6613213
# Created by <NAME> 25/8/18 import matplotlib.pyplot as plt import numpy as np import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from collections import OrderedDict from torch.autograd import Variable from PIL import Image import os, random import pandas as pd import seaborn as sb import argparse import Utils as u import json argP = argparse.ArgumentParser(description='USAGE: train.py data_dir --arch --hidden_units1 --learning_rate --epochs --dropout --gpu') argP.add_argument('data_dir', nargs='*', action="store", default="./flowers/") argP.add_argument('--arch', dest="arch", action="store", default="vgg16", type = str) argP.add_argument('--hidden_units1', type=int, dest="fc1_nodes", action="store", default=1000) argP.add_argument('--learning_rate', dest="learning_rate", action="store", default=0.001) argP.add_argument('--epochs', dest="epochs", action="store", type=int, default=1) argP.add_argument('--gpu', dest="gpu", action="store", default="cpu") #argP.add_argument('--save_dir', dest="save_dir", action="store", default="./checkpointPy.pth") argP.add_argument('--dropout', dest = "dropout", action = "store", default = 0.5) args = argP.parse_args() # Check on input args if args.arch not in ['vgg16', 'vgg13', 'alexnet', 'resnet18', 'densenet121']: print('The specified architecture is not available') img_path = args.data_dir arch = args.arch dropout = args.dropout fc1_nodes = args.fc1_nodes learning_rate = args.learning_rate epochs = args.epochs gpu = args.gpu outputNodes = 102 print_every = 20 trainloader, validloader, testloader, image_datasets = u.load_dataSet(img_path) model, criterion, optimizer = u.nn_init(arch, dropout, fc1_nodes, outputNodes, learning_rate, gpu) u.do_deep_learning(model, trainloader, validloader, epochs, print_every, criterion, optimizer, gpu) model.class_to_idx = image_datasets['train'].class_to_idx u.save_checkpoint(img_path, model, optimizer, epochs, fc1_nodes, learning_rate, arch) print("Model Configured, Trained and Saved!")
# Created by <NAME> 25/8/18 import matplotlib.pyplot as plt import numpy as np import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from collections import OrderedDict from torch.autograd import Variable from PIL import Image import os, random import pandas as pd import seaborn as sb import argparse import Utils as u import json argP = argparse.ArgumentParser(description='USAGE: train.py data_dir --arch --hidden_units1 --learning_rate --epochs --dropout --gpu') argP.add_argument('data_dir', nargs='*', action="store", default="./flowers/") argP.add_argument('--arch', dest="arch", action="store", default="vgg16", type = str) argP.add_argument('--hidden_units1', type=int, dest="fc1_nodes", action="store", default=1000) argP.add_argument('--learning_rate', dest="learning_rate", action="store", default=0.001) argP.add_argument('--epochs', dest="epochs", action="store", type=int, default=1) argP.add_argument('--gpu', dest="gpu", action="store", default="cpu") #argP.add_argument('--save_dir', dest="save_dir", action="store", default="./checkpointPy.pth") argP.add_argument('--dropout', dest = "dropout", action = "store", default = 0.5) args = argP.parse_args() # Check on input args if args.arch not in ['vgg16', 'vgg13', 'alexnet', 'resnet18', 'densenet121']: print('The specified architecture is not available') img_path = args.data_dir arch = args.arch dropout = args.dropout fc1_nodes = args.fc1_nodes learning_rate = args.learning_rate epochs = args.epochs gpu = args.gpu outputNodes = 102 print_every = 20 trainloader, validloader, testloader, image_datasets = u.load_dataSet(img_path) model, criterion, optimizer = u.nn_init(arch, dropout, fc1_nodes, outputNodes, learning_rate, gpu) u.do_deep_learning(model, trainloader, validloader, epochs, print_every, criterion, optimizer, gpu) model.class_to_idx = image_datasets['train'].class_to_idx u.save_checkpoint(img_path, model, optimizer, epochs, fc1_nodes, learning_rate, arch) print("Model Configured, Trained and Saved!")
en
0.086384
# Created by <NAME> 25/8/18 #argP.add_argument('--save_dir', dest="save_dir", action="store", default="./checkpointPy.pth") # Check on input args
2.130892
2
mep/Downloads.py
guimath/MEProject
0
6613214
<reponame>guimath/MEProject import os import requests #(uses only requests.get) import shutil # (uses only shutil.copyfileobj) import json import youtube_dl # ~ Lib responsible of all downloads (image and music) ~ # """ Downloading picture from specified url as specified filename to specified path @return the name of the new downloaded file if worked correctly, else returns '' """ def dl_image(file_url, filename, interface): # Open the url image, set stream to True, this will return the stream content. try: r = requests.get(file_url, stream=True) # Check if the image was retrieved successfully if r.status_code == 200: # Set decode_content value to True, otherwise the downloaded image file's size will be zero. r.raw.decode_content = True # Open a local file with wb ( write binary ) permission. with open(filename, 'wb') as f: shutil.copyfileobj(r.raw, f) return filename else: interface.warn("image url can't be reached", "not adding image to file") return "" except: interface.warn("image downloading failed", "not adding image to file") return "" """ Downloading mp3 file from specified urlS """ def dl_music(url,no_playlist,logger, hook, lst=None): ydl_opts = { 'format': 'bestaudio/best', 'noplaylist': no_playlist, 'outtmpl' : "yt-DL_%(title)s.%(ext)s", #name of output file 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', },{ 'key': 'FFmpegMetadata', #adding metadata to file }], 'logger': logger, 'progress_hooks': hook, } if os.path.exists("ffmpeg") : ydl_opts['ffmpeg_location'] = './ffmpeg' if lst : ydl_opts['playlist_items'] = lst try : with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return True except Exception as e: logger.error(e.args) return False def check_out_playlist(url): class Interface : def __init__(self): self.videos = {} def debug(self, msg): if '{"_type": ' in msg : j = json.loads(msg) self.videos = j['entries'] if '[download] Downloading playlist:' in msg : self.playlist_name = msg.replace('[download] Downloading playlist: ','') def warning(self, msg): pass def error(self,msg): print(f'Error during yt-dl : {msg}') interface = Interface() ydl_opts = { 'dump_single_json' : True, 'extract_flat':'in_playlist', 'playlistend': 50, 'logger': interface, } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) res = [] for video in interface.videos : secs = int(video['duration']%60) mins = int((video['duration'] - secs)/60) duration = f'{mins}min {secs}s' #print(video) res.append({'title': video['title'],'uploader':video['uploader'], 'duration':duration, 'id':len(res)}) return res, interface.playlist_name
import os import requests #(uses only requests.get) import shutil # (uses only shutil.copyfileobj) import json import youtube_dl # ~ Lib responsible of all downloads (image and music) ~ # """ Downloading picture from specified url as specified filename to specified path @return the name of the new downloaded file if worked correctly, else returns '' """ def dl_image(file_url, filename, interface): # Open the url image, set stream to True, this will return the stream content. try: r = requests.get(file_url, stream=True) # Check if the image was retrieved successfully if r.status_code == 200: # Set decode_content value to True, otherwise the downloaded image file's size will be zero. r.raw.decode_content = True # Open a local file with wb ( write binary ) permission. with open(filename, 'wb') as f: shutil.copyfileobj(r.raw, f) return filename else: interface.warn("image url can't be reached", "not adding image to file") return "" except: interface.warn("image downloading failed", "not adding image to file") return "" """ Downloading mp3 file from specified urlS """ def dl_music(url,no_playlist,logger, hook, lst=None): ydl_opts = { 'format': 'bestaudio/best', 'noplaylist': no_playlist, 'outtmpl' : "yt-DL_%(title)s.%(ext)s", #name of output file 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', },{ 'key': 'FFmpegMetadata', #adding metadata to file }], 'logger': logger, 'progress_hooks': hook, } if os.path.exists("ffmpeg") : ydl_opts['ffmpeg_location'] = './ffmpeg' if lst : ydl_opts['playlist_items'] = lst try : with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return True except Exception as e: logger.error(e.args) return False def check_out_playlist(url): class Interface : def __init__(self): self.videos = {} def debug(self, msg): if '{"_type": ' in msg : j = json.loads(msg) self.videos = j['entries'] if '[download] Downloading playlist:' in msg : self.playlist_name = msg.replace('[download] Downloading playlist: ','') def warning(self, msg): pass def error(self,msg): print(f'Error during yt-dl : {msg}') interface = Interface() ydl_opts = { 'dump_single_json' : True, 'extract_flat':'in_playlist', 'playlistend': 50, 'logger': interface, } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) res = [] for video in interface.videos : secs = int(video['duration']%60) mins = int((video['duration'] - secs)/60) duration = f'{mins}min {secs}s' #print(video) res.append({'title': video['title'],'uploader':video['uploader'], 'duration':duration, 'id':len(res)}) return res, interface.playlist_name
en
0.721221
#(uses only requests.get) # (uses only shutil.copyfileobj) # ~ Lib responsible of all downloads (image and music) ~ # Downloading picture from specified url as specified filename to specified path @return the name of the new downloaded file if worked correctly, else returns '' # Open the url image, set stream to True, this will return the stream content. # Check if the image was retrieved successfully # Set decode_content value to True, otherwise the downloaded image file's size will be zero. # Open a local file with wb ( write binary ) permission. Downloading mp3 file from specified urlS #name of output file #adding metadata to file #print(video)
3.039563
3
src/test_lis_length.py
manoldonev/algo-challenges
0
6613215
<filename>src/test_lis_length.py import unittest from lis_length import find_length_of_lis class LISLengthTests(unittest.TestCase): """Tests for length of longest increasing subsequence challenge.""" def test_case_1(self): self.assertEqual(find_length_of_lis([10, 9, 2, 5, 3, 7, 101, 18]), 4) def test_case_2(self): self.assertEqual(find_length_of_lis([]), 0) def test_case_3(self): self.assertEqual(find_length_of_lis([0]), 1) if __name__ == "__main__": unittest.main(verbosity=2)
<filename>src/test_lis_length.py import unittest from lis_length import find_length_of_lis class LISLengthTests(unittest.TestCase): """Tests for length of longest increasing subsequence challenge.""" def test_case_1(self): self.assertEqual(find_length_of_lis([10, 9, 2, 5, 3, 7, 101, 18]), 4) def test_case_2(self): self.assertEqual(find_length_of_lis([]), 0) def test_case_3(self): self.assertEqual(find_length_of_lis([0]), 1) if __name__ == "__main__": unittest.main(verbosity=2)
en
0.88368
Tests for length of longest increasing subsequence challenge.
3.500306
4
World 02/Class 12/ex044.py
DanielRios549/PythonExcercises
6
6613216
''' Calculate the price of a product according to the pay method. In cash: 10% off Once with credit card: 5% off Twice with credit card: default price More than 3 times no cartão: 20% fee ''' print(f'{" Daniel Store ":=^40}') price = float(input('How much the product costs? R$')) method = int(input(''' How do you want to pay [ 1 ] In cash [ 2 ] Once with credit card [ 3 ] Twice with credit card [ 4 ] More than three times ''')) options = [1, 2, 3, 4] if method in options: if method == 1: newPrice = price - (price * 10 / 100) elif method == 2: newPrice = price - (price * 5 / 100) elif method == 3: newPrice = price print(f'The price will be divided \033[34mwithout fee\033[m, the installment will be \033[34mR$ {newPrice / 2:.2f}\033[m per month for 2 months long.') else: newPrice = price + (price * 20 / 100) installment = int(input('What will be the installment? ')) print(f'The price will be divided \033[31mwith fee\033[m, the installment will be \033[34mR${newPrice / installment:.2f}\033[m per month for {installment} months long.') print(f'The product that costs \033[34mR${price:.2f}\033[m will cost \033[34mR${newPrice:.2f}\033[m with this payment method.') else: print('Enter a valid option, please')
''' Calculate the price of a product according to the pay method. In cash: 10% off Once with credit card: 5% off Twice with credit card: default price More than 3 times no cartão: 20% fee ''' print(f'{" Daniel Store ":=^40}') price = float(input('How much the product costs? R$')) method = int(input(''' How do you want to pay [ 1 ] In cash [ 2 ] Once with credit card [ 3 ] Twice with credit card [ 4 ] More than three times ''')) options = [1, 2, 3, 4] if method in options: if method == 1: newPrice = price - (price * 10 / 100) elif method == 2: newPrice = price - (price * 5 / 100) elif method == 3: newPrice = price print(f'The price will be divided \033[34mwithout fee\033[m, the installment will be \033[34mR$ {newPrice / 2:.2f}\033[m per month for 2 months long.') else: newPrice = price + (price * 20 / 100) installment = int(input('What will be the installment? ')) print(f'The price will be divided \033[31mwith fee\033[m, the installment will be \033[34mR${newPrice / installment:.2f}\033[m per month for {installment} months long.') print(f'The product that costs \033[34mR${price:.2f}\033[m will cost \033[34mR${newPrice:.2f}\033[m with this payment method.') else: print('Enter a valid option, please')
en
0.939591
Calculate the price of a product according to the pay method. In cash: 10% off Once with credit card: 5% off Twice with credit card: default price More than 3 times no cartão: 20% fee How do you want to pay [ 1 ] In cash [ 2 ] Once with credit card [ 3 ] Twice with credit card [ 4 ] More than three times
4.181046
4
ArticleClassifierTF/src/tests/ArticlesTests.py
joduss/ArticleClassifier
0
6613217
import unittest from data_models.article import Article from data_models.articles import Articles class ArticlesTests(unittest.TestCase): @staticmethod def create_articles() -> Articles: article1 = Article(title="Title", summary="summary", themes=[], verified_themes=[], predicted_themes=[], id="1") article2 = Article(title="Title", summary="summary", themes=["T"], verified_themes=["T"], predicted_themes=[], id="2") article3 = Article(title="Title", summary="summary", themes=["T", "T2"], verified_themes=[], predicted_themes=[], id="3") article4 = Article(title="Title", summary="summary", themes=[], verified_themes=["T"], predicted_themes=[], id="4") article5 = Article(title="Title", summary="summary", themes=["T2"], verified_themes=["T"], predicted_themes=[], id="5") article6 = Article(title="Title", summary="summary", themes=["T", "T2", "T3"], verified_themes=["T", "T2", "T3"], predicted_themes=["T3"], id="6") return Articles([article1, article2, article3, article4, article5, article6]) def test_articles_with_theme(self): articles = ArticlesTests.create_articles() filtered = articles.articles_with_theme("T2") self.assertEqual(3, filtered.count()) self.assertTrue(articles.items[2] in filtered) self.assertTrue(articles.items[4] in filtered) self.assertTrue(articles.items[5] in filtered) self.assertFalse(articles.items[3] in filtered) def test_articles_with_all_verified_themes(self): articles = ArticlesTests.create_articles() filtered = articles.articles_with_all_verified_themes(["T", "T2"]) self.assertEqual(1, filtered.count()) self.assertTrue(articles.items[5] in filtered) self.assertFalse(articles.items[0] in filtered) def test_articles_with_any_verified_themes(self): articles = ArticlesTests.create_articles() filtered = articles.articles_with_any_verified_themes(["T", "T2", "T3"]) self.assertEqual(4, filtered.count()) self.assertFalse(articles[0] in filtered) self.assertTrue(articles[1] in filtered) self.assertFalse(articles[2] in filtered) self.assertTrue(articles[3] in filtered) self.assertTrue(articles[4] in filtered) self.assertTrue(articles[5] in filtered) def test_themes(self): themes = ArticlesTests.create_articles().themes() self.assertEqual(0, len(themes[0])) self.assertEqual(1, len(themes[1])) self.assertEqual(2, len(themes[2])) self.assertEqual(0, len(themes[3])) self.assertEqual(1, len(themes[4])) self.assertEqual(3, len(themes[5])) self.assertEqual("T", themes[5][0]) self.assertEqual("T2", themes[5][1]) self.assertEqual("T3", themes[5][2]) def test_title_and_summary(self): articles = self.create_articles() self.assertEqual("Title. summary", articles.title_and_summary()[0]) def test_deep_copy(self): articles = self.create_articles() articles_copy = articles.deep_copy() for i in range(0,articles.count()): article = articles.items[i] article_copy = articles_copy.items[i] self.assertEqual(article.id, article_copy.id) self.assertEqual(article.summary, article_copy.summary) self.assertEqual(article.title, article_copy.title) self.assertEqual(article.themes, article_copy.themes) self.assertEqual(article.verified_themes, article_copy.verified_themes) self.assertEqual(article.predicted_themes, article_copy.predicted_themes) article_copy.predicted_themes.append("T4") self.assertNotEqual(article.predicted_themes, article_copy.predicted_themes) article.predicted_themes.append("T4") self.assertEqual(article.predicted_themes, article_copy.predicted_themes) def test_substraction(self): articles = self.create_articles() articles_to_remove = Articles(self.create_articles()[0:2]) filtered_articles = articles - articles_to_remove self.assertEqual(filtered_articles.count() + 2, articles.count()) self.assertFalse(filtered_articles.contains(articles_to_remove[0].id)) self.assertFalse(filtered_articles.contains(articles_to_remove[1].id)) self.assertTrue(filtered_articles.contains(articles[2].id)) self.assertTrue(filtered_articles.contains(articles[3].id)) self.assertTrue(filtered_articles.contains(articles[4].id)) self.assertTrue(filtered_articles.contains(articles[5].id)) if __name__ == '__main__': unittest.main()
import unittest from data_models.article import Article from data_models.articles import Articles class ArticlesTests(unittest.TestCase): @staticmethod def create_articles() -> Articles: article1 = Article(title="Title", summary="summary", themes=[], verified_themes=[], predicted_themes=[], id="1") article2 = Article(title="Title", summary="summary", themes=["T"], verified_themes=["T"], predicted_themes=[], id="2") article3 = Article(title="Title", summary="summary", themes=["T", "T2"], verified_themes=[], predicted_themes=[], id="3") article4 = Article(title="Title", summary="summary", themes=[], verified_themes=["T"], predicted_themes=[], id="4") article5 = Article(title="Title", summary="summary", themes=["T2"], verified_themes=["T"], predicted_themes=[], id="5") article6 = Article(title="Title", summary="summary", themes=["T", "T2", "T3"], verified_themes=["T", "T2", "T3"], predicted_themes=["T3"], id="6") return Articles([article1, article2, article3, article4, article5, article6]) def test_articles_with_theme(self): articles = ArticlesTests.create_articles() filtered = articles.articles_with_theme("T2") self.assertEqual(3, filtered.count()) self.assertTrue(articles.items[2] in filtered) self.assertTrue(articles.items[4] in filtered) self.assertTrue(articles.items[5] in filtered) self.assertFalse(articles.items[3] in filtered) def test_articles_with_all_verified_themes(self): articles = ArticlesTests.create_articles() filtered = articles.articles_with_all_verified_themes(["T", "T2"]) self.assertEqual(1, filtered.count()) self.assertTrue(articles.items[5] in filtered) self.assertFalse(articles.items[0] in filtered) def test_articles_with_any_verified_themes(self): articles = ArticlesTests.create_articles() filtered = articles.articles_with_any_verified_themes(["T", "T2", "T3"]) self.assertEqual(4, filtered.count()) self.assertFalse(articles[0] in filtered) self.assertTrue(articles[1] in filtered) self.assertFalse(articles[2] in filtered) self.assertTrue(articles[3] in filtered) self.assertTrue(articles[4] in filtered) self.assertTrue(articles[5] in filtered) def test_themes(self): themes = ArticlesTests.create_articles().themes() self.assertEqual(0, len(themes[0])) self.assertEqual(1, len(themes[1])) self.assertEqual(2, len(themes[2])) self.assertEqual(0, len(themes[3])) self.assertEqual(1, len(themes[4])) self.assertEqual(3, len(themes[5])) self.assertEqual("T", themes[5][0]) self.assertEqual("T2", themes[5][1]) self.assertEqual("T3", themes[5][2]) def test_title_and_summary(self): articles = self.create_articles() self.assertEqual("Title. summary", articles.title_and_summary()[0]) def test_deep_copy(self): articles = self.create_articles() articles_copy = articles.deep_copy() for i in range(0,articles.count()): article = articles.items[i] article_copy = articles_copy.items[i] self.assertEqual(article.id, article_copy.id) self.assertEqual(article.summary, article_copy.summary) self.assertEqual(article.title, article_copy.title) self.assertEqual(article.themes, article_copy.themes) self.assertEqual(article.verified_themes, article_copy.verified_themes) self.assertEqual(article.predicted_themes, article_copy.predicted_themes) article_copy.predicted_themes.append("T4") self.assertNotEqual(article.predicted_themes, article_copy.predicted_themes) article.predicted_themes.append("T4") self.assertEqual(article.predicted_themes, article_copy.predicted_themes) def test_substraction(self): articles = self.create_articles() articles_to_remove = Articles(self.create_articles()[0:2]) filtered_articles = articles - articles_to_remove self.assertEqual(filtered_articles.count() + 2, articles.count()) self.assertFalse(filtered_articles.contains(articles_to_remove[0].id)) self.assertFalse(filtered_articles.contains(articles_to_remove[1].id)) self.assertTrue(filtered_articles.contains(articles[2].id)) self.assertTrue(filtered_articles.contains(articles[3].id)) self.assertTrue(filtered_articles.contains(articles[4].id)) self.assertTrue(filtered_articles.contains(articles[5].id)) if __name__ == '__main__': unittest.main()
none
1
3.016968
3
python/paddle/fluid/tests/unittests/npu/test_label_smooth_op_npu.py
zmxdream/Paddle
17,085
6613218
<gh_stars>1000+ # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import numpy as np import unittest import sys sys.path.append("..") from op_test import OpTest import paddle import paddle.fluid as fluid paddle.enable_static() SEED = 2021 @unittest.skipIf(not paddle.is_compiled_with_npu(), "core is not compiled with NPU") class TestLabelSmoothOp(OpTest): def setUp(self): self.set_npu() self.op_type = "label_smooth" self.place = paddle.NPUPlace(0) self.init_dtype() np.random.seed(SEED) self.set_inputs() self.set_attrs() self.set_outputs() def calc_out(self, label, epsilon, dist=None): label_dim = label.shape[-1] y = (1 - epsilon) * label if dist is not None: y += epsilon * dist else: y += epsilon / label_dim return y.astype(self.dtype) def set_inputs(self): batch_size, label_dim = 10, 12 x = np.zeros((batch_size, label_dim)).astype(self.dtype) nonzero_index = np.random.randint(label_dim, size=(batch_size)) x[np.arange(batch_size), nonzero_index] = 1 self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)} def set_attrs(self): epsilon = 0.1 self.attrs = {"epsilon": epsilon} def set_outputs(self): dist = None if 'PriorDist' not in self.inputs else self.inputs[ 'PriorDist'] out = self.calc_out(self.inputs['X'], self.attrs['epsilon'], dist) self.outputs = {'Out': out} def set_npu(self): self.__class__.use_npu = True def init_dtype(self): self.dtype = np.float32 def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): if self.dtype == np.float16: return self.check_grad_with_place(self.place, ['X'], 'Out') class TestLabelSmoothOpWithPriorDist(TestLabelSmoothOp): def set_inputs(self): super(TestLabelSmoothOpWithPriorDist, self).set_inputs() label_dim = self.inputs['X'].shape[-1] dist = np.random.random((1, label_dim)).astype(self.dtype) self.inputs['PriorDist'] = dist class TestLabelSmoothOp3D(TestLabelSmoothOp): def set_inputs(self): super(TestLabelSmoothOp3D, self).set_inputs() self.inputs['X'].reshape([2, -1, self.inputs['X'].shape[-1]]) class TestLabelSmoothOpWithPriorDist3D(TestLabelSmoothOpWithPriorDist): def set_inputs(self): super(TestLabelSmoothOpWithPriorDist3D, self).set_inputs() self.inputs['X'].reshape([2, -1, self.inputs['X'].shape[-1]]) class TestLabelSmoothOpFP16(TestLabelSmoothOp): def init_dtype(self): self.dtype = np.float16 class TestLabelSmoothOpWithPriorDistFP16(TestLabelSmoothOpWithPriorDist): def init_dtype(self): self.dtype = np.float16 class TestLabelSmoothOp3DFP16(TestLabelSmoothOp3D): def init_dtype(self): self.dtype = np.float16 class TestLabelSmoothOpWithPriorDist3DFP16(TestLabelSmoothOpWithPriorDist3D): def init_dtype(self): self.dtype = np.float16 if __name__ == '__main__': unittest.main()
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import numpy as np import unittest import sys sys.path.append("..") from op_test import OpTest import paddle import paddle.fluid as fluid paddle.enable_static() SEED = 2021 @unittest.skipIf(not paddle.is_compiled_with_npu(), "core is not compiled with NPU") class TestLabelSmoothOp(OpTest): def setUp(self): self.set_npu() self.op_type = "label_smooth" self.place = paddle.NPUPlace(0) self.init_dtype() np.random.seed(SEED) self.set_inputs() self.set_attrs() self.set_outputs() def calc_out(self, label, epsilon, dist=None): label_dim = label.shape[-1] y = (1 - epsilon) * label if dist is not None: y += epsilon * dist else: y += epsilon / label_dim return y.astype(self.dtype) def set_inputs(self): batch_size, label_dim = 10, 12 x = np.zeros((batch_size, label_dim)).astype(self.dtype) nonzero_index = np.random.randint(label_dim, size=(batch_size)) x[np.arange(batch_size), nonzero_index] = 1 self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)} def set_attrs(self): epsilon = 0.1 self.attrs = {"epsilon": epsilon} def set_outputs(self): dist = None if 'PriorDist' not in self.inputs else self.inputs[ 'PriorDist'] out = self.calc_out(self.inputs['X'], self.attrs['epsilon'], dist) self.outputs = {'Out': out} def set_npu(self): self.__class__.use_npu = True def init_dtype(self): self.dtype = np.float32 def test_check_output(self): self.check_output_with_place(self.place) def test_check_grad(self): if self.dtype == np.float16: return self.check_grad_with_place(self.place, ['X'], 'Out') class TestLabelSmoothOpWithPriorDist(TestLabelSmoothOp): def set_inputs(self): super(TestLabelSmoothOpWithPriorDist, self).set_inputs() label_dim = self.inputs['X'].shape[-1] dist = np.random.random((1, label_dim)).astype(self.dtype) self.inputs['PriorDist'] = dist class TestLabelSmoothOp3D(TestLabelSmoothOp): def set_inputs(self): super(TestLabelSmoothOp3D, self).set_inputs() self.inputs['X'].reshape([2, -1, self.inputs['X'].shape[-1]]) class TestLabelSmoothOpWithPriorDist3D(TestLabelSmoothOpWithPriorDist): def set_inputs(self): super(TestLabelSmoothOpWithPriorDist3D, self).set_inputs() self.inputs['X'].reshape([2, -1, self.inputs['X'].shape[-1]]) class TestLabelSmoothOpFP16(TestLabelSmoothOp): def init_dtype(self): self.dtype = np.float16 class TestLabelSmoothOpWithPriorDistFP16(TestLabelSmoothOpWithPriorDist): def init_dtype(self): self.dtype = np.float16 class TestLabelSmoothOp3DFP16(TestLabelSmoothOp3D): def init_dtype(self): self.dtype = np.float16 class TestLabelSmoothOpWithPriorDist3DFP16(TestLabelSmoothOpWithPriorDist3D): def init_dtype(self): self.dtype = np.float16 if __name__ == '__main__': unittest.main()
en
0.856067
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
2.130839
2
src/logger.py
Amin-egn/InnerFire
0
6613219
<filename>src/logger.py # standard import logging # internal from src import conf # logger _logger = logging.Logger(conf.LOG_NAME) _logger_level = logging.WARNING _logger.setLevel(_logger_level) # file handler fh = logging.FileHandler(conf.LOG_FILE, 'w', 'utf-8') fh.setLevel(_logger_level) # format formatter = logging.Formatter(conf.LOG_FORMAT) # add format to fild handler fh.setFormatter(formatter) # add file handler to logger _logger.addHandler(fh) # interface warning = _logger.warning error = _logger.error
<filename>src/logger.py # standard import logging # internal from src import conf # logger _logger = logging.Logger(conf.LOG_NAME) _logger_level = logging.WARNING _logger.setLevel(_logger_level) # file handler fh = logging.FileHandler(conf.LOG_FILE, 'w', 'utf-8') fh.setLevel(_logger_level) # format formatter = logging.Formatter(conf.LOG_FORMAT) # add format to fild handler fh.setFormatter(formatter) # add file handler to logger _logger.addHandler(fh) # interface warning = _logger.warning error = _logger.error
en
0.484664
# standard # internal # logger # file handler # format # add format to fild handler # add file handler to logger # interface
2.484854
2
Automate_VTEC.py
lowandrew/ROGA_Redmine
0
6613220
# This is where I'll learn to use python-docx so that ROGAs can get automated. from Automate import Automate class VTEC_Automator(Automate): def get_serotype(self): import csv # Now we need to get the serotype since this is Ecoli. serotype_data = csv.DictReader(open(self.nasmnt + "WGSspades/reports/serotype.csv", encoding="ISO-8859-1")) for row in serotype_data: if row["Strain"] in self.names: serotype = dict() serotype["O"] = row["O-type"] serotype["H"] = row["H-type"] self.metadata[row["Strain"]]["serotype"] = serotype serotype_data = csv.DictReader(open(self.nasmnt + "External_WGSspades/reports/serotype.csv", encoding="ISO-8859-1")) for row in serotype_data: if row["Strain"] in self.names: serotype = dict() serotype["O"] = row["O-type"] serotype["H"] = row["H-type"] self.metadata[row["Strain"]]["serotype"] = serotype # This prints the GeneSeekr Analysis table and the Sequence Data Quality Table to the doc. def print_tables_to_docx(self): import docx doc = docx.Document("vtec_template.docx") j = 2 # GeneSeekr Analysis Table. for name in self.names: # Add a new row to the table for each SEQID to be added. doc.tables[2].add_row() # Input sample names. Automate.add_text_to_cell(self.metadata[name]["TextualID"] + "\n(" "" + self.metadata[name]["IsolateID"] + ")", j, 0, doc.tables[2]) # Input uidA presence/absence if "uidA" in self.metadata[name]["geneSeekr"]: Automate.add_text_to_cell(u"\u2022", j, 1, doc.tables[2]) else: Automate.add_text_to_cell("ND", j, 1, doc.tables[2]) # Input O and H types. Automate.add_text_to_cell(self.metadata[name]["serotype"]["O"].replace("(100.0)", ""), j, 2, doc.tables[2]) Automate.add_text_to_cell(self.metadata[name]["serotype"]["H"].replace("(100.0)", ""), j, 3, doc.tables[2]) # Input the Ecoli specific virulence genes. # This way of doing things is really inflexible and generally not great, but it'll work for now. if "hlyA" in self.metadata[name]["geneSeekr"]: Automate.add_text_to_cell(u"\u2022", j, 4, doc.tables[2]) else: Automate.add_text_to_cell("ND", j, 4, doc.tables[2]) # The following stretch of code is amongst the ugliest stuff you've ever written. # Output eae genes present = False for item in self.metadata[name]["geneSeekr"]: if "eae" in item: Automate.add_text_to_cell(item + ";", j, 5, doc.tables[2], italicize=True) present = True if not present: Automate.add_text_to_cell("ND", j, 5, doc.tables[2]) # Output vt1 genes. present = False for item in self.metadata[name]["geneSeekr"]: if "vt1" in item or "VT1" in item: Automate.add_text_to_cell(item + ";", j, 6, doc.tables[2], italicize=True) present = True if not present: Automate.add_text_to_cell("ND", j, 5, doc.tables[2]) # Output vt2 genes. present = False for item in self.metadata[name]["geneSeekr"]: if "vt2" in item or "VT2" in item: Automate.add_text_to_cell(item + ";", j, 7, doc.tables[2], italicize=True) present = True if not present: Automate.add_text_to_cell("ND", j, 7, doc.tables[2]) # Input MLST types. # Enter the MLST type. Automate.add_text_to_cell(self.metadata[name]["MLST"], j, 9, doc.tables[2]) # Enter the type for each of the seven genes. Again, this code is inflexible and not great, but works. for i in range(10, 17): Automate.add_text_to_cell(self.metadata[name]["mlst_info"][i - 10], j, i, doc.tables[2]) doc.tables[2].cell(j, 8).merge(doc.tables[2].cell(j, 9)) Automate.add_text_to_cell("", j, 9, doc.tables[2]) j += 1 # Sequence Data quality table. j = 1 for name in self.names: # Add a new row to the table for each SEQID to be added. doc.tables[3].add_row() # Input SEQIDS. Automate.add_text_to_cell(self.metadata[name]["TextualID"] + "\n" "(" + self.metadata[name]["IsolateID"] + ")", j, 0, doc.tables[3]) Automate.add_text_to_cell(name, j, 1, doc.tables[3]) doc.tables[3].cell(j, 1).text = name # Input total length. length = int(self.metadata[name]["TotalLength"]) Automate.add_text_to_cell(str(length), j, 2, doc.tables[3]) # Input coverage. cov = float(self.metadata[name]["Coverage"]) covstr = "%.1f" % cov Automate.add_text_to_cell(covstr, j, 3, doc.tables[3]) # Input % Identity GDCS, rST, and Pass/Fail. percent_id = float(self.metadata[name]["Matches"])/53.0 * 100.0 Automate.add_text_to_cell(str(percent_id), j, 4, doc.tables[3]) Automate.add_text_to_cell(self.metadata[name]["rST"], j, 5, doc.tables[3]) if percent_id == 100.0: Automate.add_text_to_cell("Pass", j, 6, doc.tables[3]) else: Automate.add_text_to_cell("Fail", j, 6, doc.tables[3]) # Finally, input pipeline version. Automate.add_text_to_cell(self.metadata[name]["PipelineVersion"], j, 7, doc.tables[3]) j += 1 doc.save(self.outfile) def find_verotoxin_genes(self): verotoxin_genes = list() for strain in self.metadata: for item in self.metadata[strain]["geneSeekr"]: if "VT" in item or "vt" in item: if item not in verotoxin_genes: verotoxin_genes.append(item) return verotoxin_genes # This takes care of printing the SNVPhyl summary to docx. def print_summary_to_docx(self): import docx import re doc = docx.Document(self.outfile) tables = doc.tables # This is going to be long and messy, but I'm not sure of a better way to do it. tables[1].cell(0, 0).text = "" para = tables[1].cell(0, 0).add_paragraph("") para.add_run("Identification Summary:\n\n").bold = True if len(self.names) == 1: para.add_run("Strain " + self.metadata[self.names[0]]["TextualID"]) para.add_run(" was submitted to for whole-genome sequencing and confirmed to be ") else: para.add_run(str(len(self.names)) + " strains (see Table 1)") para.add_run(" were submitted for whole-genome sequencing and confirmed to be ") para.add_run("VTEC") para.add_run(" based on the detection of probe sequences (e-probes) indicating the presence of ") para.add_run("verotoxin") vt_genes = self.find_verotoxin_genes() if len(vt_genes) == 1: para.add_run(" gene " + vt_genes[0] + ".\n\n") else: para.add_run(" genes ") for i in range(len(vt_genes)): if i == len(vt_genes) - 2: para.add_run(vt_genes[i] + " and ") elif i == len(vt_genes) - 1: para.add_run(vt_genes[i] + ", ") else: para.add_run(vt_genes[i] + ", ") para.add_run("and intimin (") para.add_run("eae").italic = True para.add_run(") genes.\n\n") if len(self.metadata) == 1: para.add_run("Further analyses conducted using databases from the Center For Genomic Epidemiology" " (https://cge.cbs.dtu.dk/services/SerotypeFinder/) predicted the serotype of this isolate to be ") for strain in self.metadata: para.add_run(re.sub(r'\([^)]*\)', '', self.metadata[strain]["serotype"]["O"]) + ":" + re.sub(r'\([^)]*\)', '', self.metadata[strain]["serotype"]["H"]) + ".\n") else: para.add_run("Further analyses conducted using databases from the Center For Genomic Epidemiology" " (https://cge.cbs.dtu.dk/services/SerotypeFinder/) predicted the serotypes of these isolates:\n") for strain in self.metadata: para.add_run("\t\u2022Isolate " + self.metadata[strain]["TextualID"] + " was serotype " + re.sub(r'\([^)]*\)', '', self.metadata[strain]["serotype"]["O"]) + ":" + re.sub(r'\([^)]*\)', '', self.metadata[strain]["serotype"]["H"]) + "\n") para.add_run("\nMultilocus sequence typing (MLST):\n\n").underline = True if len(self.mlstdict) > 1: para.add_run("\u2022 Isolates were sequence types ") i = 1 for st in self.mlstdict: para.add_run("ST-") para.add_run(st) if i == len(self.mlstdict) - 1: para.add_run(" and ") elif i == len(self.mlstdict): para.add_run(".\n") else: para.add_run(", ") i += 1 else: para.add_run("\u2022 All isolates were sequence type ") for st in self.mlstdict: para.add_run("ST-") para.add_run(st + ".\n") for st in self.matching_mlst: if len(self.matching_mlst[st]) > 5: para.add_run("\tIsolates with ST-" + st + " are commonly recovered from the CFIA's food testing" " program (2009-present).\n") elif len(self.matching_mlst[st]) == 1: para.add_run("\tIsolates with ST-" + st + " have not previously been recovered by the CFIA's" " food testing program (2009-present).\n") else: para.add_run("\tIsolates with ST-" + st + " have previously been recovered from the CFIA's food " "testing program (2009-present).\n") para.add_run("\n") para.add_run("Quality Control Analysis:\n").bold = True if "11" not in self.matching_mlst: if len(self.metadata) == 1: para.add_run("\t This isolate does not match CFIA ") else: para.add_run("\t These isolates do not match the ") para.add_run("OLC-795 nalidixic acid-resistant ") para.add_run("E. coli").italic = True para.add_run(" control strain used at the CFIA (ST-11, rST-2119).") else: matches_control = False for strain in self.metadata: if self.metadata[strain]["MLST"] == 11 and self.metadata[strain]["rST"] == 2119: matches_control = True para.add_run("Isolate " + self.metadata[strain]["TextualID"] + " matches") para.add_run(" the OLC-795 nalidixic acid-resistant ") para.add_run("E. coli").italic = True para.add_run(" control strain used at the CFIA (ST-11, rST-2119).") if not matches_control: if len(self.metadata) == 1: para.add_run("\t This isolate does not match CFIA ") else: para.add_run("\t These isolates do not match the ") para.add_run("OLC-795 nalidixic acid-resistant ") para.add_run("E. coli").italic = True para.add_run(" control strain used at the CFIA (ST-11, rST-2119).") doc.save(self.outfile) def print_references(self): import docx from docx.enum.text import WD_ALIGN_PARAGRAPH doc = docx.Document(self.outfile) para = doc.add_paragraph("") para.add_run("\n\nReferences:\n").bold = True para.add_run("\t1. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Yokoyama K, Han CG, Ohtsubo E, " "Nakayama K, <NAME> ") para.add_run("et al:").italic = True para.add_run(" Complete genome sequence of enterohemorrhagic Eshcherichia coli O157:H7 and genomic comparison" " with laboratory strain K-12.").bold = True para.add_run(" DNA Res. 2001; 8(1):11-22\n") para.add_run("\t2. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, et al. ") para.add_run("Phylogenetic and genomic diversity of human bateremic Escherichia coli strains.").bold = True para.add_run(" BMC Genomics. 2008; 9:560.\n") para.add_run("\t3. <NAME>, <NAME>, <NAME>, <NAME>, et al. (2012) ") para.add_run("Ribosomal multilocus sequence typing: universal characterization of bacteria from domain to " "strain.").bold = True para.add_run(" Microbiology. 158:1005-15") para = doc.add_paragraph() para.alignment = WD_ALIGN_PARAGRAPH.CENTER para.add_run("--End Of Report--").bold = True doc.save(self.outfile) def __init__(self, args): self.seq_id_list = args.seq_id_list self.outfile = args.outfile_name self.nasmnt = args.nasmnt self.names = dict() self.metadata = dict() self.matching_mlst = dict() self.parse_metadata() self.get_serotype() self.find_matching_mlst() self.mlstdict = dict() self.mlst_to_dict() self.print_tables_to_docx() self.print_summary_to_docx() self.first_table() self.find_amr() self.add_amr_table() self.print_references() self.change_fonts() # self.add_redmine() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("seq_id_list") parser.add_argument("outfile_name") parser.add_argument("-n", "--nasmnt", type=str, default="/mnt/nas/", help="Where your NAS is mounted. Default is " "/mnt/nas/, trailing slash must be" "included.") arguments = parser.parse_args() x = VTEC_Automator(arguments)
# This is where I'll learn to use python-docx so that ROGAs can get automated. from Automate import Automate class VTEC_Automator(Automate): def get_serotype(self): import csv # Now we need to get the serotype since this is Ecoli. serotype_data = csv.DictReader(open(self.nasmnt + "WGSspades/reports/serotype.csv", encoding="ISO-8859-1")) for row in serotype_data: if row["Strain"] in self.names: serotype = dict() serotype["O"] = row["O-type"] serotype["H"] = row["H-type"] self.metadata[row["Strain"]]["serotype"] = serotype serotype_data = csv.DictReader(open(self.nasmnt + "External_WGSspades/reports/serotype.csv", encoding="ISO-8859-1")) for row in serotype_data: if row["Strain"] in self.names: serotype = dict() serotype["O"] = row["O-type"] serotype["H"] = row["H-type"] self.metadata[row["Strain"]]["serotype"] = serotype # This prints the GeneSeekr Analysis table and the Sequence Data Quality Table to the doc. def print_tables_to_docx(self): import docx doc = docx.Document("vtec_template.docx") j = 2 # GeneSeekr Analysis Table. for name in self.names: # Add a new row to the table for each SEQID to be added. doc.tables[2].add_row() # Input sample names. Automate.add_text_to_cell(self.metadata[name]["TextualID"] + "\n(" "" + self.metadata[name]["IsolateID"] + ")", j, 0, doc.tables[2]) # Input uidA presence/absence if "uidA" in self.metadata[name]["geneSeekr"]: Automate.add_text_to_cell(u"\u2022", j, 1, doc.tables[2]) else: Automate.add_text_to_cell("ND", j, 1, doc.tables[2]) # Input O and H types. Automate.add_text_to_cell(self.metadata[name]["serotype"]["O"].replace("(100.0)", ""), j, 2, doc.tables[2]) Automate.add_text_to_cell(self.metadata[name]["serotype"]["H"].replace("(100.0)", ""), j, 3, doc.tables[2]) # Input the Ecoli specific virulence genes. # This way of doing things is really inflexible and generally not great, but it'll work for now. if "hlyA" in self.metadata[name]["geneSeekr"]: Automate.add_text_to_cell(u"\u2022", j, 4, doc.tables[2]) else: Automate.add_text_to_cell("ND", j, 4, doc.tables[2]) # The following stretch of code is amongst the ugliest stuff you've ever written. # Output eae genes present = False for item in self.metadata[name]["geneSeekr"]: if "eae" in item: Automate.add_text_to_cell(item + ";", j, 5, doc.tables[2], italicize=True) present = True if not present: Automate.add_text_to_cell("ND", j, 5, doc.tables[2]) # Output vt1 genes. present = False for item in self.metadata[name]["geneSeekr"]: if "vt1" in item or "VT1" in item: Automate.add_text_to_cell(item + ";", j, 6, doc.tables[2], italicize=True) present = True if not present: Automate.add_text_to_cell("ND", j, 5, doc.tables[2]) # Output vt2 genes. present = False for item in self.metadata[name]["geneSeekr"]: if "vt2" in item or "VT2" in item: Automate.add_text_to_cell(item + ";", j, 7, doc.tables[2], italicize=True) present = True if not present: Automate.add_text_to_cell("ND", j, 7, doc.tables[2]) # Input MLST types. # Enter the MLST type. Automate.add_text_to_cell(self.metadata[name]["MLST"], j, 9, doc.tables[2]) # Enter the type for each of the seven genes. Again, this code is inflexible and not great, but works. for i in range(10, 17): Automate.add_text_to_cell(self.metadata[name]["mlst_info"][i - 10], j, i, doc.tables[2]) doc.tables[2].cell(j, 8).merge(doc.tables[2].cell(j, 9)) Automate.add_text_to_cell("", j, 9, doc.tables[2]) j += 1 # Sequence Data quality table. j = 1 for name in self.names: # Add a new row to the table for each SEQID to be added. doc.tables[3].add_row() # Input SEQIDS. Automate.add_text_to_cell(self.metadata[name]["TextualID"] + "\n" "(" + self.metadata[name]["IsolateID"] + ")", j, 0, doc.tables[3]) Automate.add_text_to_cell(name, j, 1, doc.tables[3]) doc.tables[3].cell(j, 1).text = name # Input total length. length = int(self.metadata[name]["TotalLength"]) Automate.add_text_to_cell(str(length), j, 2, doc.tables[3]) # Input coverage. cov = float(self.metadata[name]["Coverage"]) covstr = "%.1f" % cov Automate.add_text_to_cell(covstr, j, 3, doc.tables[3]) # Input % Identity GDCS, rST, and Pass/Fail. percent_id = float(self.metadata[name]["Matches"])/53.0 * 100.0 Automate.add_text_to_cell(str(percent_id), j, 4, doc.tables[3]) Automate.add_text_to_cell(self.metadata[name]["rST"], j, 5, doc.tables[3]) if percent_id == 100.0: Automate.add_text_to_cell("Pass", j, 6, doc.tables[3]) else: Automate.add_text_to_cell("Fail", j, 6, doc.tables[3]) # Finally, input pipeline version. Automate.add_text_to_cell(self.metadata[name]["PipelineVersion"], j, 7, doc.tables[3]) j += 1 doc.save(self.outfile) def find_verotoxin_genes(self): verotoxin_genes = list() for strain in self.metadata: for item in self.metadata[strain]["geneSeekr"]: if "VT" in item or "vt" in item: if item not in verotoxin_genes: verotoxin_genes.append(item) return verotoxin_genes # This takes care of printing the SNVPhyl summary to docx. def print_summary_to_docx(self): import docx import re doc = docx.Document(self.outfile) tables = doc.tables # This is going to be long and messy, but I'm not sure of a better way to do it. tables[1].cell(0, 0).text = "" para = tables[1].cell(0, 0).add_paragraph("") para.add_run("Identification Summary:\n\n").bold = True if len(self.names) == 1: para.add_run("Strain " + self.metadata[self.names[0]]["TextualID"]) para.add_run(" was submitted to for whole-genome sequencing and confirmed to be ") else: para.add_run(str(len(self.names)) + " strains (see Table 1)") para.add_run(" were submitted for whole-genome sequencing and confirmed to be ") para.add_run("VTEC") para.add_run(" based on the detection of probe sequences (e-probes) indicating the presence of ") para.add_run("verotoxin") vt_genes = self.find_verotoxin_genes() if len(vt_genes) == 1: para.add_run(" gene " + vt_genes[0] + ".\n\n") else: para.add_run(" genes ") for i in range(len(vt_genes)): if i == len(vt_genes) - 2: para.add_run(vt_genes[i] + " and ") elif i == len(vt_genes) - 1: para.add_run(vt_genes[i] + ", ") else: para.add_run(vt_genes[i] + ", ") para.add_run("and intimin (") para.add_run("eae").italic = True para.add_run(") genes.\n\n") if len(self.metadata) == 1: para.add_run("Further analyses conducted using databases from the Center For Genomic Epidemiology" " (https://cge.cbs.dtu.dk/services/SerotypeFinder/) predicted the serotype of this isolate to be ") for strain in self.metadata: para.add_run(re.sub(r'\([^)]*\)', '', self.metadata[strain]["serotype"]["O"]) + ":" + re.sub(r'\([^)]*\)', '', self.metadata[strain]["serotype"]["H"]) + ".\n") else: para.add_run("Further analyses conducted using databases from the Center For Genomic Epidemiology" " (https://cge.cbs.dtu.dk/services/SerotypeFinder/) predicted the serotypes of these isolates:\n") for strain in self.metadata: para.add_run("\t\u2022Isolate " + self.metadata[strain]["TextualID"] + " was serotype " + re.sub(r'\([^)]*\)', '', self.metadata[strain]["serotype"]["O"]) + ":" + re.sub(r'\([^)]*\)', '', self.metadata[strain]["serotype"]["H"]) + "\n") para.add_run("\nMultilocus sequence typing (MLST):\n\n").underline = True if len(self.mlstdict) > 1: para.add_run("\u2022 Isolates were sequence types ") i = 1 for st in self.mlstdict: para.add_run("ST-") para.add_run(st) if i == len(self.mlstdict) - 1: para.add_run(" and ") elif i == len(self.mlstdict): para.add_run(".\n") else: para.add_run(", ") i += 1 else: para.add_run("\u2022 All isolates were sequence type ") for st in self.mlstdict: para.add_run("ST-") para.add_run(st + ".\n") for st in self.matching_mlst: if len(self.matching_mlst[st]) > 5: para.add_run("\tIsolates with ST-" + st + " are commonly recovered from the CFIA's food testing" " program (2009-present).\n") elif len(self.matching_mlst[st]) == 1: para.add_run("\tIsolates with ST-" + st + " have not previously been recovered by the CFIA's" " food testing program (2009-present).\n") else: para.add_run("\tIsolates with ST-" + st + " have previously been recovered from the CFIA's food " "testing program (2009-present).\n") para.add_run("\n") para.add_run("Quality Control Analysis:\n").bold = True if "11" not in self.matching_mlst: if len(self.metadata) == 1: para.add_run("\t This isolate does not match CFIA ") else: para.add_run("\t These isolates do not match the ") para.add_run("OLC-795 nalidixic acid-resistant ") para.add_run("E. coli").italic = True para.add_run(" control strain used at the CFIA (ST-11, rST-2119).") else: matches_control = False for strain in self.metadata: if self.metadata[strain]["MLST"] == 11 and self.metadata[strain]["rST"] == 2119: matches_control = True para.add_run("Isolate " + self.metadata[strain]["TextualID"] + " matches") para.add_run(" the OLC-795 nalidixic acid-resistant ") para.add_run("E. coli").italic = True para.add_run(" control strain used at the CFIA (ST-11, rST-2119).") if not matches_control: if len(self.metadata) == 1: para.add_run("\t This isolate does not match CFIA ") else: para.add_run("\t These isolates do not match the ") para.add_run("OLC-795 nalidixic acid-resistant ") para.add_run("E. coli").italic = True para.add_run(" control strain used at the CFIA (ST-11, rST-2119).") doc.save(self.outfile) def print_references(self): import docx from docx.enum.text import WD_ALIGN_PARAGRAPH doc = docx.Document(self.outfile) para = doc.add_paragraph("") para.add_run("\n\nReferences:\n").bold = True para.add_run("\t1. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Yokoyama K, Han CG, Ohtsubo E, " "Nakayama K, <NAME> ") para.add_run("et al:").italic = True para.add_run(" Complete genome sequence of enterohemorrhagic Eshcherichia coli O157:H7 and genomic comparison" " with laboratory strain K-12.").bold = True para.add_run(" DNA Res. 2001; 8(1):11-22\n") para.add_run("\t2. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, et al. ") para.add_run("Phylogenetic and genomic diversity of human bateremic Escherichia coli strains.").bold = True para.add_run(" BMC Genomics. 2008; 9:560.\n") para.add_run("\t3. <NAME>, <NAME>, <NAME>, <NAME>, et al. (2012) ") para.add_run("Ribosomal multilocus sequence typing: universal characterization of bacteria from domain to " "strain.").bold = True para.add_run(" Microbiology. 158:1005-15") para = doc.add_paragraph() para.alignment = WD_ALIGN_PARAGRAPH.CENTER para.add_run("--End Of Report--").bold = True doc.save(self.outfile) def __init__(self, args): self.seq_id_list = args.seq_id_list self.outfile = args.outfile_name self.nasmnt = args.nasmnt self.names = dict() self.metadata = dict() self.matching_mlst = dict() self.parse_metadata() self.get_serotype() self.find_matching_mlst() self.mlstdict = dict() self.mlst_to_dict() self.print_tables_to_docx() self.print_summary_to_docx() self.first_table() self.find_amr() self.add_amr_table() self.print_references() self.change_fonts() # self.add_redmine() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("seq_id_list") parser.add_argument("outfile_name") parser.add_argument("-n", "--nasmnt", type=str, default="/mnt/nas/", help="Where your NAS is mounted. Default is " "/mnt/nas/, trailing slash must be" "included.") arguments = parser.parse_args() x = VTEC_Automator(arguments)
en
0.869803
# This is where I'll learn to use python-docx so that ROGAs can get automated. # Now we need to get the serotype since this is Ecoli. # This prints the GeneSeekr Analysis table and the Sequence Data Quality Table to the doc. # GeneSeekr Analysis Table. # Add a new row to the table for each SEQID to be added. # Input sample names. # Input uidA presence/absence # Input O and H types. # Input the Ecoli specific virulence genes. # This way of doing things is really inflexible and generally not great, but it'll work for now. # The following stretch of code is amongst the ugliest stuff you've ever written. # Output eae genes # Output vt1 genes. # Output vt2 genes. # Input MLST types. # Enter the MLST type. # Enter the type for each of the seven genes. Again, this code is inflexible and not great, but works. # Sequence Data quality table. # Add a new row to the table for each SEQID to be added. # Input SEQIDS. # Input total length. # Input coverage. # Input % Identity GDCS, rST, and Pass/Fail. # Finally, input pipeline version. # This takes care of printing the SNVPhyl summary to docx. # This is going to be long and messy, but I'm not sure of a better way to do it. # self.add_redmine()
3.03419
3
GT_forms/form_app/views.py
10K-Linesofcode/Glowing-Tribble
0
6613221
from django.shortcuts import render # Create your views here. from . import forms def index(request): return render(request, 'form_app/index.html') def form_name_view(request): form=forms.FormName() if request.method =='POST': form= forms.FormName(request.POST) if form.is_valid(): # Do Something Code print(" Validation sucecss") print("NAME: "+ form.cleaned_data['name']) print("Email: "+ form.cleaned_data['email']) print("Text: "+ form.cleaned_data['text']) return render (request,'form_app/form_app.html', {'form':form} )
from django.shortcuts import render # Create your views here. from . import forms def index(request): return render(request, 'form_app/index.html') def form_name_view(request): form=forms.FormName() if request.method =='POST': form= forms.FormName(request.POST) if form.is_valid(): # Do Something Code print(" Validation sucecss") print("NAME: "+ form.cleaned_data['name']) print("Email: "+ form.cleaned_data['email']) print("Text: "+ form.cleaned_data['text']) return render (request,'form_app/form_app.html', {'form':form} )
en
0.864551
# Create your views here. # Do Something Code
2.315431
2
src/webserver/api.py
Ibrahim2750mi/WebServer
0
6613222
<filename>src/webserver/api.py from pathlib import Path import warnings class WebServer: def __init__(self, client_connection, htdocs=""): self.client_connection = client_connection index_of_project = str(Path.cwd()).split("/").index("Webserver") self.HTDOCS_DIR = htdocs or '/'.join(str(Path.cwd()).split("/")[0: index_of_project + 1]) self.response = 'HTTP/1.1 200 OK\r\n' def _send_404_error(self, filename: str) -> None: resp = 'HTTP/1.1 404 Not Found\r\nFile Not Found' self.client_connection.sendall(resp.encode()) warnings.warn(f"404 File Not Found: {filename}") def send_406_error(self) -> None: resp = "HTTP/1.1 406 Type not supported\r\n" self.client_connection.send(resp.encode()) warnings.warn("406 Type not supported") def _read_and_respond_media(self, filename: str) -> None: if not Path(f"{self.HTDOCS_DIR}/htdocs{filename}").exists(): self._send_404_error(filename) return with open(f"{self.HTDOCS_DIR}/htdocs{filename}", "rb") as fs: fs_data = fs.read() self.response += f"Content-Type: image/x-icon\r\nContent-Length: {len(fs_data)}\r\n\r\n" self.response = self.response.encode() + fs_data self.client_connection.sendall(self.response) def _read_and_respond_text(self, filename: str) -> None: if not Path(f"{self.HTDOCS_DIR}/htdocs{filename}").exists(): self._send_404_error(filename) return with open(f"{self.HTDOCS_DIR}/htdocs{filename}") as fs: fs_data = fs.read() self.response += f"Content-Length: {len(fs_data)}\r\n\r\n{fs_data}" self.client_connection.sendall(self.response.encode()) def load(self, filename: str, request_type: str ="text") -> None: extension = Path(filename).suffix[1:] if request_type == "image": self.load_img(filename, extension) elif request_type == "text": self.load_text(filename, extension) elif request_type == "audio": self.load_audio(filename, extension) else: self.load_video(filename, extension) def load_img(self, filename: str, extension: str) -> None: if extension == "ico": extension = "x-icon" self.response += f"Content-Type: image/{extension}\r\n" self._read_and_respond_media(filename) def load_text(self, filename: str, extension: str) -> None: if extension == "txt": extension = "plain" self.response += f"Content-Type: text/{extension}\r\n" self._read_and_respond_text(filename) def load_video(self, filename: str, extension: str) -> None: self.response += f"Content-Type: video/{extension}\r\n" self._read_and_respond_media(filename) def load_audio(self, filename: str, extension: str) -> None: if extension == "mp3": extension = "mpeg" self.response += f"Content-Type: audio/{extension}\r\n" self._read_and_respond_media(filename)
<filename>src/webserver/api.py from pathlib import Path import warnings class WebServer: def __init__(self, client_connection, htdocs=""): self.client_connection = client_connection index_of_project = str(Path.cwd()).split("/").index("Webserver") self.HTDOCS_DIR = htdocs or '/'.join(str(Path.cwd()).split("/")[0: index_of_project + 1]) self.response = 'HTTP/1.1 200 OK\r\n' def _send_404_error(self, filename: str) -> None: resp = 'HTTP/1.1 404 Not Found\r\nFile Not Found' self.client_connection.sendall(resp.encode()) warnings.warn(f"404 File Not Found: {filename}") def send_406_error(self) -> None: resp = "HTTP/1.1 406 Type not supported\r\n" self.client_connection.send(resp.encode()) warnings.warn("406 Type not supported") def _read_and_respond_media(self, filename: str) -> None: if not Path(f"{self.HTDOCS_DIR}/htdocs{filename}").exists(): self._send_404_error(filename) return with open(f"{self.HTDOCS_DIR}/htdocs{filename}", "rb") as fs: fs_data = fs.read() self.response += f"Content-Type: image/x-icon\r\nContent-Length: {len(fs_data)}\r\n\r\n" self.response = self.response.encode() + fs_data self.client_connection.sendall(self.response) def _read_and_respond_text(self, filename: str) -> None: if not Path(f"{self.HTDOCS_DIR}/htdocs{filename}").exists(): self._send_404_error(filename) return with open(f"{self.HTDOCS_DIR}/htdocs{filename}") as fs: fs_data = fs.read() self.response += f"Content-Length: {len(fs_data)}\r\n\r\n{fs_data}" self.client_connection.sendall(self.response.encode()) def load(self, filename: str, request_type: str ="text") -> None: extension = Path(filename).suffix[1:] if request_type == "image": self.load_img(filename, extension) elif request_type == "text": self.load_text(filename, extension) elif request_type == "audio": self.load_audio(filename, extension) else: self.load_video(filename, extension) def load_img(self, filename: str, extension: str) -> None: if extension == "ico": extension = "x-icon" self.response += f"Content-Type: image/{extension}\r\n" self._read_and_respond_media(filename) def load_text(self, filename: str, extension: str) -> None: if extension == "txt": extension = "plain" self.response += f"Content-Type: text/{extension}\r\n" self._read_and_respond_text(filename) def load_video(self, filename: str, extension: str) -> None: self.response += f"Content-Type: video/{extension}\r\n" self._read_and_respond_media(filename) def load_audio(self, filename: str, extension: str) -> None: if extension == "mp3": extension = "mpeg" self.response += f"Content-Type: audio/{extension}\r\n" self._read_and_respond_media(filename)
none
1
3.102515
3
UniqueBotsKR/model.py
Paloras/UniqueBotsKR
0
6613223
<gh_stars>0 class UniqueBotsResponse: """.HTTPClient의 모든 반환 데이터에 대한 기본 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. """ def __init__(self, response): self.response = response def __getattr__(self, attr): return self.response.get(attr) def __dict__(self): return self.response class Hearts(UniqueBotsResponse): """.HTTPClient의 디스코드 하트 정보 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. """ def __init__(self, response): super().__init__(response['from']) class Bot(UniqueBotsResponse): """.HTTPClient의 디스코드 봇 정보 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. """ def __init__(self, response): super().__init__(response) class Categories(UniqueBotsResponse): """.HTTPClient의 디스코드 봇 카테고리 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. """ def __init__(self, response): super().__init__(response)
class UniqueBotsResponse: """.HTTPClient의 모든 반환 데이터에 대한 기본 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. """ def __init__(self, response): self.response = response def __getattr__(self, attr): return self.response.get(attr) def __dict__(self): return self.response class Hearts(UniqueBotsResponse): """.HTTPClient의 디스코드 하트 정보 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. """ def __init__(self, response): super().__init__(response['from']) class Bot(UniqueBotsResponse): """.HTTPClient의 디스코드 봇 정보 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. """ def __init__(self, response): super().__init__(response) class Categories(UniqueBotsResponse): """.HTTPClient의 디스코드 봇 카테고리 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. """ def __init__(self, response): super().__init__(response)
ko
0.999894
.HTTPClient의 모든 반환 데이터에 대한 기본 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. .HTTPClient의 디스코드 하트 정보 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. .HTTPClient의 디스코드 봇 정보 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다. .HTTPClient의 디스코드 봇 카테고리 데이터의 모델입니다. Returns ======= response: dict 반환되는 데이터의 dict입니다. attribute attribute의 이름을 입력하면 해당 값을 반환합니다.
2.992417
3
software/firmware/dev_modem.py
andreacorbo/Buoy_Controller_Async_v1
0
6613224
<gh_stars>0 # dev_modem.py # MIT license; Copyright (c) 2020 <NAME> #"Init_Ats":["ATE1\r","ATI\r","AT+CREG=0\r","AT+CSQ\r","AT+CBST=7,0,1\r","AT+COPS=1,2,22201\r","ATS0=1\r","AT&W\r"], import uasyncio as asyncio from primitives.semaphore import Semaphore import time from tools.utils import log, verbose, files_to_send, transmitting from configs import dfl, cfg from device import DEVICE from tools.ymodem import YMODEM class MODEM(DEVICE, YMODEM): def __init__(self): DEVICE.__init__(self) self.sreader = asyncio.StreamReader(self.uart) self.swriter = asyncio.StreamWriter(self.uart, {}) self.data = b'' self.semaphore = Semaphore() # Data/Sms semaphore. self.at_timeout = self.config['Modem']['At_Timeout'] self.init_ats = self.config['Modem']['Init_Ats'] self.init_timeout = self.config['Modem']['Init_Timeout'] self.call_ats = self.config['Modem']['Call_Ats'] self.hangup_ats = self.config['Modem']['Hangup_Ats'] self.at_delay = self.config['Modem']['At_Delay'] self.call_attempt = self.config['Modem']['Call_Attempt'] self.call_delay = self.config['Modem']['Call_Delay'] self.call_timeout = self.config['Modem']['Call_Timeout'] self.ymodem_delay = self.config['Modem']['Ymodem_Delay'] self.keep_alive = self.config['Modem']['Keep_Alive'] self.sms_ats1 = self.config['Modem']['Sms_Ats1'] self.sms_ats2 = self.config['Modem']['Sms_Ats2'] self.sms_timeout = self.config['Modem']['Sms_Timeout'] self.transmitting = transmitting YMODEM.__init__(self, self.agetc, self.aputc) async def startup(self, **kwargs): self.on() self.init_uart() if await self.is_ready(): await self.init() def decode(self): try: return self.data.decode('utf-8') except UnicodeError: log(self.__qualname__, 'communication error') return False # Captures commands replies. async def reply(self): self.data = b'' try: self.data = await asyncio.wait_for(self.sreader.readline(), self.reply_timeout) if self.decode(): return True except asyncio.TimeoutError: log(self.__qualname__, 'no answer') return False # Sends ats commands. async def cmd(self, cmd): await self.swriter.awrite(cmd) while await self.reply(): verbose(self.data) if (self.data.startswith(b'OK') or self.data.startswith(b'ERROR') or self.data.startswith(b'NO CARRIER') or self.data.startswith(b'NO ANSWER') or self.data.startswith(b'NO DIALTONE') or self.data.startswith(b'CONNECT') ): return True await asyncio.sleep_ms(10) return False # Waits for modem getting ready. async def is_ready(self): self.reply_timeout = self.at_timeout t0 = time.time() while time.time() - t0 < self.init_timeout: if await self.cmd('AT\r'): if self.data.startswith(b'OK'): return True await asyncio.sleep_ms(100) log(self.__qualname__, 'not ready') return False # Sends initialisation cmds. async def init(self): self.reply_timeout = self.at_timeout for at in self.init_ats: while True: if await self.cmd(at): if self.data.startswith(b'OK'): break elif self.data.startswith(b'ERROR'): await asyncio.sleep(self.at_delay) continue log(self.__qualname__, 'initialisation failed') return await asyncio.sleep(self.at_delay) log(self.__qualname__, 'successfully initialised') async def agetc(self, size, timeout=1): try: return await asyncio.wait_for(self.sreader.readexactly(size), timeout) except asyncio.TimeoutError: return False # Sends n-bytes. async def aputc(self, data, timeout=1): try: await asyncio.wait_for(self.swriter.awrite(data), timeout) except asyncio.TimeoutError: return 0 return len(data) # Make a call. async def call(self): self.reply_timeout = self.call_timeout # Takes in account the real call timeout. log(self.__qualname__, 'calling...') for at in self.call_ats: if await self.cmd(at): if self.data.startswith(b'CONNECT'): #await self.sreader.read(1) # Clears last byte. return True await asyncio.sleep(self.at_delay) log(self.__qualname__, 'call failed') return False # hangs a call. async def hangup(self): self.reply_timeout = self.at_timeout log(self.__qualname__, 'hangup...') for at in self.hangup_ats: if await self.cmd(at): if self.data.startswith(b'OK'): await asyncio.sleep(self.at_delay) continue log(self.__qualname__, 'hangup failed') return False return True # Tells to remote who it is. async def preamble(self, retry=10, timeout=10): #await asyncio.sleep(2) # Safely waits for remote getting ready. ec = 0 # Error counter. while ec < retry: if await self.aputc(cfg.HOSTNAME.lower()): verbose(cfg.HOSTNAME.lower() +' -->') try: res = await asyncio.wait_for(self.sreader.readexactly(1), timeout) if res == b'\x06': # ACK verbose('<-- ACK') return True else: ec += 1 except asyncio.TimeoutError: ec += 1 await asyncio.sleep(1) return False # Sends and receives data. async def datacall(self): self.transmitting.set(True) async with self.semaphore: self.init_uart() ca = 0 # Attempts counter. for _ in range(self.call_attempt): ca += 1 if await self.call(): if await self.preamble(self.call_attempt, self.at_timeout): # Introduces itself. if await self.asend(files_to_send()): # Puts files. if await self.arecv(): # Gets files. await asyncio.sleep(self.keep_alive) # Awaits user interaction. break #await self.hangup() if ca < self.call_attempt: await asyncio.sleep(self.at_delay) self.uart.deinit() self.off() # Restarts device. await asyncio.sleep(2) self.on() self.transmitting.set(False) # Sends an sms. async def sms(self, text, num): async with self.semaphore: self.transmitting.set(True) self.init_uart() self.reply_timeout = self.at_timeout log(self.__qualname__,'sending sms...') for at in self.sms_ats1: if not await self.cmd(at): log(self.__qualname__,'sms failed', at) self.transmitting.set(False) return False await asyncio.sleep(self.at_delay) await self.swriter.awrite(self.sms_ats2 + num + '\r') try: self.data = await asyncio.wait_for(self.sreader.readline(), self.reply_timeout) except asyncio.TimeoutError: log(self.__qualname__,'sms failed', num) self.transmitting.set(False) return False if self.data.startswith(self.sms_ats2 + num + '\r'): verbose(self.data) try: self.data = await asyncio.wait_for(self.sreader.read(2), self.reply_timeout) except asyncio.TimeoutError: log(self.__qualname__,'sms failed') self.transmitting.set(False) return False if self.data.startswith(b'>'): verbose(self.data) await self.swriter.awrite(text+'\r\n') try: self.data = await asyncio.wait_for(self.sreader.readline(), 60) except asyncio.TimeoutError: log(self.__qualname__,'sms failed') self.transmitting.set(False) return False if self.data.startswith(text): verbose(self.data) if await self.cmd('\x1a'): self.transmitting.set(False) return True log(self.__qualname__,'sms failed') self.transmitting.set(False) return False async def main(self, task='datacall'): if task == 'datacall': await self.datacall()
# dev_modem.py # MIT license; Copyright (c) 2020 <NAME> #"Init_Ats":["ATE1\r","ATI\r","AT+CREG=0\r","AT+CSQ\r","AT+CBST=7,0,1\r","AT+COPS=1,2,22201\r","ATS0=1\r","AT&W\r"], import uasyncio as asyncio from primitives.semaphore import Semaphore import time from tools.utils import log, verbose, files_to_send, transmitting from configs import dfl, cfg from device import DEVICE from tools.ymodem import YMODEM class MODEM(DEVICE, YMODEM): def __init__(self): DEVICE.__init__(self) self.sreader = asyncio.StreamReader(self.uart) self.swriter = asyncio.StreamWriter(self.uart, {}) self.data = b'' self.semaphore = Semaphore() # Data/Sms semaphore. self.at_timeout = self.config['Modem']['At_Timeout'] self.init_ats = self.config['Modem']['Init_Ats'] self.init_timeout = self.config['Modem']['Init_Timeout'] self.call_ats = self.config['Modem']['Call_Ats'] self.hangup_ats = self.config['Modem']['Hangup_Ats'] self.at_delay = self.config['Modem']['At_Delay'] self.call_attempt = self.config['Modem']['Call_Attempt'] self.call_delay = self.config['Modem']['Call_Delay'] self.call_timeout = self.config['Modem']['Call_Timeout'] self.ymodem_delay = self.config['Modem']['Ymodem_Delay'] self.keep_alive = self.config['Modem']['Keep_Alive'] self.sms_ats1 = self.config['Modem']['Sms_Ats1'] self.sms_ats2 = self.config['Modem']['Sms_Ats2'] self.sms_timeout = self.config['Modem']['Sms_Timeout'] self.transmitting = transmitting YMODEM.__init__(self, self.agetc, self.aputc) async def startup(self, **kwargs): self.on() self.init_uart() if await self.is_ready(): await self.init() def decode(self): try: return self.data.decode('utf-8') except UnicodeError: log(self.__qualname__, 'communication error') return False # Captures commands replies. async def reply(self): self.data = b'' try: self.data = await asyncio.wait_for(self.sreader.readline(), self.reply_timeout) if self.decode(): return True except asyncio.TimeoutError: log(self.__qualname__, 'no answer') return False # Sends ats commands. async def cmd(self, cmd): await self.swriter.awrite(cmd) while await self.reply(): verbose(self.data) if (self.data.startswith(b'OK') or self.data.startswith(b'ERROR') or self.data.startswith(b'NO CARRIER') or self.data.startswith(b'NO ANSWER') or self.data.startswith(b'NO DIALTONE') or self.data.startswith(b'CONNECT') ): return True await asyncio.sleep_ms(10) return False # Waits for modem getting ready. async def is_ready(self): self.reply_timeout = self.at_timeout t0 = time.time() while time.time() - t0 < self.init_timeout: if await self.cmd('AT\r'): if self.data.startswith(b'OK'): return True await asyncio.sleep_ms(100) log(self.__qualname__, 'not ready') return False # Sends initialisation cmds. async def init(self): self.reply_timeout = self.at_timeout for at in self.init_ats: while True: if await self.cmd(at): if self.data.startswith(b'OK'): break elif self.data.startswith(b'ERROR'): await asyncio.sleep(self.at_delay) continue log(self.__qualname__, 'initialisation failed') return await asyncio.sleep(self.at_delay) log(self.__qualname__, 'successfully initialised') async def agetc(self, size, timeout=1): try: return await asyncio.wait_for(self.sreader.readexactly(size), timeout) except asyncio.TimeoutError: return False # Sends n-bytes. async def aputc(self, data, timeout=1): try: await asyncio.wait_for(self.swriter.awrite(data), timeout) except asyncio.TimeoutError: return 0 return len(data) # Make a call. async def call(self): self.reply_timeout = self.call_timeout # Takes in account the real call timeout. log(self.__qualname__, 'calling...') for at in self.call_ats: if await self.cmd(at): if self.data.startswith(b'CONNECT'): #await self.sreader.read(1) # Clears last byte. return True await asyncio.sleep(self.at_delay) log(self.__qualname__, 'call failed') return False # hangs a call. async def hangup(self): self.reply_timeout = self.at_timeout log(self.__qualname__, 'hangup...') for at in self.hangup_ats: if await self.cmd(at): if self.data.startswith(b'OK'): await asyncio.sleep(self.at_delay) continue log(self.__qualname__, 'hangup failed') return False return True # Tells to remote who it is. async def preamble(self, retry=10, timeout=10): #await asyncio.sleep(2) # Safely waits for remote getting ready. ec = 0 # Error counter. while ec < retry: if await self.aputc(cfg.HOSTNAME.lower()): verbose(cfg.HOSTNAME.lower() +' -->') try: res = await asyncio.wait_for(self.sreader.readexactly(1), timeout) if res == b'\x06': # ACK verbose('<-- ACK') return True else: ec += 1 except asyncio.TimeoutError: ec += 1 await asyncio.sleep(1) return False # Sends and receives data. async def datacall(self): self.transmitting.set(True) async with self.semaphore: self.init_uart() ca = 0 # Attempts counter. for _ in range(self.call_attempt): ca += 1 if await self.call(): if await self.preamble(self.call_attempt, self.at_timeout): # Introduces itself. if await self.asend(files_to_send()): # Puts files. if await self.arecv(): # Gets files. await asyncio.sleep(self.keep_alive) # Awaits user interaction. break #await self.hangup() if ca < self.call_attempt: await asyncio.sleep(self.at_delay) self.uart.deinit() self.off() # Restarts device. await asyncio.sleep(2) self.on() self.transmitting.set(False) # Sends an sms. async def sms(self, text, num): async with self.semaphore: self.transmitting.set(True) self.init_uart() self.reply_timeout = self.at_timeout log(self.__qualname__,'sending sms...') for at in self.sms_ats1: if not await self.cmd(at): log(self.__qualname__,'sms failed', at) self.transmitting.set(False) return False await asyncio.sleep(self.at_delay) await self.swriter.awrite(self.sms_ats2 + num + '\r') try: self.data = await asyncio.wait_for(self.sreader.readline(), self.reply_timeout) except asyncio.TimeoutError: log(self.__qualname__,'sms failed', num) self.transmitting.set(False) return False if self.data.startswith(self.sms_ats2 + num + '\r'): verbose(self.data) try: self.data = await asyncio.wait_for(self.sreader.read(2), self.reply_timeout) except asyncio.TimeoutError: log(self.__qualname__,'sms failed') self.transmitting.set(False) return False if self.data.startswith(b'>'): verbose(self.data) await self.swriter.awrite(text+'\r\n') try: self.data = await asyncio.wait_for(self.sreader.readline(), 60) except asyncio.TimeoutError: log(self.__qualname__,'sms failed') self.transmitting.set(False) return False if self.data.startswith(text): verbose(self.data) if await self.cmd('\x1a'): self.transmitting.set(False) return True log(self.__qualname__,'sms failed') self.transmitting.set(False) return False async def main(self, task='datacall'): if task == 'datacall': await self.datacall()
en
0.712436
# dev_modem.py # MIT license; Copyright (c) 2020 <NAME> #"Init_Ats":["ATE1\r","ATI\r","AT+CREG=0\r","AT+CSQ\r","AT+CBST=7,0,1\r","AT+COPS=1,2,22201\r","ATS0=1\r","AT&W\r"], # Data/Sms semaphore. # Captures commands replies. # Sends ats commands. # Waits for modem getting ready. # Sends initialisation cmds. # Sends n-bytes. # Make a call. # Takes in account the real call timeout. #await self.sreader.read(1) # Clears last byte. # hangs a call. # Tells to remote who it is. #await asyncio.sleep(2) # Safely waits for remote getting ready. # Error counter. # ACK # Sends and receives data. # Attempts counter. # Introduces itself. # Puts files. # Gets files. # Awaits user interaction. #await self.hangup() # Restarts device. # Sends an sms.
2.161934
2
combine_excel.py
luxutao/mytoy
0
6613225
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ Description: """ import os, re import xlrd import xlwt import time row = 0 path = '/home/luxutao/Desktop/未命名文件夹/' # 读取excel表,存入到temp.txt中,格式为列表形式 def WriteTemp(file): data = xlrd.open_workbook(file).sheet_by_index(0) num = data.nrows for n in range(num): dd = [data.row(n)[i].value for i in range(data.ncols)] if isinstance(dd[0], float): ltime = xlrd.xldate_as_tuple(dd[0], data) dd[0] = time.strftime("%Y/%m/%d", ltime) with open(path + 'temp.txt', 'a') as ff: print(dd, file=ff) return num # 写入数据 def WriteXlsx(rowsl): f = xlwt.Workbook() sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True) with open(path + 'temp.txt') as qq: for col, line in zip(qq, range(rowsl)): search = re.findall(r"\[(.+?)\]", col) listdata = search[0].split(',') replist = [m.strip().replace('\'', '') for m in listdata] for n in range(len(replist)): if replist[n]: sheet1.write(line, n, replist[n]) f.save(path + '合并数据.xlsx') # os.remove(path + 'temp.txt') if __name__ == '__main__': # 循环目录下所有文件 filelist = os.listdir(path) for filename in filelist: rows = WriteTemp(path + filename) row += rows WriteXlsx(row)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ Description: """ import os, re import xlrd import xlwt import time row = 0 path = '/home/luxutao/Desktop/未命名文件夹/' # 读取excel表,存入到temp.txt中,格式为列表形式 def WriteTemp(file): data = xlrd.open_workbook(file).sheet_by_index(0) num = data.nrows for n in range(num): dd = [data.row(n)[i].value for i in range(data.ncols)] if isinstance(dd[0], float): ltime = xlrd.xldate_as_tuple(dd[0], data) dd[0] = time.strftime("%Y/%m/%d", ltime) with open(path + 'temp.txt', 'a') as ff: print(dd, file=ff) return num # 写入数据 def WriteXlsx(rowsl): f = xlwt.Workbook() sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True) with open(path + 'temp.txt') as qq: for col, line in zip(qq, range(rowsl)): search = re.findall(r"\[(.+?)\]", col) listdata = search[0].split(',') replist = [m.strip().replace('\'', '') for m in listdata] for n in range(len(replist)): if replist[n]: sheet1.write(line, n, replist[n]) f.save(path + '合并数据.xlsx') # os.remove(path + 'temp.txt') if __name__ == '__main__': # 循环目录下所有文件 filelist = os.listdir(path) for filename in filelist: rows = WriteTemp(path + filename) row += rows WriteXlsx(row)
zh
0.565639
#!/usr/bin/env python3 # -*- coding:utf-8 -*- Description: # 读取excel表,存入到temp.txt中,格式为列表形式 # 写入数据 # os.remove(path + 'temp.txt') # 循环目录下所有文件
2.957604
3
aioreactive/operators/merge.py
tr11/aioreactive
0
6613226
import asyncio from asyncio.locks import BoundedSemaphore from typing import Dict, TypeVar import logging from aioreactive.core.utils import noopobserver from aioreactive.core import AsyncSingleStream, AsyncDisposable, AsyncCompositeDisposable from aioreactive.core import AsyncObservable, AsyncObserver, chain T = TypeVar('T') log = logging.getLogger(__name__) class Merge(AsyncObservable): def __init__(self, source: AsyncObservable, max_concurrent: int) -> None: self._source = source self.max_concurrent = max_concurrent async def __asubscribe__(self, observer: AsyncObserver) -> AsyncDisposable: log.debug("Merge:__asubscribe__()") sink = Merge.Sink(self, self.max_concurrent) down = await chain(sink, observer) up = await chain(self._source, sink) return AsyncCompositeDisposable(up, down) class Sink(AsyncSingleStream): def __init__(self, source: AsyncObservable, max_concurrent: int) -> None: super().__init__() self._inner_subs = {} # type: Dict[AsyncObserver[T], AsyncSingleStream] self._sem = BoundedSemaphore(max_concurrent) self._is_closed = False async def cancel(self, sub=None) -> None: log.debug("Merge.Sink:adispose()") super().cancel() # Use .values() so that no one modifies the dict while we # cancel the inner streams. for sub in self._inner_subs.values(): if sub is not None: await sub.adispose() self._inner_subs = {} async def asend_core(self, stream: AsyncObservable) -> None: log.debug("Merge.Sink:asend_core(%s)" % stream) inner_stream = Merge.Sink.InnerStream() inner_sub = await chain(inner_stream, self._observer) # type: AsyncDisposable # Allocate entry to make sure no-one closes the merge before # we get to aquire the semaphore. self._inner_subs[inner_sub] = None await self._sem.acquire() def done(sub): self._inner_subs.pop(inner_sub, None) self._sem.release() if self._is_closed and not len(self._inner_subs): asyncio.ensure_future(self._observer.aclose()) inner_stream.add_done_callback(done) sub = self._inner_subs[inner_sub] = await chain(stream, inner_stream) return sub async def aclose_core(self) -> None: log.debug("Merge.Sink:aclose_core()") if len(self._inner_subs): self._is_closed = True return log.debug("Closing merge ...") await self._observer.aclose() class InnerStream(AsyncSingleStream): async def aclose_core(self) -> None: log.debug("Merge.Sink.InnerStream:aclose()") # Unlink observer to avoid forwarding the close. This will # make the inner_stream complete, and the done callback # will take care of any cleanup. self._observer = noopobserver def merge(source: AsyncObservable, max_concurrent: int=42) -> AsyncObservable: """Merges a source stream of source streams. Keyword arguments: source -- source stream to merge. max_concurrent -- Max number of streams to process concurrently. Default value is 42. Setting this to 1 turns merge into concat. Returns flattened source stream. """ return Merge(source, max_concurrent)
import asyncio from asyncio.locks import BoundedSemaphore from typing import Dict, TypeVar import logging from aioreactive.core.utils import noopobserver from aioreactive.core import AsyncSingleStream, AsyncDisposable, AsyncCompositeDisposable from aioreactive.core import AsyncObservable, AsyncObserver, chain T = TypeVar('T') log = logging.getLogger(__name__) class Merge(AsyncObservable): def __init__(self, source: AsyncObservable, max_concurrent: int) -> None: self._source = source self.max_concurrent = max_concurrent async def __asubscribe__(self, observer: AsyncObserver) -> AsyncDisposable: log.debug("Merge:__asubscribe__()") sink = Merge.Sink(self, self.max_concurrent) down = await chain(sink, observer) up = await chain(self._source, sink) return AsyncCompositeDisposable(up, down) class Sink(AsyncSingleStream): def __init__(self, source: AsyncObservable, max_concurrent: int) -> None: super().__init__() self._inner_subs = {} # type: Dict[AsyncObserver[T], AsyncSingleStream] self._sem = BoundedSemaphore(max_concurrent) self._is_closed = False async def cancel(self, sub=None) -> None: log.debug("Merge.Sink:adispose()") super().cancel() # Use .values() so that no one modifies the dict while we # cancel the inner streams. for sub in self._inner_subs.values(): if sub is not None: await sub.adispose() self._inner_subs = {} async def asend_core(self, stream: AsyncObservable) -> None: log.debug("Merge.Sink:asend_core(%s)" % stream) inner_stream = Merge.Sink.InnerStream() inner_sub = await chain(inner_stream, self._observer) # type: AsyncDisposable # Allocate entry to make sure no-one closes the merge before # we get to aquire the semaphore. self._inner_subs[inner_sub] = None await self._sem.acquire() def done(sub): self._inner_subs.pop(inner_sub, None) self._sem.release() if self._is_closed and not len(self._inner_subs): asyncio.ensure_future(self._observer.aclose()) inner_stream.add_done_callback(done) sub = self._inner_subs[inner_sub] = await chain(stream, inner_stream) return sub async def aclose_core(self) -> None: log.debug("Merge.Sink:aclose_core()") if len(self._inner_subs): self._is_closed = True return log.debug("Closing merge ...") await self._observer.aclose() class InnerStream(AsyncSingleStream): async def aclose_core(self) -> None: log.debug("Merge.Sink.InnerStream:aclose()") # Unlink observer to avoid forwarding the close. This will # make the inner_stream complete, and the done callback # will take care of any cleanup. self._observer = noopobserver def merge(source: AsyncObservable, max_concurrent: int=42) -> AsyncObservable: """Merges a source stream of source streams. Keyword arguments: source -- source stream to merge. max_concurrent -- Max number of streams to process concurrently. Default value is 42. Setting this to 1 turns merge into concat. Returns flattened source stream. """ return Merge(source, max_concurrent)
en
0.774439
# type: Dict[AsyncObserver[T], AsyncSingleStream] # Use .values() so that no one modifies the dict while we # cancel the inner streams. # type: AsyncDisposable # Allocate entry to make sure no-one closes the merge before # we get to aquire the semaphore. # Unlink observer to avoid forwarding the close. This will # make the inner_stream complete, and the done callback # will take care of any cleanup. Merges a source stream of source streams. Keyword arguments: source -- source stream to merge. max_concurrent -- Max number of streams to process concurrently. Default value is 42. Setting this to 1 turns merge into concat. Returns flattened source stream.
2.257039
2
deepspeed/ops/adam/__init__.py
ConnollyLeon/DeepSpeed
6,728
6613227
<reponame>ConnollyLeon/DeepSpeed from .cpu_adam import DeepSpeedCPUAdam from .fused_adam import FusedAdam
from .cpu_adam import DeepSpeedCPUAdam from .fused_adam import FusedAdam
none
1
1.047945
1
snbopen.py
ntauch/snbopen
0
6613228
#!/usr/bin/python from zipfile import ZipFile from xml.dom.minidom import parseString from zlib import decompress from PIL import Image from os import system, sep, listdir from sys import argv from reportlab.pdfgen import canvas from io import BytesIO from reportlab.pdfbase.pdfutils import ImageReader from re import sub from tempfile import gettempdir import webbrowser def showUsage(): print """ Usage: snbopen snbfile [pdffile] snbopen opens .snb files created by samsung tablets if pdf file is specified the program converts the snb file to the pdf. """ def zipRead(zipFile, filename): tempFile = zipFile.open(filename) str = tempFile.read() tempFile.close() return str def addImage(snbFile, canvas, image, rels, element): imgFileName = "snote/" + rels[image.getAttribute("r:id")] imgStr = zipRead(snbFile, imgFileName) if imgFileName.endswith(".zdib"): imgStr = decompress(imgStr) width = ord(imgStr[5]) * 256 + ord(imgStr[4]) height = ord(imgStr[9]) * 256 + ord(imgStr[8]) try: img = Image.frombytes("RGBA", (width, height), imgStr[52:]) except: img = Image.fromstring("RGBA", (width, height), imgStr[52:]) canvas.drawInlineImage(alpha_to_color(img), 0, 0, 595.27, 841.89) else: style = imagePoss(element.getElementsByTagName("v:shape")[0].getAttribute("style")) img = Image.open(BytesIO(imgStr)) canvas.drawInlineImage(img, style.left, style.bottom, style.width, style.height) def addText(canvas, element, styles): for run in element.getElementsByTagName("sn:r"): if (len(run.getElementsByTagName("sn:t")) > 0): ##TODO: support italic, bold and underlined text charStyle = styles["Character" + run.getAttributeNode("sn:rStyle").value] text = run.getElementsByTagName("sn:t")[0].firstChild.nodeValue canvas.setFont("Helvetica", charStyle.size) canvas.setFillColor(charStyle.color) canvas.drawString(40, 810 - charStyle.size, text) ##TODO: support non-unicode characters def readRelsFile(snbFile): relations = parseString(zipRead(snbFile, "snote/_rels/snote.xml.rels")) rels = dict() for relation in relations.getElementsByTagName("Relationship"): rels[relation.getAttribute("Id")] = relation.getAttribute("Target") return rels def readCharStyles(snbFile): styles = parseString(zipRead(snbFile, "snote/styles.xml")) charStyles = dict() for style in styles.getElementsByTagName("sn:style"): if style.getAttributeNode("sn:type").value == "character": if len(style.getElementsByTagName("sn:color")) > 0: color = style.getElementsByTagName("sn:color")[0].getAttribute("sn:val") else: color = "000000" if len(style.getElementsByTagName("sn:sz")) > 0: size = int(style.getElementsByTagName("sn:sz")[0].getAttribute("sn:val")) * .5 else: size = 16 charStyles[style.getAttribute("sn:styleId")] = Style(len(style.getElementsByTagName("sn:b")) > 0, len(style.getElementsByTagName("sn:i")) > 0, len(style.getElementsByTagName("sn:u")) > 0, color, size) return charStyles class Style: def __init__(self, bold, italic, underline, color="000000", size=48): self.bold = bold self.italic = italic self.underline = underline self.color = "0X" + color self.size = size class imagePoss: def __init__(self, style): info = sub(r'[A-Za-z\-:]', "", style).split(";") self.left = float(info[2]) self.bottom = 841.89 - (float(info[3]) + float(info[5])) self.width = float(info[4]) self.height = float(info[5]) def alpha_to_color(image, color=(255, 255, 255)): image.load() # needed for split() background = Image.new('RGB', image.size, color) background.paste(image, mask=image.split()[3]) # 3 is the alpha channel return background def snbToPdf(snbname, pdfname=None): snbFile = ZipFile(snbname, "r") rels = readRelsFile(snbFile) charStyles = readCharStyles(snbFile) snote = parseString(zipRead(snbFile, "snote/snote.xml")) bodyElements = snote.firstChild.firstChild.childNodes for element in bodyElements: if element.nodeName == "sn:page": if 'pdfCanvas' in vars(): pdfCanvas.showPage() else: pdfCanvas = canvas.Canvas(pdfname if pdfname else snbname.replace(".snb", ".pdf")) # ussually images elif element.nodeName == "sn:SNoteObj": images = element.getElementsByTagName("v:imagedata") if len(images) != 0: addImage(snbFile, pdfCanvas, images[0], rels, element) else: print "unknown SNoteObj" + "on page " + str(pdfCanvas.getPageNumber()) elif element.nodeName == "sn:l": addText(pdfCanvas, element, charStyles) else: print "unknown element type:" + element.nodeName + " on page " + str(pdfCanvas.getPageNumber()) if (pdfname): pdfCanvas.save() snbFile.close() if len(argv) == 1: # If no arguments are provided, simply convert ALL SNB-files in the current script-directory to PDF for snbFile in listdir("."): if snbFile.endswith(".snb"): snbToPdf(snbFile, snbFile.replace(".snb", ".pdf")) elif len(argv) == 2: pdfFileName = gettempdir() + sep + sub('.*' + sep, "", argv[1]).replace(".snb", ".pdf") snbToPdf(argv[1], pdfFileName) webbrowser.open(pdfFileName) elif len(argv) == 3: snbToPdf(argv[1], argv[2]) else: showUsage()
#!/usr/bin/python from zipfile import ZipFile from xml.dom.minidom import parseString from zlib import decompress from PIL import Image from os import system, sep, listdir from sys import argv from reportlab.pdfgen import canvas from io import BytesIO from reportlab.pdfbase.pdfutils import ImageReader from re import sub from tempfile import gettempdir import webbrowser def showUsage(): print """ Usage: snbopen snbfile [pdffile] snbopen opens .snb files created by samsung tablets if pdf file is specified the program converts the snb file to the pdf. """ def zipRead(zipFile, filename): tempFile = zipFile.open(filename) str = tempFile.read() tempFile.close() return str def addImage(snbFile, canvas, image, rels, element): imgFileName = "snote/" + rels[image.getAttribute("r:id")] imgStr = zipRead(snbFile, imgFileName) if imgFileName.endswith(".zdib"): imgStr = decompress(imgStr) width = ord(imgStr[5]) * 256 + ord(imgStr[4]) height = ord(imgStr[9]) * 256 + ord(imgStr[8]) try: img = Image.frombytes("RGBA", (width, height), imgStr[52:]) except: img = Image.fromstring("RGBA", (width, height), imgStr[52:]) canvas.drawInlineImage(alpha_to_color(img), 0, 0, 595.27, 841.89) else: style = imagePoss(element.getElementsByTagName("v:shape")[0].getAttribute("style")) img = Image.open(BytesIO(imgStr)) canvas.drawInlineImage(img, style.left, style.bottom, style.width, style.height) def addText(canvas, element, styles): for run in element.getElementsByTagName("sn:r"): if (len(run.getElementsByTagName("sn:t")) > 0): ##TODO: support italic, bold and underlined text charStyle = styles["Character" + run.getAttributeNode("sn:rStyle").value] text = run.getElementsByTagName("sn:t")[0].firstChild.nodeValue canvas.setFont("Helvetica", charStyle.size) canvas.setFillColor(charStyle.color) canvas.drawString(40, 810 - charStyle.size, text) ##TODO: support non-unicode characters def readRelsFile(snbFile): relations = parseString(zipRead(snbFile, "snote/_rels/snote.xml.rels")) rels = dict() for relation in relations.getElementsByTagName("Relationship"): rels[relation.getAttribute("Id")] = relation.getAttribute("Target") return rels def readCharStyles(snbFile): styles = parseString(zipRead(snbFile, "snote/styles.xml")) charStyles = dict() for style in styles.getElementsByTagName("sn:style"): if style.getAttributeNode("sn:type").value == "character": if len(style.getElementsByTagName("sn:color")) > 0: color = style.getElementsByTagName("sn:color")[0].getAttribute("sn:val") else: color = "000000" if len(style.getElementsByTagName("sn:sz")) > 0: size = int(style.getElementsByTagName("sn:sz")[0].getAttribute("sn:val")) * .5 else: size = 16 charStyles[style.getAttribute("sn:styleId")] = Style(len(style.getElementsByTagName("sn:b")) > 0, len(style.getElementsByTagName("sn:i")) > 0, len(style.getElementsByTagName("sn:u")) > 0, color, size) return charStyles class Style: def __init__(self, bold, italic, underline, color="000000", size=48): self.bold = bold self.italic = italic self.underline = underline self.color = "0X" + color self.size = size class imagePoss: def __init__(self, style): info = sub(r'[A-Za-z\-:]', "", style).split(";") self.left = float(info[2]) self.bottom = 841.89 - (float(info[3]) + float(info[5])) self.width = float(info[4]) self.height = float(info[5]) def alpha_to_color(image, color=(255, 255, 255)): image.load() # needed for split() background = Image.new('RGB', image.size, color) background.paste(image, mask=image.split()[3]) # 3 is the alpha channel return background def snbToPdf(snbname, pdfname=None): snbFile = ZipFile(snbname, "r") rels = readRelsFile(snbFile) charStyles = readCharStyles(snbFile) snote = parseString(zipRead(snbFile, "snote/snote.xml")) bodyElements = snote.firstChild.firstChild.childNodes for element in bodyElements: if element.nodeName == "sn:page": if 'pdfCanvas' in vars(): pdfCanvas.showPage() else: pdfCanvas = canvas.Canvas(pdfname if pdfname else snbname.replace(".snb", ".pdf")) # ussually images elif element.nodeName == "sn:SNoteObj": images = element.getElementsByTagName("v:imagedata") if len(images) != 0: addImage(snbFile, pdfCanvas, images[0], rels, element) else: print "unknown SNoteObj" + "on page " + str(pdfCanvas.getPageNumber()) elif element.nodeName == "sn:l": addText(pdfCanvas, element, charStyles) else: print "unknown element type:" + element.nodeName + " on page " + str(pdfCanvas.getPageNumber()) if (pdfname): pdfCanvas.save() snbFile.close() if len(argv) == 1: # If no arguments are provided, simply convert ALL SNB-files in the current script-directory to PDF for snbFile in listdir("."): if snbFile.endswith(".snb"): snbToPdf(snbFile, snbFile.replace(".snb", ".pdf")) elif len(argv) == 2: pdfFileName = gettempdir() + sep + sub('.*' + sep, "", argv[1]).replace(".snb", ".pdf") snbToPdf(argv[1], pdfFileName) webbrowser.open(pdfFileName) elif len(argv) == 3: snbToPdf(argv[1], argv[2]) else: showUsage()
en
0.673593
#!/usr/bin/python Usage: snbopen snbfile [pdffile] snbopen opens .snb files created by samsung tablets if pdf file is specified the program converts the snb file to the pdf. ##TODO: support italic, bold and underlined text ##TODO: support non-unicode characters # needed for split() # 3 is the alpha channel # ussually images # If no arguments are provided, simply convert ALL SNB-files in the current script-directory to PDF
2.554685
3
src/hdx/freshness/testdata/serialize.py
OCHA-DAP/hdx-data-freshness
5
6613229
""" Serialize: --------- Serialize datasets and other types """ from collections import OrderedDict from hdx.data.dataset import Dataset from hdx.freshness.testdata.dbtestdataset import DBTestDataset from hdx.freshness.testdata.dbtestdate import DBTestDate from hdx.freshness.testdata.dbtesthashresult import DBTestHashResult from hdx.freshness.testdata.dbtestresource import DBTestResource from hdx.freshness.testdata.dbtestresult import DBTestResult def serialize_datasets(session, datasets): for dataset in datasets: dataset_id = dataset["id"] dbtestdataset = DBTestDataset( id=dataset_id, organization_id=dataset["organization"]["id"], organization_name=dataset["organization"]["name"], organization_title=dataset["organization"]["title"], dataset_name=dataset["name"], dataset_title=dataset["title"], dataset_private=dataset["private"], dataset_maintainer=dataset["maintainer"], dataset_date=dataset.get("dataset_date"), update_frequency=dataset.get("data_update_frequency"), review_date=dataset["review_date"], last_modified=dataset["last_modified"], updated_by_script=dataset.get("updated_by_script"), metadata_modified=dataset["metadata_modified"], is_requestdata_type=dataset.get("is_requestdata_type"), dataset_location=",".join([x["name"] for x in dataset["groups"]]), ) session.add(dbtestdataset) for resource in dataset.get_resources(): dbtestresource = DBTestResource( id=resource["id"], name=resource["name"], dataset_id=dataset_id, format=resource["format"], url=resource["url"], metadata_modified=resource["metadata_modified"], last_modified=resource["last_modified"], ) session.add(dbtestresource) session.commit() def serialize_now(session, now): dbtestdate = DBTestDate(test_date=now) session.add(dbtestdate) session.commit() def serialize_results(session, results): for id in results: url, resource_format, err, http_last_modified, hash, force_hash = results[id] dbtestresult = DBTestResult( id=id, url=url, format=resource_format, err=err, http_last_modified=http_last_modified, hash=hash, force_hash=force_hash, ) session.add(dbtestresult) session.commit() def serialize_hashresults(session, hash_results): for id in hash_results: url, resource_format, err, http_last_modified, hash, force_hash = hash_results[ id ] dbtesthashresult = DBTestHashResult( id=id, url=url, format=resource_format, err=err, http_last_modified=http_last_modified, hash=hash, force_hash=force_hash, ) session.add(dbtesthashresult) session.commit() def deserialize_datasets(session): datasets = OrderedDict() for dbtestdataset in session.query(DBTestDataset): dataset_id = dbtestdataset.id organization = { "id": dbtestdataset.organization_id, "name": dbtestdataset.organization_name, "title": dbtestdataset.organization_title, } dataset = Dataset( { "id": dataset_id, "organization": organization, "name": dbtestdataset.dataset_name, "title": dbtestdataset.dataset_title, "private": dbtestdataset.dataset_private, "maintainer": dbtestdataset.dataset_maintainer, "dataset_date": dbtestdataset.dataset_date, "data_update_frequency": dbtestdataset.update_frequency, "review_date": dbtestdataset.review_date, "last_modified": dbtestdataset.last_modified, "updated_by_script": dbtestdataset.updated_by_script, "metadata_modified": dbtestdataset.metadata_modified, "groups": [ {"name": x} for x in dbtestdataset.dataset_location.split(",") ], } ) dataset.set_requestable(dbtestdataset.is_requestdata_type) datasets[dataset_id] = dataset for dbtestresource in session.query(DBTestResource): dataset = datasets[dbtestresource.dataset_id] resource = { "id": dbtestresource.id, "name": dbtestresource.name, "format": dbtestresource.format, "url": dbtestresource.url, "metadata_modified": dbtestresource.metadata_modified, "last_modified": dbtestresource.last_modified, } dataset.get_resources().append(resource) return datasets.values() def deserialize_now(session): return session.query(DBTestDate.test_date).scalar() def deserialize_results(session): results = dict() for dbtestresult in session.query(DBTestResult): results[dbtestresult.id] = ( dbtestresult.url, dbtestresult.format, dbtestresult.err, dbtestresult.http_last_modified, dbtestresult.hash, ) return results def deserialize_hashresults(session): hash_results = dict() for dbtesthashresult in session.query(DBTestHashResult): hash_results[dbtesthashresult.id] = ( dbtesthashresult.url, dbtesthashresult.format, dbtesthashresult.err, dbtesthashresult.http_last_modified, dbtesthashresult.hash, ) return hash_results
""" Serialize: --------- Serialize datasets and other types """ from collections import OrderedDict from hdx.data.dataset import Dataset from hdx.freshness.testdata.dbtestdataset import DBTestDataset from hdx.freshness.testdata.dbtestdate import DBTestDate from hdx.freshness.testdata.dbtesthashresult import DBTestHashResult from hdx.freshness.testdata.dbtestresource import DBTestResource from hdx.freshness.testdata.dbtestresult import DBTestResult def serialize_datasets(session, datasets): for dataset in datasets: dataset_id = dataset["id"] dbtestdataset = DBTestDataset( id=dataset_id, organization_id=dataset["organization"]["id"], organization_name=dataset["organization"]["name"], organization_title=dataset["organization"]["title"], dataset_name=dataset["name"], dataset_title=dataset["title"], dataset_private=dataset["private"], dataset_maintainer=dataset["maintainer"], dataset_date=dataset.get("dataset_date"), update_frequency=dataset.get("data_update_frequency"), review_date=dataset["review_date"], last_modified=dataset["last_modified"], updated_by_script=dataset.get("updated_by_script"), metadata_modified=dataset["metadata_modified"], is_requestdata_type=dataset.get("is_requestdata_type"), dataset_location=",".join([x["name"] for x in dataset["groups"]]), ) session.add(dbtestdataset) for resource in dataset.get_resources(): dbtestresource = DBTestResource( id=resource["id"], name=resource["name"], dataset_id=dataset_id, format=resource["format"], url=resource["url"], metadata_modified=resource["metadata_modified"], last_modified=resource["last_modified"], ) session.add(dbtestresource) session.commit() def serialize_now(session, now): dbtestdate = DBTestDate(test_date=now) session.add(dbtestdate) session.commit() def serialize_results(session, results): for id in results: url, resource_format, err, http_last_modified, hash, force_hash = results[id] dbtestresult = DBTestResult( id=id, url=url, format=resource_format, err=err, http_last_modified=http_last_modified, hash=hash, force_hash=force_hash, ) session.add(dbtestresult) session.commit() def serialize_hashresults(session, hash_results): for id in hash_results: url, resource_format, err, http_last_modified, hash, force_hash = hash_results[ id ] dbtesthashresult = DBTestHashResult( id=id, url=url, format=resource_format, err=err, http_last_modified=http_last_modified, hash=hash, force_hash=force_hash, ) session.add(dbtesthashresult) session.commit() def deserialize_datasets(session): datasets = OrderedDict() for dbtestdataset in session.query(DBTestDataset): dataset_id = dbtestdataset.id organization = { "id": dbtestdataset.organization_id, "name": dbtestdataset.organization_name, "title": dbtestdataset.organization_title, } dataset = Dataset( { "id": dataset_id, "organization": organization, "name": dbtestdataset.dataset_name, "title": dbtestdataset.dataset_title, "private": dbtestdataset.dataset_private, "maintainer": dbtestdataset.dataset_maintainer, "dataset_date": dbtestdataset.dataset_date, "data_update_frequency": dbtestdataset.update_frequency, "review_date": dbtestdataset.review_date, "last_modified": dbtestdataset.last_modified, "updated_by_script": dbtestdataset.updated_by_script, "metadata_modified": dbtestdataset.metadata_modified, "groups": [ {"name": x} for x in dbtestdataset.dataset_location.split(",") ], } ) dataset.set_requestable(dbtestdataset.is_requestdata_type) datasets[dataset_id] = dataset for dbtestresource in session.query(DBTestResource): dataset = datasets[dbtestresource.dataset_id] resource = { "id": dbtestresource.id, "name": dbtestresource.name, "format": dbtestresource.format, "url": dbtestresource.url, "metadata_modified": dbtestresource.metadata_modified, "last_modified": dbtestresource.last_modified, } dataset.get_resources().append(resource) return datasets.values() def deserialize_now(session): return session.query(DBTestDate.test_date).scalar() def deserialize_results(session): results = dict() for dbtestresult in session.query(DBTestResult): results[dbtestresult.id] = ( dbtestresult.url, dbtestresult.format, dbtestresult.err, dbtestresult.http_last_modified, dbtestresult.hash, ) return results def deserialize_hashresults(session): hash_results = dict() for dbtesthashresult in session.query(DBTestHashResult): hash_results[dbtesthashresult.id] = ( dbtesthashresult.url, dbtesthashresult.format, dbtesthashresult.err, dbtesthashresult.http_last_modified, dbtesthashresult.hash, ) return hash_results
en
0.688754
Serialize: --------- Serialize datasets and other types
2.342993
2
test/test_phones.py
fairwind2k/python_training
0
6613230
<filename>test/test_phones.py import allure from model.contact import Contact import re def test_phones_on_home_page(app): with allure.step('Given a phones list from home page'): contact_from_home_page = app.contacts.get_contacts_list()[0] with allure.step('Given a phones list from edit page'): contact_from_edit_page = app.contacts.get_contact_info_from_edit_page(0) with allure.step('Then the pones list from home page is equal to pones list from edit page'): assert contact_from_home_page.all_phones_from_home_page == merge_phones_like_on_home_page(contact_from_edit_page) def test_phones_on_contact_view_page(app): with allure.step('Given a phones list from view page'): contact_from_view_page = app.contacts.get_contact_from_view_page(0) with allure.step('Given a phones list from edit page'): contact_from_edit_page = app.contacts.get_contact_info_from_edit_page(0) with allure.step('Then the pones list from view page is equal to pones list from edit page'): assert contact_from_view_page.homephone == contact_from_edit_page.homephone assert contact_from_view_page.workphone == contact_from_edit_page.workphone assert contact_from_view_page.mobile == contact_from_edit_page.mobile assert contact_from_view_page.secondaryphone == contact_from_edit_page.secondaryphone def clear(s): return re.sub("[() -]", "", s) def merge_phones_like_on_home_page(contact): return "\n".join(filter(lambda x: x != "", map(lambda x: clear(x), filter(lambda x: x is not None, [contact.homephone, contact.mobile, contact.workphone, contact.secondaryphone]))))
<filename>test/test_phones.py import allure from model.contact import Contact import re def test_phones_on_home_page(app): with allure.step('Given a phones list from home page'): contact_from_home_page = app.contacts.get_contacts_list()[0] with allure.step('Given a phones list from edit page'): contact_from_edit_page = app.contacts.get_contact_info_from_edit_page(0) with allure.step('Then the pones list from home page is equal to pones list from edit page'): assert contact_from_home_page.all_phones_from_home_page == merge_phones_like_on_home_page(contact_from_edit_page) def test_phones_on_contact_view_page(app): with allure.step('Given a phones list from view page'): contact_from_view_page = app.contacts.get_contact_from_view_page(0) with allure.step('Given a phones list from edit page'): contact_from_edit_page = app.contacts.get_contact_info_from_edit_page(0) with allure.step('Then the pones list from view page is equal to pones list from edit page'): assert contact_from_view_page.homephone == contact_from_edit_page.homephone assert contact_from_view_page.workphone == contact_from_edit_page.workphone assert contact_from_view_page.mobile == contact_from_edit_page.mobile assert contact_from_view_page.secondaryphone == contact_from_edit_page.secondaryphone def clear(s): return re.sub("[() -]", "", s) def merge_phones_like_on_home_page(contact): return "\n".join(filter(lambda x: x != "", map(lambda x: clear(x), filter(lambda x: x is not None, [contact.homephone, contact.mobile, contact.workphone, contact.secondaryphone]))))
none
1
2.638917
3
app/tests/order/infra/dao/test_sql_order_summary_dao.py
amazingguni/flask-ddd
1
6613231
from app.order.domain.order import Order from app.order.domain.shipping_info import ShippingInfo, Receiver, Address from app.order.domain.order_state import OrderState def test_select_by_orderer(pre_data_db_session, order_summary_dao): order_summaries = order_summary_dao.select_by_orderer(2) assert len(order_summaries) == 2 summary = order_summaries[0] assert summary.order_id == 2 assert summary.orderer_id == 2 assert summary.orderer_username == '사용자1' assert summary.product_name == '라즈베리파이3 모델B' assert summary.total_amounts == 123920 def test_count_by_filter(pre_data_db_session, order_summary_dao): assert order_summary_dao.counts(None) == 4 assert order_summary_dao.counts({'orderer_id': 2}) == 2 assert order_summary_dao.counts({'orderer_id': 3}) == 1 def test_select_by_filter(pre_data_db_session, order_summary_dao): assert len(order_summary_dao.select(None, 0, 10)) == 4 assert len(order_summary_dao.select({'orderer_id': 2}, 0, 10)) == 2 assert len(order_summary_dao.select({'orderer_id': 3}, 0, 10)) == 1 def test_select_by_filter_limited_test(db_session, order_summary_dao, loginned_user): # Given shipping_info = ShippingInfo( receiver=Receiver('사용자1', '010-1234-5678'), address=Address('123456', '서울시', '관악구'), message='메시지') for _ in range(15): db_session.add(Order( orderer=loginned_user, shipping_info=shipping_info, state=OrderState.PREPARING )) db_session.commit() # When, Then filter = { 'orderer_id': loginned_user.id } assert len(order_summary_dao.select(filter, 0, 10)) == 10 assert len(order_summary_dao.select(filter, 0, 5)) == 5 assert len(order_summary_dao.select(filter, 12, 5)) == 3
from app.order.domain.order import Order from app.order.domain.shipping_info import ShippingInfo, Receiver, Address from app.order.domain.order_state import OrderState def test_select_by_orderer(pre_data_db_session, order_summary_dao): order_summaries = order_summary_dao.select_by_orderer(2) assert len(order_summaries) == 2 summary = order_summaries[0] assert summary.order_id == 2 assert summary.orderer_id == 2 assert summary.orderer_username == '사용자1' assert summary.product_name == '라즈베리파이3 모델B' assert summary.total_amounts == 123920 def test_count_by_filter(pre_data_db_session, order_summary_dao): assert order_summary_dao.counts(None) == 4 assert order_summary_dao.counts({'orderer_id': 2}) == 2 assert order_summary_dao.counts({'orderer_id': 3}) == 1 def test_select_by_filter(pre_data_db_session, order_summary_dao): assert len(order_summary_dao.select(None, 0, 10)) == 4 assert len(order_summary_dao.select({'orderer_id': 2}, 0, 10)) == 2 assert len(order_summary_dao.select({'orderer_id': 3}, 0, 10)) == 1 def test_select_by_filter_limited_test(db_session, order_summary_dao, loginned_user): # Given shipping_info = ShippingInfo( receiver=Receiver('사용자1', '010-1234-5678'), address=Address('123456', '서울시', '관악구'), message='메시지') for _ in range(15): db_session.add(Order( orderer=loginned_user, shipping_info=shipping_info, state=OrderState.PREPARING )) db_session.commit() # When, Then filter = { 'orderer_id': loginned_user.id } assert len(order_summary_dao.select(filter, 0, 10)) == 10 assert len(order_summary_dao.select(filter, 0, 5)) == 5 assert len(order_summary_dao.select(filter, 12, 5)) == 3
en
0.355948
# Given # When, Then
2.238847
2
nekoyume/battle/__init__.py
earlbread/nekoyume
70
6613232
<reponame>earlbread/nekoyume<filename>nekoyume/battle/__init__.py class WeightedList: def __init__(self): self.values_ = [] self.weights_ = [] def __len__(self): return len(self.values_) def __str__(self): return str((self.values_, self.weights_)) def add(self, value, weight): self.values_.append(value) self.weights_.append(weight) def select(self, random, pop=False): if not self.values_: return None weight_sum = 0 for i in self.weights_: weight_sum += i rnd = random.randint(0, weight_sum - 1) idx = -1 for i in range(len(self.values_)): if rnd < self.weights_[i]: idx = i break rnd -= self.weights_[i] if idx < 0: return None ret = self.values_[idx] if pop: del self.values_[i] del self.weights_[i] return ret def pop(self, random): return self.select(random, True)
class WeightedList: def __init__(self): self.values_ = [] self.weights_ = [] def __len__(self): return len(self.values_) def __str__(self): return str((self.values_, self.weights_)) def add(self, value, weight): self.values_.append(value) self.weights_.append(weight) def select(self, random, pop=False): if not self.values_: return None weight_sum = 0 for i in self.weights_: weight_sum += i rnd = random.randint(0, weight_sum - 1) idx = -1 for i in range(len(self.values_)): if rnd < self.weights_[i]: idx = i break rnd -= self.weights_[i] if idx < 0: return None ret = self.values_[idx] if pop: del self.values_[i] del self.weights_[i] return ret def pop(self, random): return self.select(random, True)
none
1
3.169541
3
koapy/cli/commands/generate/__init__.py
webclinic017/koapy
0
6613233
import click from .grpc import grpc from .openapi import openapi @click.group(short_help="Generate files related to grpc, openapi.") def generate(): pass generate.add_command(grpc) generate.add_command(openapi)
import click from .grpc import grpc from .openapi import openapi @click.group(short_help="Generate files related to grpc, openapi.") def generate(): pass generate.add_command(grpc) generate.add_command(openapi)
none
1
1.693834
2
abstractions/python/kiota/abstractions/serialization/serialization_writer.py
jasonjoh/kiota
0
6613234
<filename>abstractions/python/kiota/abstractions/serialization/serialization_writer.py from __future__ import annotations from abc import ABC, abstractmethod from datetime import date, datetime, time, timedelta from enum import Enum from io import BytesIO from typing import Any, Callable, Dict, List, Optional, TypeVar from uuid import UUID from .parsable import Parsable T = TypeVar("T") U = TypeVar("U", bound=Parsable) class SerializationWriter(ABC): """Defines an interface for serialization of objects to a stream """ @abstractmethod def write_string_value(self, key: Optional[str], value: Optional[str]) -> None: """Writes the specified string value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[str]): The string value to be written. """ pass @abstractmethod def write_boolean_value(self, key: Optional[str], value: Optional[bool]) -> None: """Writes the specified boolean value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[bool]): The boolean value to be written. """ pass @abstractmethod def write_int_value(self, key: Optional[str], value: Optional[int]) -> None: """Writes the specified integer value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[int]): The integer value to be written. """ pass @abstractmethod def write_float_value(self, key: Optional[str], value: Optional[float]) -> None: """Writes the specified float value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[float]): The float value to be written. """ pass @abstractmethod def write_uuid_value(self, key: Optional[str], value: Optional[UUID]) -> None: """Writes the specified uuid value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[UUId]): The uuid value to be written. """ pass @abstractmethod def write_datetime_offset_value(self, key: Optional[str], value: Optional[datetime]) -> None: """Writes the specified datetime offset value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[datetime]): The datetime offset value to be written. """ pass @abstractmethod def write_timedelta_value(self, key: Optional[str], value: Optional[timedelta]) -> None: """Writes the specified timedelta value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[timedelta]): The timedelta value to be written. """ pass @abstractmethod def write_date_value(self, key: Optional[str], value: Optional[date]) -> None: """Writes the specified date value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[date]): The date value to be written. """ pass @abstractmethod def write_time_value(self, key: Optional[str], value: Optional[time]) -> None: """Writes the specified time value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[time]): The time value to be written. """ pass @abstractmethod def write_collection_of_primitive_values( self, key: Optional[str], values: Optional[List[T]] ) -> None: """Writes the specified collection of primitive values to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values (Optional[List[T]]): The collection of primitive values to be written. """ pass @abstractmethod def write_collection_of_object_values( self, key: Optional[str], values: Optional[List[U]] ) -> None: """Writes the specified collection of model objects to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values (Optional[List[U]]): The collection of model objects to be written. """ pass @abstractmethod def write_collection_of_enum_values( self, key: Optional[str], values: Optional[List[Enum]] ) -> None: """Writes the specified collection of enum values to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values Optional[List[Enum]): The enum values to be written. """ pass @abstractmethod def write_bytearray_value(self, key: Optional[str], value: BytesIO) -> None: """Writes the specified byte array as a base64 string to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (BytesIO): The byte array to be written. """ pass @abstractmethod def write_object_value(self, key: Optional[str], value: U) -> None: """Writes the specified model object to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Parsable): The model object to be written. """ pass @abstractmethod def write_enum_value(self, key: Optional[str], value: Optional[Enum]) -> None: """Writes the specified enum value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[Enum]): The enum value to be written. """ pass @abstractmethod def write_null_value(self, key: Optional[str]) -> None: """Writes a null value for the specified key. Args: key (Optional[str]): The key to be used for the written value. May be null. """ pass @abstractmethod def write_additional_data_value(self, value: Dict[str, Any]) -> None: """Writes the specified additional data to the stream. Args: value (Dict[str, Any]): he additional data to be written. """ pass @abstractmethod def get_serialized_content(self) -> BytesIO: """Gets the value of the serialized content. Returns: BytesIO: The value of the serialized content. """ pass @abstractmethod def get_on_before_object_serialization(self) -> Optional[Callable[[Parsable], None]]: """Gets the callback called before the object gets serialized. Returns: Optional[Callable[[Parsable], None]]:the callback called before the object gets serialized. """ pass @abstractmethod def get_on_after_object_serialization(self) -> Optional[Callable[[Parsable], None]]: """Gets the callback called after the object gets serialized. Returns: Optional[Optional[Callable[[Parsable], None]]]: the callback called after the object gets serialized. """ pass @abstractmethod def get_on_start_object_serialization( self ) -> Optional[Callable[[Parsable, SerializationWriter], None]]: """Gets the callback called right after the serialization process starts. Returns: Optional[Callable[[Parsable, SerializationWriter], None]]: the callback called right after the serialization process starts. """ pass @abstractmethod def set_on_before_object_serialization( self, value: Optional[Callable[[Parsable], None]] ) -> None: """Sets the callback called before the objects gets serialized. Args: value (Optional[Callable[[Parsable], None]]): the callback called before the objects gets serialized. """ pass @abstractmethod def set_on_after_object_serialization( self, value: Optional[Callable[[Parsable], None]] ) -> None: """Sets the callback called after the objects gets serialized. Args: value (Optional[Callable[[Parsable], None]]): the callback called after the objects gets serialized. """ pass @abstractmethod def set_on_start_object_serialization( self, value: Optional[Callable[[Parsable, SerializationWriter], None]] ) -> None: """Sets the callback called right after the serialization process starts. Args: value (Optional[Callable[[Parsable, SerializationWriter], None]]): the callback called right after the serialization process starts. """ pass
<filename>abstractions/python/kiota/abstractions/serialization/serialization_writer.py from __future__ import annotations from abc import ABC, abstractmethod from datetime import date, datetime, time, timedelta from enum import Enum from io import BytesIO from typing import Any, Callable, Dict, List, Optional, TypeVar from uuid import UUID from .parsable import Parsable T = TypeVar("T") U = TypeVar("U", bound=Parsable) class SerializationWriter(ABC): """Defines an interface for serialization of objects to a stream """ @abstractmethod def write_string_value(self, key: Optional[str], value: Optional[str]) -> None: """Writes the specified string value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[str]): The string value to be written. """ pass @abstractmethod def write_boolean_value(self, key: Optional[str], value: Optional[bool]) -> None: """Writes the specified boolean value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[bool]): The boolean value to be written. """ pass @abstractmethod def write_int_value(self, key: Optional[str], value: Optional[int]) -> None: """Writes the specified integer value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[int]): The integer value to be written. """ pass @abstractmethod def write_float_value(self, key: Optional[str], value: Optional[float]) -> None: """Writes the specified float value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[float]): The float value to be written. """ pass @abstractmethod def write_uuid_value(self, key: Optional[str], value: Optional[UUID]) -> None: """Writes the specified uuid value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[UUId]): The uuid value to be written. """ pass @abstractmethod def write_datetime_offset_value(self, key: Optional[str], value: Optional[datetime]) -> None: """Writes the specified datetime offset value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[datetime]): The datetime offset value to be written. """ pass @abstractmethod def write_timedelta_value(self, key: Optional[str], value: Optional[timedelta]) -> None: """Writes the specified timedelta value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[timedelta]): The timedelta value to be written. """ pass @abstractmethod def write_date_value(self, key: Optional[str], value: Optional[date]) -> None: """Writes the specified date value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[date]): The date value to be written. """ pass @abstractmethod def write_time_value(self, key: Optional[str], value: Optional[time]) -> None: """Writes the specified time value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[time]): The time value to be written. """ pass @abstractmethod def write_collection_of_primitive_values( self, key: Optional[str], values: Optional[List[T]] ) -> None: """Writes the specified collection of primitive values to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values (Optional[List[T]]): The collection of primitive values to be written. """ pass @abstractmethod def write_collection_of_object_values( self, key: Optional[str], values: Optional[List[U]] ) -> None: """Writes the specified collection of model objects to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values (Optional[List[U]]): The collection of model objects to be written. """ pass @abstractmethod def write_collection_of_enum_values( self, key: Optional[str], values: Optional[List[Enum]] ) -> None: """Writes the specified collection of enum values to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values Optional[List[Enum]): The enum values to be written. """ pass @abstractmethod def write_bytearray_value(self, key: Optional[str], value: BytesIO) -> None: """Writes the specified byte array as a base64 string to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (BytesIO): The byte array to be written. """ pass @abstractmethod def write_object_value(self, key: Optional[str], value: U) -> None: """Writes the specified model object to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Parsable): The model object to be written. """ pass @abstractmethod def write_enum_value(self, key: Optional[str], value: Optional[Enum]) -> None: """Writes the specified enum value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[Enum]): The enum value to be written. """ pass @abstractmethod def write_null_value(self, key: Optional[str]) -> None: """Writes a null value for the specified key. Args: key (Optional[str]): The key to be used for the written value. May be null. """ pass @abstractmethod def write_additional_data_value(self, value: Dict[str, Any]) -> None: """Writes the specified additional data to the stream. Args: value (Dict[str, Any]): he additional data to be written. """ pass @abstractmethod def get_serialized_content(self) -> BytesIO: """Gets the value of the serialized content. Returns: BytesIO: The value of the serialized content. """ pass @abstractmethod def get_on_before_object_serialization(self) -> Optional[Callable[[Parsable], None]]: """Gets the callback called before the object gets serialized. Returns: Optional[Callable[[Parsable], None]]:the callback called before the object gets serialized. """ pass @abstractmethod def get_on_after_object_serialization(self) -> Optional[Callable[[Parsable], None]]: """Gets the callback called after the object gets serialized. Returns: Optional[Optional[Callable[[Parsable], None]]]: the callback called after the object gets serialized. """ pass @abstractmethod def get_on_start_object_serialization( self ) -> Optional[Callable[[Parsable, SerializationWriter], None]]: """Gets the callback called right after the serialization process starts. Returns: Optional[Callable[[Parsable, SerializationWriter], None]]: the callback called right after the serialization process starts. """ pass @abstractmethod def set_on_before_object_serialization( self, value: Optional[Callable[[Parsable], None]] ) -> None: """Sets the callback called before the objects gets serialized. Args: value (Optional[Callable[[Parsable], None]]): the callback called before the objects gets serialized. """ pass @abstractmethod def set_on_after_object_serialization( self, value: Optional[Callable[[Parsable], None]] ) -> None: """Sets the callback called after the objects gets serialized. Args: value (Optional[Callable[[Parsable], None]]): the callback called after the objects gets serialized. """ pass @abstractmethod def set_on_start_object_serialization( self, value: Optional[Callable[[Parsable, SerializationWriter], None]] ) -> None: """Sets the callback called right after the serialization process starts. Args: value (Optional[Callable[[Parsable, SerializationWriter], None]]): the callback called right after the serialization process starts. """ pass
en
0.64939
Defines an interface for serialization of objects to a stream Writes the specified string value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[str]): The string value to be written. Writes the specified boolean value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[bool]): The boolean value to be written. Writes the specified integer value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[int]): The integer value to be written. Writes the specified float value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[float]): The float value to be written. Writes the specified uuid value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[UUId]): The uuid value to be written. Writes the specified datetime offset value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[datetime]): The datetime offset value to be written. Writes the specified timedelta value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[timedelta]): The timedelta value to be written. Writes the specified date value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[date]): The date value to be written. Writes the specified time value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[time]): The time value to be written. Writes the specified collection of primitive values to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values (Optional[List[T]]): The collection of primitive values to be written. Writes the specified collection of model objects to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values (Optional[List[U]]): The collection of model objects to be written. Writes the specified collection of enum values to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. values Optional[List[Enum]): The enum values to be written. Writes the specified byte array as a base64 string to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (BytesIO): The byte array to be written. Writes the specified model object to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Parsable): The model object to be written. Writes the specified enum value to the stream with an optional given key. Args: key (Optional[str]): The key to be used for the written value. May be null. value (Optional[Enum]): The enum value to be written. Writes a null value for the specified key. Args: key (Optional[str]): The key to be used for the written value. May be null. Writes the specified additional data to the stream. Args: value (Dict[str, Any]): he additional data to be written. Gets the value of the serialized content. Returns: BytesIO: The value of the serialized content. Gets the callback called before the object gets serialized. Returns: Optional[Callable[[Parsable], None]]:the callback called before the object gets serialized. Gets the callback called after the object gets serialized. Returns: Optional[Optional[Callable[[Parsable], None]]]: the callback called after the object gets serialized. Gets the callback called right after the serialization process starts. Returns: Optional[Callable[[Parsable, SerializationWriter], None]]: the callback called right after the serialization process starts. Sets the callback called before the objects gets serialized. Args: value (Optional[Callable[[Parsable], None]]): the callback called before the objects gets serialized. Sets the callback called after the objects gets serialized. Args: value (Optional[Callable[[Parsable], None]]): the callback called after the objects gets serialized. Sets the callback called right after the serialization process starts. Args: value (Optional[Callable[[Parsable, SerializationWriter], None]]): the callback called right after the serialization process starts.
3.050992
3
bin/Python27/Lib/site-packages/omniORBpy-4.2.0/lib/python/omniORB/COS/CosPersistencePDS_DA_idl.py
lefevre-fraser/openmeta-mms
0
6613235
# Python stubs generated by omniidl from ..\..\..\..\..\idl\COS\CosPersistencePDS_DA.idl # DO NOT EDIT THIS FILE! import omniORB, _omnipy from omniORB import CORBA, PortableServer _0_CORBA = CORBA _omnipy.checkVersion(4,2, __file__, 1) try: property except NameError: def property(*args): return None # #include "CosPersistencePID.idl" import CosPersistencePID_idl _0_CosPersistencePID = omniORB.openModule("CosPersistencePID") _0_CosPersistencePID__POA = omniORB.openModule("CosPersistencePID__POA") # #include "CosPersistencePDS.idl" import CosPersistencePDS_idl _0_CosPersistencePDS = omniORB.openModule("CosPersistencePDS") _0_CosPersistencePDS__POA = omniORB.openModule("CosPersistencePDS__POA") # # Start of module "CosPersistencePDS_DA" # __name__ = "CosPersistencePDS_DA" _0_CosPersistencePDS_DA = omniORB.openModule("CosPersistencePDS_DA", r"..\..\..\..\..\idl\COS\CosPersistencePDS_DA.idl") _0_CosPersistencePDS_DA__POA = omniORB.openModule("CosPersistencePDS_DA__POA", r"..\..\..\..\..\idl\COS\CosPersistencePDS_DA.idl") # typedef ... DAObjectID class DAObjectID: _NP_RepositoryId = "IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0" def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _0_CosPersistencePDS_DA.DAObjectID = DAObjectID _0_CosPersistencePDS_DA._d_DAObjectID = (omniORB.tcInternal.tv_string,0) _0_CosPersistencePDS_DA._ad_DAObjectID = (omniORB.tcInternal.tv_alias, DAObjectID._NP_RepositoryId, "DAObjectID", (omniORB.tcInternal.tv_string,0)) _0_CosPersistencePDS_DA._tc_DAObjectID = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._ad_DAObjectID) omniORB.registerType(DAObjectID._NP_RepositoryId, _0_CosPersistencePDS_DA._ad_DAObjectID, _0_CosPersistencePDS_DA._tc_DAObjectID) del DAObjectID # interface PID_DA _0_CosPersistencePDS_DA._d_PID_DA = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0", "PID_DA") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0"] = _0_CosPersistencePDS_DA._d_PID_DA _0_CosPersistencePDS_DA.PID_DA = omniORB.newEmptyClass() class PID_DA (_0_CosPersistencePID.PID): _NP_RepositoryId = _0_CosPersistencePDS_DA._d_PID_DA[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.PID_DA = PID_DA _0_CosPersistencePDS_DA._tc_PID_DA = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_PID_DA) omniORB.registerType(PID_DA._NP_RepositoryId, _0_CosPersistencePDS_DA._d_PID_DA, _0_CosPersistencePDS_DA._tc_PID_DA) # PID_DA operations and attributes PID_DA._d__get_oid = ((),(omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0"],),None) PID_DA._d__set_oid = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0"],),(),None) # PID_DA object reference class _objref_PID_DA (_0_CosPersistencePID._objref_PID): _NP_RepositoryId = PID_DA._NP_RepositoryId def __init__(self, obj): _0_CosPersistencePID._objref_PID.__init__(self, obj) def _get_oid(self, *args): return self._obj.invoke("_get_oid", _0_CosPersistencePDS_DA.PID_DA._d__get_oid, args) def _set_oid(self, *args): return self._obj.invoke("_set_oid", _0_CosPersistencePDS_DA.PID_DA._d__set_oid, args) oid = property(_get_oid, _set_oid) omniORB.registerObjref(PID_DA._NP_RepositoryId, _objref_PID_DA) _0_CosPersistencePDS_DA._objref_PID_DA = _objref_PID_DA del PID_DA, _objref_PID_DA # PID_DA skeleton __name__ = "CosPersistencePDS_DA__POA" class PID_DA (_0_CosPersistencePID__POA.PID): _NP_RepositoryId = _0_CosPersistencePDS_DA.PID_DA._NP_RepositoryId _omni_op_d = {"_get_oid": _0_CosPersistencePDS_DA.PID_DA._d__get_oid, "_set_oid": _0_CosPersistencePDS_DA.PID_DA._d__set_oid} _omni_op_d.update(_0_CosPersistencePID__POA.PID._omni_op_d) PID_DA._omni_skeleton = PID_DA _0_CosPersistencePDS_DA__POA.PID_DA = PID_DA omniORB.registerSkeleton(PID_DA._NP_RepositoryId, PID_DA) del PID_DA __name__ = "CosPersistencePDS_DA" # interface DAObject _0_CosPersistencePDS_DA._d_DAObject = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0", "DAObject") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"] = _0_CosPersistencePDS_DA._d_DAObject _0_CosPersistencePDS_DA.DAObject = omniORB.newEmptyClass() class DAObject : _NP_RepositoryId = _0_CosPersistencePDS_DA._d_DAObject[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.DAObject = DAObject _0_CosPersistencePDS_DA._tc_DAObject = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_DAObject) omniORB.registerType(DAObject._NP_RepositoryId, _0_CosPersistencePDS_DA._d_DAObject, _0_CosPersistencePDS_DA._tc_DAObject) # DAObject operations and attributes DAObject._d_dado_same = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), (omniORB.tcInternal.tv_boolean, ), None) DAObject._d_dado_oid = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0"], ), None) DAObject._d_dado_pid = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0"], ), None) DAObject._d_dado_remove = ((), (), None) DAObject._d_dado_free = ((), (), None) # DAObject object reference class _objref_DAObject (CORBA.Object): _NP_RepositoryId = DAObject._NP_RepositoryId def __init__(self, obj): CORBA.Object.__init__(self, obj) def dado_same(self, *args): return self._obj.invoke("dado_same", _0_CosPersistencePDS_DA.DAObject._d_dado_same, args) def dado_oid(self, *args): return self._obj.invoke("dado_oid", _0_CosPersistencePDS_DA.DAObject._d_dado_oid, args) def dado_pid(self, *args): return self._obj.invoke("dado_pid", _0_CosPersistencePDS_DA.DAObject._d_dado_pid, args) def dado_remove(self, *args): return self._obj.invoke("dado_remove", _0_CosPersistencePDS_DA.DAObject._d_dado_remove, args) def dado_free(self, *args): return self._obj.invoke("dado_free", _0_CosPersistencePDS_DA.DAObject._d_dado_free, args) omniORB.registerObjref(DAObject._NP_RepositoryId, _objref_DAObject) _0_CosPersistencePDS_DA._objref_DAObject = _objref_DAObject del DAObject, _objref_DAObject # DAObject skeleton __name__ = "CosPersistencePDS_DA__POA" class DAObject (PortableServer.Servant): _NP_RepositoryId = _0_CosPersistencePDS_DA.DAObject._NP_RepositoryId _omni_op_d = {"dado_same": _0_CosPersistencePDS_DA.DAObject._d_dado_same, "dado_oid": _0_CosPersistencePDS_DA.DAObject._d_dado_oid, "dado_pid": _0_CosPersistencePDS_DA.DAObject._d_dado_pid, "dado_remove": _0_CosPersistencePDS_DA.DAObject._d_dado_remove, "dado_free": _0_CosPersistencePDS_DA.DAObject._d_dado_free} DAObject._omni_skeleton = DAObject _0_CosPersistencePDS_DA__POA.DAObject = DAObject omniORB.registerSkeleton(DAObject._NP_RepositoryId, DAObject) del DAObject __name__ = "CosPersistencePDS_DA" # interface DAObjectFactory _0_CosPersistencePDS_DA._d_DAObjectFactory = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/DAObjectFactory:1.0", "DAObjectFactory") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectFactory:1.0"] = _0_CosPersistencePDS_DA._d_DAObjectFactory _0_CosPersistencePDS_DA.DAObjectFactory = omniORB.newEmptyClass() class DAObjectFactory : _NP_RepositoryId = _0_CosPersistencePDS_DA._d_DAObjectFactory[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.DAObjectFactory = DAObjectFactory _0_CosPersistencePDS_DA._tc_DAObjectFactory = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_DAObjectFactory) omniORB.registerType(DAObjectFactory._NP_RepositoryId, _0_CosPersistencePDS_DA._d_DAObjectFactory, _0_CosPersistencePDS_DA._tc_DAObjectFactory) # DAObjectFactory operations and attributes DAObjectFactory._d_create = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), None) # DAObjectFactory object reference class _objref_DAObjectFactory (CORBA.Object): _NP_RepositoryId = DAObjectFactory._NP_RepositoryId def __init__(self, obj): CORBA.Object.__init__(self, obj) def create(self, *args): return self._obj.invoke("create", _0_CosPersistencePDS_DA.DAObjectFactory._d_create, args) omniORB.registerObjref(DAObjectFactory._NP_RepositoryId, _objref_DAObjectFactory) _0_CosPersistencePDS_DA._objref_DAObjectFactory = _objref_DAObjectFactory del DAObjectFactory, _objref_DAObjectFactory # DAObjectFactory skeleton __name__ = "CosPersistencePDS_DA__POA" class DAObjectFactory (PortableServer.Servant): _NP_RepositoryId = _0_CosPersistencePDS_DA.DAObjectFactory._NP_RepositoryId _omni_op_d = {"create": _0_CosPersistencePDS_DA.DAObjectFactory._d_create} DAObjectFactory._omni_skeleton = DAObjectFactory _0_CosPersistencePDS_DA__POA.DAObjectFactory = DAObjectFactory omniORB.registerSkeleton(DAObjectFactory._NP_RepositoryId, DAObjectFactory) del DAObjectFactory __name__ = "CosPersistencePDS_DA" # interface DAObjectFactoryFinder _0_CosPersistencePDS_DA._d_DAObjectFactoryFinder = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/DAObjectFactoryFinder:1.0", "DAObjectFactoryFinder") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectFactoryFinder:1.0"] = _0_CosPersistencePDS_DA._d_DAObjectFactoryFinder _0_CosPersistencePDS_DA.DAObjectFactoryFinder = omniORB.newEmptyClass() class DAObjectFactoryFinder : _NP_RepositoryId = _0_CosPersistencePDS_DA._d_DAObjectFactoryFinder[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.DAObjectFactoryFinder = DAObjectFactoryFinder _0_CosPersistencePDS_DA._tc_DAObjectFactoryFinder = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_DAObjectFactoryFinder) omniORB.registerType(DAObjectFactoryFinder._NP_RepositoryId, _0_CosPersistencePDS_DA._d_DAObjectFactoryFinder, _0_CosPersistencePDS_DA._tc_DAObjectFactoryFinder) # DAObjectFactoryFinder operations and attributes DAObjectFactoryFinder._d_find_factory = (((omniORB.tcInternal.tv_string,0), ), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectFactory:1.0"], ), None) # DAObjectFactoryFinder object reference class _objref_DAObjectFactoryFinder (CORBA.Object): _NP_RepositoryId = DAObjectFactoryFinder._NP_RepositoryId def __init__(self, obj): CORBA.Object.__init__(self, obj) def find_factory(self, *args): return self._obj.invoke("find_factory", _0_CosPersistencePDS_DA.DAObjectFactoryFinder._d_find_factory, args) omniORB.registerObjref(DAObjectFactoryFinder._NP_RepositoryId, _objref_DAObjectFactoryFinder) _0_CosPersistencePDS_DA._objref_DAObjectFactoryFinder = _objref_DAObjectFactoryFinder del DAObjectFactoryFinder, _objref_DAObjectFactoryFinder # DAObjectFactoryFinder skeleton __name__ = "CosPersistencePDS_DA__POA" class DAObjectFactoryFinder (PortableServer.Servant): _NP_RepositoryId = _0_CosPersistencePDS_DA.DAObjectFactoryFinder._NP_RepositoryId _omni_op_d = {"find_factory": _0_CosPersistencePDS_DA.DAObjectFactoryFinder._d_find_factory} DAObjectFactoryFinder._omni_skeleton = DAObjectFactoryFinder _0_CosPersistencePDS_DA__POA.DAObjectFactoryFinder = DAObjectFactoryFinder omniORB.registerSkeleton(DAObjectFactoryFinder._NP_RepositoryId, DAObjectFactoryFinder) del DAObjectFactoryFinder __name__ = "CosPersistencePDS_DA" # interface PDS_DA _0_CosPersistencePDS_DA._d_PDS_DA = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/PDS_DA:1.0", "PDS_DA") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PDS_DA:1.0"] = _0_CosPersistencePDS_DA._d_PDS_DA _0_CosPersistencePDS_DA.PDS_DA = omniORB.newEmptyClass() class PDS_DA (_0_CosPersistencePDS.PDS): _NP_RepositoryId = _0_CosPersistencePDS_DA._d_PDS_DA[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.PDS_DA = PDS_DA _0_CosPersistencePDS_DA._tc_PDS_DA = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_PDS_DA) omniORB.registerType(PDS_DA._NP_RepositoryId, _0_CosPersistencePDS_DA._d_PDS_DA, _0_CosPersistencePDS_DA._tc_PDS_DA) # PDS_DA operations and attributes PDS_DA._d_get_data = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), None) PDS_DA._d_set_data = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), (), None) PDS_DA._d_lookup = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0"], ), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), None) PDS_DA._d_get_pid = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0"], ), None) PDS_DA._d_get_object_pid = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0"], ), None) PDS_DA._d_data_factories = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectFactoryFinder:1.0"], ), None) # PDS_DA object reference class _objref_PDS_DA (_0_CosPersistencePDS._objref_PDS): _NP_RepositoryId = PDS_DA._NP_RepositoryId def __init__(self, obj): _0_CosPersistencePDS._objref_PDS.__init__(self, obj) def get_data(self, *args): return self._obj.invoke("get_data", _0_CosPersistencePDS_DA.PDS_DA._d_get_data, args) def set_data(self, *args): return self._obj.invoke("set_data", _0_CosPersistencePDS_DA.PDS_DA._d_set_data, args) def lookup(self, *args): return self._obj.invoke("lookup", _0_CosPersistencePDS_DA.PDS_DA._d_lookup, args) def get_pid(self, *args): return self._obj.invoke("get_pid", _0_CosPersistencePDS_DA.PDS_DA._d_get_pid, args) def get_object_pid(self, *args): return self._obj.invoke("get_object_pid", _0_CosPersistencePDS_DA.PDS_DA._d_get_object_pid, args) def data_factories(self, *args): return self._obj.invoke("data_factories", _0_CosPersistencePDS_DA.PDS_DA._d_data_factories, args) omniORB.registerObjref(PDS_DA._NP_RepositoryId, _objref_PDS_DA) _0_CosPersistencePDS_DA._objref_PDS_DA = _objref_PDS_DA del PDS_DA, _objref_PDS_DA # PDS_DA skeleton __name__ = "CosPersistencePDS_DA__POA" class PDS_DA (_0_CosPersistencePDS__POA.PDS): _NP_RepositoryId = _0_CosPersistencePDS_DA.PDS_DA._NP_RepositoryId _omni_op_d = {"get_data": _0_CosPersistencePDS_DA.PDS_DA._d_get_data, "set_data": _0_CosPersistencePDS_DA.PDS_DA._d_set_data, "lookup": _0_CosPersistencePDS_DA.PDS_DA._d_lookup, "get_pid": _0_CosPersistencePDS_DA.PDS_DA._d_get_pid, "get_object_pid": _0_CosPersistencePDS_DA.PDS_DA._d_get_object_pid, "data_factories": _0_CosPersistencePDS_DA.PDS_DA._d_data_factories} _omni_op_d.update(_0_CosPersistencePDS__POA.PDS._omni_op_d) PDS_DA._omni_skeleton = PDS_DA _0_CosPersistencePDS_DA__POA.PDS_DA = PDS_DA omniORB.registerSkeleton(PDS_DA._NP_RepositoryId, PDS_DA) del PDS_DA __name__ = "CosPersistencePDS_DA" # # End of module "CosPersistencePDS_DA" # __name__ = "CosPersistencePDS_DA_idl" _exported_modules = ( "CosPersistencePDS_DA", ) # The end.
# Python stubs generated by omniidl from ..\..\..\..\..\idl\COS\CosPersistencePDS_DA.idl # DO NOT EDIT THIS FILE! import omniORB, _omnipy from omniORB import CORBA, PortableServer _0_CORBA = CORBA _omnipy.checkVersion(4,2, __file__, 1) try: property except NameError: def property(*args): return None # #include "CosPersistencePID.idl" import CosPersistencePID_idl _0_CosPersistencePID = omniORB.openModule("CosPersistencePID") _0_CosPersistencePID__POA = omniORB.openModule("CosPersistencePID__POA") # #include "CosPersistencePDS.idl" import CosPersistencePDS_idl _0_CosPersistencePDS = omniORB.openModule("CosPersistencePDS") _0_CosPersistencePDS__POA = omniORB.openModule("CosPersistencePDS__POA") # # Start of module "CosPersistencePDS_DA" # __name__ = "CosPersistencePDS_DA" _0_CosPersistencePDS_DA = omniORB.openModule("CosPersistencePDS_DA", r"..\..\..\..\..\idl\COS\CosPersistencePDS_DA.idl") _0_CosPersistencePDS_DA__POA = omniORB.openModule("CosPersistencePDS_DA__POA", r"..\..\..\..\..\idl\COS\CosPersistencePDS_DA.idl") # typedef ... DAObjectID class DAObjectID: _NP_RepositoryId = "IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0" def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _0_CosPersistencePDS_DA.DAObjectID = DAObjectID _0_CosPersistencePDS_DA._d_DAObjectID = (omniORB.tcInternal.tv_string,0) _0_CosPersistencePDS_DA._ad_DAObjectID = (omniORB.tcInternal.tv_alias, DAObjectID._NP_RepositoryId, "DAObjectID", (omniORB.tcInternal.tv_string,0)) _0_CosPersistencePDS_DA._tc_DAObjectID = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._ad_DAObjectID) omniORB.registerType(DAObjectID._NP_RepositoryId, _0_CosPersistencePDS_DA._ad_DAObjectID, _0_CosPersistencePDS_DA._tc_DAObjectID) del DAObjectID # interface PID_DA _0_CosPersistencePDS_DA._d_PID_DA = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0", "PID_DA") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0"] = _0_CosPersistencePDS_DA._d_PID_DA _0_CosPersistencePDS_DA.PID_DA = omniORB.newEmptyClass() class PID_DA (_0_CosPersistencePID.PID): _NP_RepositoryId = _0_CosPersistencePDS_DA._d_PID_DA[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.PID_DA = PID_DA _0_CosPersistencePDS_DA._tc_PID_DA = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_PID_DA) omniORB.registerType(PID_DA._NP_RepositoryId, _0_CosPersistencePDS_DA._d_PID_DA, _0_CosPersistencePDS_DA._tc_PID_DA) # PID_DA operations and attributes PID_DA._d__get_oid = ((),(omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0"],),None) PID_DA._d__set_oid = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0"],),(),None) # PID_DA object reference class _objref_PID_DA (_0_CosPersistencePID._objref_PID): _NP_RepositoryId = PID_DA._NP_RepositoryId def __init__(self, obj): _0_CosPersistencePID._objref_PID.__init__(self, obj) def _get_oid(self, *args): return self._obj.invoke("_get_oid", _0_CosPersistencePDS_DA.PID_DA._d__get_oid, args) def _set_oid(self, *args): return self._obj.invoke("_set_oid", _0_CosPersistencePDS_DA.PID_DA._d__set_oid, args) oid = property(_get_oid, _set_oid) omniORB.registerObjref(PID_DA._NP_RepositoryId, _objref_PID_DA) _0_CosPersistencePDS_DA._objref_PID_DA = _objref_PID_DA del PID_DA, _objref_PID_DA # PID_DA skeleton __name__ = "CosPersistencePDS_DA__POA" class PID_DA (_0_CosPersistencePID__POA.PID): _NP_RepositoryId = _0_CosPersistencePDS_DA.PID_DA._NP_RepositoryId _omni_op_d = {"_get_oid": _0_CosPersistencePDS_DA.PID_DA._d__get_oid, "_set_oid": _0_CosPersistencePDS_DA.PID_DA._d__set_oid} _omni_op_d.update(_0_CosPersistencePID__POA.PID._omni_op_d) PID_DA._omni_skeleton = PID_DA _0_CosPersistencePDS_DA__POA.PID_DA = PID_DA omniORB.registerSkeleton(PID_DA._NP_RepositoryId, PID_DA) del PID_DA __name__ = "CosPersistencePDS_DA" # interface DAObject _0_CosPersistencePDS_DA._d_DAObject = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0", "DAObject") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"] = _0_CosPersistencePDS_DA._d_DAObject _0_CosPersistencePDS_DA.DAObject = omniORB.newEmptyClass() class DAObject : _NP_RepositoryId = _0_CosPersistencePDS_DA._d_DAObject[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.DAObject = DAObject _0_CosPersistencePDS_DA._tc_DAObject = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_DAObject) omniORB.registerType(DAObject._NP_RepositoryId, _0_CosPersistencePDS_DA._d_DAObject, _0_CosPersistencePDS_DA._tc_DAObject) # DAObject operations and attributes DAObject._d_dado_same = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), (omniORB.tcInternal.tv_boolean, ), None) DAObject._d_dado_oid = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0"], ), None) DAObject._d_dado_pid = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0"], ), None) DAObject._d_dado_remove = ((), (), None) DAObject._d_dado_free = ((), (), None) # DAObject object reference class _objref_DAObject (CORBA.Object): _NP_RepositoryId = DAObject._NP_RepositoryId def __init__(self, obj): CORBA.Object.__init__(self, obj) def dado_same(self, *args): return self._obj.invoke("dado_same", _0_CosPersistencePDS_DA.DAObject._d_dado_same, args) def dado_oid(self, *args): return self._obj.invoke("dado_oid", _0_CosPersistencePDS_DA.DAObject._d_dado_oid, args) def dado_pid(self, *args): return self._obj.invoke("dado_pid", _0_CosPersistencePDS_DA.DAObject._d_dado_pid, args) def dado_remove(self, *args): return self._obj.invoke("dado_remove", _0_CosPersistencePDS_DA.DAObject._d_dado_remove, args) def dado_free(self, *args): return self._obj.invoke("dado_free", _0_CosPersistencePDS_DA.DAObject._d_dado_free, args) omniORB.registerObjref(DAObject._NP_RepositoryId, _objref_DAObject) _0_CosPersistencePDS_DA._objref_DAObject = _objref_DAObject del DAObject, _objref_DAObject # DAObject skeleton __name__ = "CosPersistencePDS_DA__POA" class DAObject (PortableServer.Servant): _NP_RepositoryId = _0_CosPersistencePDS_DA.DAObject._NP_RepositoryId _omni_op_d = {"dado_same": _0_CosPersistencePDS_DA.DAObject._d_dado_same, "dado_oid": _0_CosPersistencePDS_DA.DAObject._d_dado_oid, "dado_pid": _0_CosPersistencePDS_DA.DAObject._d_dado_pid, "dado_remove": _0_CosPersistencePDS_DA.DAObject._d_dado_remove, "dado_free": _0_CosPersistencePDS_DA.DAObject._d_dado_free} DAObject._omni_skeleton = DAObject _0_CosPersistencePDS_DA__POA.DAObject = DAObject omniORB.registerSkeleton(DAObject._NP_RepositoryId, DAObject) del DAObject __name__ = "CosPersistencePDS_DA" # interface DAObjectFactory _0_CosPersistencePDS_DA._d_DAObjectFactory = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/DAObjectFactory:1.0", "DAObjectFactory") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectFactory:1.0"] = _0_CosPersistencePDS_DA._d_DAObjectFactory _0_CosPersistencePDS_DA.DAObjectFactory = omniORB.newEmptyClass() class DAObjectFactory : _NP_RepositoryId = _0_CosPersistencePDS_DA._d_DAObjectFactory[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.DAObjectFactory = DAObjectFactory _0_CosPersistencePDS_DA._tc_DAObjectFactory = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_DAObjectFactory) omniORB.registerType(DAObjectFactory._NP_RepositoryId, _0_CosPersistencePDS_DA._d_DAObjectFactory, _0_CosPersistencePDS_DA._tc_DAObjectFactory) # DAObjectFactory operations and attributes DAObjectFactory._d_create = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), None) # DAObjectFactory object reference class _objref_DAObjectFactory (CORBA.Object): _NP_RepositoryId = DAObjectFactory._NP_RepositoryId def __init__(self, obj): CORBA.Object.__init__(self, obj) def create(self, *args): return self._obj.invoke("create", _0_CosPersistencePDS_DA.DAObjectFactory._d_create, args) omniORB.registerObjref(DAObjectFactory._NP_RepositoryId, _objref_DAObjectFactory) _0_CosPersistencePDS_DA._objref_DAObjectFactory = _objref_DAObjectFactory del DAObjectFactory, _objref_DAObjectFactory # DAObjectFactory skeleton __name__ = "CosPersistencePDS_DA__POA" class DAObjectFactory (PortableServer.Servant): _NP_RepositoryId = _0_CosPersistencePDS_DA.DAObjectFactory._NP_RepositoryId _omni_op_d = {"create": _0_CosPersistencePDS_DA.DAObjectFactory._d_create} DAObjectFactory._omni_skeleton = DAObjectFactory _0_CosPersistencePDS_DA__POA.DAObjectFactory = DAObjectFactory omniORB.registerSkeleton(DAObjectFactory._NP_RepositoryId, DAObjectFactory) del DAObjectFactory __name__ = "CosPersistencePDS_DA" # interface DAObjectFactoryFinder _0_CosPersistencePDS_DA._d_DAObjectFactoryFinder = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/DAObjectFactoryFinder:1.0", "DAObjectFactoryFinder") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectFactoryFinder:1.0"] = _0_CosPersistencePDS_DA._d_DAObjectFactoryFinder _0_CosPersistencePDS_DA.DAObjectFactoryFinder = omniORB.newEmptyClass() class DAObjectFactoryFinder : _NP_RepositoryId = _0_CosPersistencePDS_DA._d_DAObjectFactoryFinder[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.DAObjectFactoryFinder = DAObjectFactoryFinder _0_CosPersistencePDS_DA._tc_DAObjectFactoryFinder = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_DAObjectFactoryFinder) omniORB.registerType(DAObjectFactoryFinder._NP_RepositoryId, _0_CosPersistencePDS_DA._d_DAObjectFactoryFinder, _0_CosPersistencePDS_DA._tc_DAObjectFactoryFinder) # DAObjectFactoryFinder operations and attributes DAObjectFactoryFinder._d_find_factory = (((omniORB.tcInternal.tv_string,0), ), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectFactory:1.0"], ), None) # DAObjectFactoryFinder object reference class _objref_DAObjectFactoryFinder (CORBA.Object): _NP_RepositoryId = DAObjectFactoryFinder._NP_RepositoryId def __init__(self, obj): CORBA.Object.__init__(self, obj) def find_factory(self, *args): return self._obj.invoke("find_factory", _0_CosPersistencePDS_DA.DAObjectFactoryFinder._d_find_factory, args) omniORB.registerObjref(DAObjectFactoryFinder._NP_RepositoryId, _objref_DAObjectFactoryFinder) _0_CosPersistencePDS_DA._objref_DAObjectFactoryFinder = _objref_DAObjectFactoryFinder del DAObjectFactoryFinder, _objref_DAObjectFactoryFinder # DAObjectFactoryFinder skeleton __name__ = "CosPersistencePDS_DA__POA" class DAObjectFactoryFinder (PortableServer.Servant): _NP_RepositoryId = _0_CosPersistencePDS_DA.DAObjectFactoryFinder._NP_RepositoryId _omni_op_d = {"find_factory": _0_CosPersistencePDS_DA.DAObjectFactoryFinder._d_find_factory} DAObjectFactoryFinder._omni_skeleton = DAObjectFactoryFinder _0_CosPersistencePDS_DA__POA.DAObjectFactoryFinder = DAObjectFactoryFinder omniORB.registerSkeleton(DAObjectFactoryFinder._NP_RepositoryId, DAObjectFactoryFinder) del DAObjectFactoryFinder __name__ = "CosPersistencePDS_DA" # interface PDS_DA _0_CosPersistencePDS_DA._d_PDS_DA = (omniORB.tcInternal.tv_objref, "IDL:omg.org/CosPersistencePDS_DA/PDS_DA:1.0", "PDS_DA") omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PDS_DA:1.0"] = _0_CosPersistencePDS_DA._d_PDS_DA _0_CosPersistencePDS_DA.PDS_DA = omniORB.newEmptyClass() class PDS_DA (_0_CosPersistencePDS.PDS): _NP_RepositoryId = _0_CosPersistencePDS_DA._d_PDS_DA[1] def __init__(self, *args, **kw): raise RuntimeError("Cannot construct objects of this type.") _nil = CORBA.Object._nil _0_CosPersistencePDS_DA.PDS_DA = PDS_DA _0_CosPersistencePDS_DA._tc_PDS_DA = omniORB.tcInternal.createTypeCode(_0_CosPersistencePDS_DA._d_PDS_DA) omniORB.registerType(PDS_DA._NP_RepositoryId, _0_CosPersistencePDS_DA._d_PDS_DA, _0_CosPersistencePDS_DA._tc_PDS_DA) # PDS_DA operations and attributes PDS_DA._d_get_data = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), None) PDS_DA._d_set_data = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), (), None) PDS_DA._d_lookup = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectID:1.0"], ), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), None) PDS_DA._d_get_pid = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0"], ), None) PDS_DA._d_get_object_pid = ((omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObject:1.0"], ), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/PID_DA:1.0"], ), None) PDS_DA._d_data_factories = ((), (omniORB.typeMapping["IDL:omg.org/CosPersistencePDS_DA/DAObjectFactoryFinder:1.0"], ), None) # PDS_DA object reference class _objref_PDS_DA (_0_CosPersistencePDS._objref_PDS): _NP_RepositoryId = PDS_DA._NP_RepositoryId def __init__(self, obj): _0_CosPersistencePDS._objref_PDS.__init__(self, obj) def get_data(self, *args): return self._obj.invoke("get_data", _0_CosPersistencePDS_DA.PDS_DA._d_get_data, args) def set_data(self, *args): return self._obj.invoke("set_data", _0_CosPersistencePDS_DA.PDS_DA._d_set_data, args) def lookup(self, *args): return self._obj.invoke("lookup", _0_CosPersistencePDS_DA.PDS_DA._d_lookup, args) def get_pid(self, *args): return self._obj.invoke("get_pid", _0_CosPersistencePDS_DA.PDS_DA._d_get_pid, args) def get_object_pid(self, *args): return self._obj.invoke("get_object_pid", _0_CosPersistencePDS_DA.PDS_DA._d_get_object_pid, args) def data_factories(self, *args): return self._obj.invoke("data_factories", _0_CosPersistencePDS_DA.PDS_DA._d_data_factories, args) omniORB.registerObjref(PDS_DA._NP_RepositoryId, _objref_PDS_DA) _0_CosPersistencePDS_DA._objref_PDS_DA = _objref_PDS_DA del PDS_DA, _objref_PDS_DA # PDS_DA skeleton __name__ = "CosPersistencePDS_DA__POA" class PDS_DA (_0_CosPersistencePDS__POA.PDS): _NP_RepositoryId = _0_CosPersistencePDS_DA.PDS_DA._NP_RepositoryId _omni_op_d = {"get_data": _0_CosPersistencePDS_DA.PDS_DA._d_get_data, "set_data": _0_CosPersistencePDS_DA.PDS_DA._d_set_data, "lookup": _0_CosPersistencePDS_DA.PDS_DA._d_lookup, "get_pid": _0_CosPersistencePDS_DA.PDS_DA._d_get_pid, "get_object_pid": _0_CosPersistencePDS_DA.PDS_DA._d_get_object_pid, "data_factories": _0_CosPersistencePDS_DA.PDS_DA._d_data_factories} _omni_op_d.update(_0_CosPersistencePDS__POA.PDS._omni_op_d) PDS_DA._omni_skeleton = PDS_DA _0_CosPersistencePDS_DA__POA.PDS_DA = PDS_DA omniORB.registerSkeleton(PDS_DA._NP_RepositoryId, PDS_DA) del PDS_DA __name__ = "CosPersistencePDS_DA" # # End of module "CosPersistencePDS_DA" # __name__ = "CosPersistencePDS_DA_idl" _exported_modules = ( "CosPersistencePDS_DA", ) # The end.
en
0.516003
# Python stubs generated by omniidl from ..\..\..\..\..\idl\COS\CosPersistencePDS_DA.idl # DO NOT EDIT THIS FILE! # #include "CosPersistencePID.idl" # #include "CosPersistencePDS.idl" # # Start of module "CosPersistencePDS_DA" # # typedef ... DAObjectID # interface PID_DA # PID_DA operations and attributes # PID_DA object reference # PID_DA skeleton # interface DAObject # DAObject operations and attributes # DAObject object reference # DAObject skeleton # interface DAObjectFactory # DAObjectFactory operations and attributes # DAObjectFactory object reference # DAObjectFactory skeleton # interface DAObjectFactoryFinder # DAObjectFactoryFinder operations and attributes # DAObjectFactoryFinder object reference # DAObjectFactoryFinder skeleton # interface PDS_DA # PDS_DA operations and attributes # PDS_DA object reference # PDS_DA skeleton # # End of module "CosPersistencePDS_DA" # # The end.
1.742449
2
arpoc/exceptions.py
JustKiddingCode/arpoc
1
6613236
<filename>arpoc/exceptions.py class OIDCProxyException(Exception): pass class ACEntityMissing(OIDCProxyException): pass class AttributeMissing(OIDCProxyException): pass class SubjectAttributeMissing(AttributeMissing): def __init__(self, message: str, attr: str) -> None: super().__init__(self, message) self.attr = attr class ObjectAttributeMissing(AttributeMissing): pass class EnvironmentAttributeMissing(AttributeMissing): pass class BadRuleSyntax(Exception): pass class BadSemantics(Exception): pass class DuplicateKeyError(OIDCProxyException): pass class ConfigError(OIDCProxyException): pass
<filename>arpoc/exceptions.py class OIDCProxyException(Exception): pass class ACEntityMissing(OIDCProxyException): pass class AttributeMissing(OIDCProxyException): pass class SubjectAttributeMissing(AttributeMissing): def __init__(self, message: str, attr: str) -> None: super().__init__(self, message) self.attr = attr class ObjectAttributeMissing(AttributeMissing): pass class EnvironmentAttributeMissing(AttributeMissing): pass class BadRuleSyntax(Exception): pass class BadSemantics(Exception): pass class DuplicateKeyError(OIDCProxyException): pass class ConfigError(OIDCProxyException): pass
none
1
2.288973
2
my_lambda/helper_utility.py
ahvblackwelltech/lambdata_ahvblackwelltech
0
6613237
import pandas as pd from sklearn.model_selection import train_test_split # from sklearn.datasets import load_wine from pdb import set_trace as breakpoint from IPython.display import display # def changeColumnsName(df): # df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')) # return df class MyDataSplitter(): def __init__(self, df): self.df = df def train_validation_test_split(self, features, target, train_size=0.7, val_size=0.1, test_size=0.2, random_state=None, shuffle=True): X_train_val, X_test, y_train_val, y_test = train_test_split( self.X, self.y, test_size=test_size, random_state=random_state, shuffle=shuffle) X_train, X_val, y_train, y_val = train_test_split( X_train_val, y_train_val, test_size=val_size/(train_size+val_size), random_state=random_state, shuffle=shuffle) return X_train, X_val, X_test, y_train, y_val, y_test def dateDivider(self, date_col): converted_df = self.df.copy() converted_df['Year'] = pd.DatetimeIndex(converted_df[date_col]).year converted_df['Month'] = pd.DatetimeIndex(converted_df[date_col]).month converted_df['Day'] = pd.DatetimeIndex(converted_df[date_col]).day return converted_df def print_split_summary(self, X_train, X_val, X_test): print('########### TRAINING DATA ###########') print(f'X_train Shape: {X_train.shape}') display(X_train.describe(include='all').transpose()) print('########### VALIDATION DATA ###########') print(f'X_val Shape: {X_val.shape}') display(X_val.describe(include='all').transpose()) print('########### Test DATA ###########') print(f'X_test Shape: {X_test.shape}') display(X_test.describe(include='all').transpose()) if __name__ == '__main__': df = pd.read_csv('burritos.csv') breakpoint() print(df.shape)
import pandas as pd from sklearn.model_selection import train_test_split # from sklearn.datasets import load_wine from pdb import set_trace as breakpoint from IPython.display import display # def changeColumnsName(df): # df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')) # return df class MyDataSplitter(): def __init__(self, df): self.df = df def train_validation_test_split(self, features, target, train_size=0.7, val_size=0.1, test_size=0.2, random_state=None, shuffle=True): X_train_val, X_test, y_train_val, y_test = train_test_split( self.X, self.y, test_size=test_size, random_state=random_state, shuffle=shuffle) X_train, X_val, y_train, y_val = train_test_split( X_train_val, y_train_val, test_size=val_size/(train_size+val_size), random_state=random_state, shuffle=shuffle) return X_train, X_val, X_test, y_train, y_val, y_test def dateDivider(self, date_col): converted_df = self.df.copy() converted_df['Year'] = pd.DatetimeIndex(converted_df[date_col]).year converted_df['Month'] = pd.DatetimeIndex(converted_df[date_col]).month converted_df['Day'] = pd.DatetimeIndex(converted_df[date_col]).day return converted_df def print_split_summary(self, X_train, X_val, X_test): print('########### TRAINING DATA ###########') print(f'X_train Shape: {X_train.shape}') display(X_train.describe(include='all').transpose()) print('########### VALIDATION DATA ###########') print(f'X_val Shape: {X_val.shape}') display(X_val.describe(include='all').transpose()) print('########### Test DATA ###########') print(f'X_test Shape: {X_test.shape}') display(X_test.describe(include='all').transpose()) if __name__ == '__main__': df = pd.read_csv('burritos.csv') breakpoint() print(df.shape)
fa
0.089638
# from sklearn.datasets import load_wine # def changeColumnsName(df): # df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')) # return df ########## TRAINING DATA ###########') ########## VALIDATION DATA ###########') ########## Test DATA ###########')
2.709667
3
cubes_lite/sql/mapping.py
notexistence/cubes_lite
0
6613238
<reponame>notexistence/cubes_lite<filename>cubes_lite/sql/mapping.py # -*- encoding: utf-8 -*- from __future__ import absolute_import import sqlalchemy as sa import sqlalchemy.sql as sql from copy import copy from cubes_lite import compat from cubes_lite.errors import ( ArgumentError, ModelError, NoSuchAttributeError, MissingObjectError, ) from cubes_lite.model.utils import object_dict from .functions import Function __all__ = ( 'Mapper', ) class NoSuchTableError(MissingObjectError): """Error related to the physical star schema.""" pass def _make_compound_key(table, key): """Returns a list of columns from `column_key` for `table` representing potentially a compound key. The `column_key` can be a name of a single column or list of column names.""" if not isinstance(key, (list, tuple)): key = [key] return [table.columns[name] for name in key] class Mapper(object): """Represents a star/snowflake table schema""" def __init__(self, cube, metadata): self.cube = cube self.metadata = metadata self.joins = [JoinObject.parse(join) for join in self.cube.joins] self._columns = {} # keys: logical column names self._physical_tables = {} # keys: tuples (schema, table physical name) self.root_table_object = TableObject.parse(self.cube.ref) self.root_table_object.table = self.construct_physical_table( name=self.root_table_object.name, schema=self.root_table_object.schema, ) # keys: tuples (schema, table aliased name) self._table_objects = self._collect_tables() def __getitem__(self, key): return self._columns[key] def _collect_tables(self): """" Collect all the detail tables We don't need to collect the master tables as they are expected to be referenced as 'details'. The exception is the fact table that is provided explicitly for the snowflake schema. """ table_objects = [self.root_table_object] for join in self.joins: table_name = join.detail.table if not table_name: raise ModelError( 'No detail table specified for a join "{}"'.format(join) ) detail_table = self.construct_physical_table( name=table_name, schema=join.detail.schema, ) if join.alias: detail_table = detail_table.alias(join.alias) obj = TableObject( table=detail_table, schema=join.detail.schema, name=table_name, alias=join.alias, join=join, ) table_objects.append(obj) table_objects = object_dict( table_objects, key_func=lambda obj: (obj.schema, obj.alias or obj.name), error_message=( 'Detail table "{key[1]}" joined twice in cube "{cube}".' 'Unique join alias is required.' ), error_dict={'cube': self.cube.name}, ) # alias for fact table table_objects[(None, None)] = self.root_table_object return table_objects def get_table_object(self, key): """Return a table reference for `key` which has form of a tuple (`schema`, `table`). """ if not key: raise ArgumentError('Table key should not be empty') try: return self._table_objects[key] except KeyError: schema = '"{}".'.format(key[0]) if key[0] else '' raise ModelError( 'Unknown star table {}"{}". Missing join?' .format(schema, key[1]) ) def construct_physical_table(self, name, schema=None): """Return a physical table or table expression, regardless whether it exists or not in the star.""" if '.' in name: if schema: raise ArgumentError('Ambiguous schema in "{}"'.format(name)) schema, name = name.split('.', 1) key = (schema, name) table = self._physical_tables.get(key) if table is not None: return table try: table = sa.Table( name, self.metadata, autoload=True, schema=schema, ) except sa.exc.NoSuchTableError: in_schema = ' in schema "{}"'.format(schema) if schema else '' msg = 'No such fact table "{}"{}'.format(name, in_schema) raise NoSuchTableError(msg) self._physical_tables[key] = table return table def get_column_by_attribute(self, attribute): """Return a column for `logical` reference. The returned column will have a label same as the column part of `logical`. """ if isinstance(attribute, compat.string_type): attribute = self.cube.get_attributes([attribute])[0] logical = attribute.ref if logical in self._columns: return self._columns[logical] try: column_object = self.get_column_object_by_attribute(attribute) except KeyError: raise NoSuchAttributeError(logical) table_object = self.get_table_object(column_object.table_key) table = table_object.table try: column = table.columns[column_object.column] except KeyError: available = '", "'.join(str(c) for c in table.columns) raise ModelError( 'Unknown column "{}" in table "{}" available columns: "{}"' .format(column_object.column, column_object.table, available) ) if column_object.extract: column = sql.expression.extract(column_object.extract, column) if column_object.function: column = getattr(sql.expression.func, column_object.function)(column) column = column.label(column_object.column) self._columns[logical] = column return column def construct_column_for_attribute(self, attribute, columns): if isinstance(attribute, compat.string_type): attribute = self.cube.get_attributes([attribute])[0] names = [attribute.ref] try: column_object = self.get_column_object_by_attribute(attribute) except KeyError: raise NoSuchAttributeError(attribute) names.append(column_object.qualified_column) for name in names: try: column = columns[name] break except KeyError: continue else: raise ModelError('Unknown column "{}"'.format(name)) if column_object.extract: column = sql.expression.extract(column_object.extract, column) if column_object.function: column = getattr(sql.expression.func, column_object.function)(column) label = attribute.ref if attribute.dimension.is_plain else attribute.base_name column = column.label(label) return column def get_column_object_by_attribute(self, attribute): """Returns implicit physical column reference for `attribute`, which should be an instance of :class:`cubes_lite.model.Attribute`. The returned reference has attributes `schema`, `table`, `column`, `extract`.""" if not attribute.is_base: raise ModelError( 'Attribute "{}" is dependant, it can not have a physical' 'representation' .format(attribute.name), ) physical = self.cube.mappings.get(attribute.ref) if physical: return ColumnObject.parse(physical) schema, table = self._ref_key_for_attribute(attribute) return ColumnObject.parse((schema, table, attribute.base_name)) def _ref_key_for_attribute(self, attribute): """Return a tuple (schema, table) for attribute.""" dimension = attribute.dimension if dimension.is_plain: table = self.cube.ref else: table = dimension.ref table = TableObject.parse(table) return (table.schema, table.name) def _required_tables(self, attributes, root_table_object=None): """Get all tables that are required to be joined to get `attributes`. `attributes` is a list of `Mapper` attributes (or objects with same kind of attributes). """ root_table_object = root_table_object or self.root_table_object attributes = [attr for attr in attributes if attr.is_base] relevant_tables = set( self.get_table_object(self.get_column_object_by_attribute(a).table_key) for a in attributes ) # now we have to resolve all dependencies required = {} while relevant_tables: table = relevant_tables.pop() required[table.key] = table if not table.join: continue master = table.join.master.table_key if master not in required: relevant_tables.add(self.get_table_object(master)) detail = table.join.detail.table_key if table.join.alias: detail = (detail[0], table.join.alias) if detail not in required: relevant_tables.add(self.get_table_object(detail)) # plain_dimensions = {a.dimension for a in attributes if a.dimension.is_plain} # if not plain_dimensions: # required.pop(self.root_table_object.key, None) required.pop(self.root_table_object.key, None) required = { key: table for key, table in required.items() if ( table.join.master.table is not None or table == root_table_object ) } if root_table_object.key in required: masters = {root_table_object.key: root_table_object} sorted_tables = [root_table_object] else: details = [ table for table in required.values() if table.join.method == 'detail' ] if details: first = details[0] else: first = required.values()[0] sorted_tables = [first] masters = {first.key: first} while required: details = [ table for table in required.values() if table.join and table.join.master.table_key in masters ] if not details: break for detail in details: masters[detail.key] = detail sorted_tables.append(detail) del required[detail.key] if len(required) > 1: keys = [ str(table) for table in required.values() if table.key != self.root_table_object.key ] raise ModelError( 'Some tables are not joined: {}' .format(', '.join(keys)) ) return sorted_tables def get_joined_tables_for(self, attributes, root_table_object=None): """The main method for generating underlying star schema joins. Returns a denormalized JOIN expression that includes all relevant tables containing base `attributes` (attributes representing actual columns). """ attributes = self.cube.get_attributes(attributes) table_objects = self._required_tables(attributes, root_table_object) return self.join_tables(table_objects) def join_tables(self, table_objects): # Dictionary of raw tables and their joined products # At the end this should contain only one item representing the whole # star. star_tables = {o.key: o.table for o in table_objects} # Here the `star` contains mapping table key -> table, which will be # gradually replaced by JOINs # Perform the joins # ================= # # 1. find the column # 2. construct the condition # 3. use the appropriate SQL JOIN # 4. wrap the star with detail # first table does not need to be joined star = table_objects[0].table for table in table_objects[1:]: if not table.join: raise ModelError( 'Attempt to join the table "{}" without join spec'.format(table) ) join = table.join # Get the physical table object (aliased) and already constructed # key (properly aliased) detail_table = table.table detail_key = table.key # The `table` here is a detail table to be joined. We need to get # the master table this table joins to: master = join.master master_key = master.table_key # We need plain tables to get columns for prepare the join # condition. We can't get it form `star`. # Master table.column master_table = self.get_table_object(master_key).table try: master_columns = _make_compound_key(master_table, master.column) except KeyError as e: raise ModelError( 'Unable to find master key column "{key}" ' 'in table "{table}"' .format(key=e, table=master_table) ) # Detail table.column try: detail_columns = _make_compound_key(detail_table, join.detail.column) except KeyError as e: raise ModelError( 'Unable to find master key column "{key}" ' 'in table "{table}"' .format(key=e, table=detail_table) ) if len(master_columns) != len(detail_columns): raise ModelError( 'Compound keys for master "{}" and detail ' '"{}" table have different number of columns' .format(master_table, detail_table) ) # the JOIN ON condition key_conditions = [ left == right for left, right in zip(master_columns, detail_columns) ] onclause = sa.and_(*key_conditions) # Determine the join type based on the join method. If the method # is "detail" then we need to swap the order of the tables # (products), because SQLAlchemy provides inteface only for # left-outer join. left, right = (star, detail_table) if join.method is None or join.method == 'match': is_outer = False elif join.method == 'master': is_outer = True elif join.method == 'detail': # Swap the master and detail tables to perform RIGHT OUTER JOIN left, right = (right, left) is_outer = True else: raise ModelError('Unknown join method "{}"'.format(join.method)) star = sql.expression.join( left, right, onclause=onclause, isouter=is_outer, ) # Consume the detail if detail_key not in star_tables: raise ModelError( 'Detail table "{}" not in star. Missing join?' .format(detail_table) ) # The table is consumed by the join product, becomes the join # product itself. star_tables[detail_key] = star star_tables[master_key] = star return star def compile_aggregates(self, aggregates, base_columns=None, coalesce=True): aggregates = [self.cube.get_aggregate(a) for a in aggregates] if not base_columns: base_columns = self.cube.all_fact_attributes if not isinstance(base_columns, dict): base_columns = {c.name: c for c in base_columns} context = ColumnsContext(base_columns) # dependency resolution # maximum number of iterations: the worst case times = len(aggregates) ** 2 sorted_dependants = [] dependants = aggregates[:] for _ in range(times): if not dependants: break attr = dependants.pop(0) already_prepared = [dep.name for dep in sorted_dependants] if all( (related in context) or (related in already_prepared) for related in attr.depends_on ): # all dependencies already in context sorted_dependants.append(attr) continue dependants.append(attr) # construct all aggregates with its dependencies # in reverse-dependency order for attr in sorted_dependants: function_name = attr.function.lower() function = Function.get(function_name) column = function(attr, context, coalesce) context.add_column(attr.name, column) return [ context.columns[a.name] for a in aggregates ] class ColumnObject(object): """Physical column reference. `schema` is a database schema name, `table` is a table name containing the `column`. `extract` is an element to be extracted from complex data type such as date or JSON (in postgres). `function` is name of unary function to be applied on the `column`.""" @classmethod def parse(cls, obj, default_table=None, default_schema=None): """Utility function that will create a `Column` reference object from an anonymous tuple, dictionary or a similar object. `obj` can also be a string in form ``schema.table.column`` where shcema or both schema and table can be ommited. `default_table` and `default_schema` are used when no table or schema is provided in `obj`. """ if obj is None: raise ArgumentError('Mapping object can not be None') if isinstance(obj, compat.string_type): obj = obj.split('.') schema = None table = None column = None extract = None function = None if isinstance(obj, (tuple, list)): if len(obj) == 1: column = obj[0] table = None schema = None elif len(obj) == 2: table, column = obj schema = None elif len(obj) == 3: schema, table, column = obj else: raise ArgumentError( 'Join key can have 1 to 3 items (has "{}"): "{}"' .format(len(obj), obj) ) if hasattr(obj, 'get'): schema = obj.get('schema') table = obj.get('table') column = obj.get('column') extract = obj.get('extract') function = obj.get('function') if column is None: schema = obj.schema table = obj.table column = obj.column extract = obj.extract function = obj.function table = table or default_table schema = schema or default_schema if column is None: raise ArgumentError( 'Cannot parse column representation: "{}"' .format(obj) ) return cls( schema=schema, table=table, column=column, extract=extract, function=function, ) def __init__(self, table, column, schema=None, extract=None, function=None): msg = 'Either `extract` or `function` can be used, not both' assert not all([extract, function]), msg self.table = table # type: str self.column = column # type: str self.schema = schema # type: str self.extract = extract # type: str self.function = function # type: str def __str__(self): output = self.column if self.table: output = '{}.{}'.format(self.table, output) if self.schema: return '{}.{}'.format(self.schema, output) return output @property def table_key(self): return self.schema, self.table @property def qualified_column(self): if not self.table: return self.column return '{}.{}'.format(self.table, self.column) class JoinObject(object): """Table join specification. `master` and `detail` are ColumnObjects. `method` - denotes which table members should be considered in the join: *master* - all master members (left outer join) *detail* - all detail members (right outer join) *match* - members must match (inner join). """ @classmethod def parse(cls, obj): master = None detail = None alias = None method = None if isinstance(obj, (tuple, list)): if len(obj) < 2 or len(obj) > 4: raise ArgumentError( 'Join object can have 2 to 4 items (has "{}"): "{}"' .format(len(obj), obj) ) master = obj[0] detail = obj[1] if len(obj) == 3: alias = obj[2] if len(obj) == 4: alias = obj[2] method = obj[3] if hasattr(obj, 'get'): master = obj.get('master') detail = obj.get('detail') alias = obj.get('alias') method = obj.get('method') if detail is None: master = obj.master detail = obj.detail alias = obj.alias method = obj.method if detail is None: raise ArgumentError( 'Cannot parse join representation: "{}"' .format(obj) ) master = ColumnObject.parse(master) detail = ColumnObject.parse(detail) return cls(master, detail, alias, method) def __init__(self, master, detail, alias=None, method=None): self.master = master # type: ColumnObject self.detail = detail # type: ColumnObject self.alias = alias # type: str self.method = method # type: str def __str__(self): return '{} -> {}'.format(self.master, self.detail) class TableObject(object): """ "schema", # Database schema "name", # Table name "alias", # Optional table alias instead of name "key", # Table key (for caching or referencing) "table", # SQLAlchemy Table object, reflected "join" # join which joins this table as a detail """ @classmethod def parse(cls, obj): if not obj: raise ArgumentError('Mapping object can not be empty') if isinstance(obj, compat.string_type): obj = obj.split('.') schema = None name = None if isinstance(obj, (tuple, list)): if len(obj) == 1: name = obj[0] schema = None elif len(obj) == 2: schema, name = obj else: raise ArgumentError( 'Table name can have 1 to 2 items (has "{}"): "{}"' .format(len(obj), obj) ) if hasattr(obj, 'get'): schema = obj.get('schema') name = obj.get('name') if name is None: schema = obj.schema name = obj.name if name is None: raise ArgumentError( 'Cannot parse table name representation: "{}"' .format(obj) ) return cls(name=name, schema=schema) def __init__(self, name, alias=None, schema=None, table=None, join=None): self.name = name # type: str self.alias = alias # type: str self.schema = schema # type: str self.table = table # type: sa.Table or sa.Selectable self.join = join # type: JoinObject def __str__(self): if self.schema: return '{}.{}'.format(self.schema, self.name) return self.name @property def key(self): return self.schema, self.alias or self.name def copy_with(self, table): result = copy(self) result.table = table return result class ColumnsContext(object): """Context used for building a list of all columns to be used within a single SQL query.""" def __init__(self, columns): """Creates a SQL expression context. * `bases` is a dictionary of base columns or column expressions * `parameters` is a flag where `True` means that the expression is expected to be an aggregate expression """ if columns: self._columns = dict(columns) else: self._columns = {} @property def columns(self): return self._columns def resolve(self, variable): """Resolve `variable` – return either a column, variable from a dictionary or a SQL constant (in that order).""" if variable in self._columns: return self._columns[variable] raise ValueError( 'Unknown variable "{}"'.format(variable) ) def __getitem__(self, item): return self.resolve(item) def __contains__(self, item): return item in self._columns def add_column(self, name, column): self._columns[name] = column
# -*- encoding: utf-8 -*- from __future__ import absolute_import import sqlalchemy as sa import sqlalchemy.sql as sql from copy import copy from cubes_lite import compat from cubes_lite.errors import ( ArgumentError, ModelError, NoSuchAttributeError, MissingObjectError, ) from cubes_lite.model.utils import object_dict from .functions import Function __all__ = ( 'Mapper', ) class NoSuchTableError(MissingObjectError): """Error related to the physical star schema.""" pass def _make_compound_key(table, key): """Returns a list of columns from `column_key` for `table` representing potentially a compound key. The `column_key` can be a name of a single column or list of column names.""" if not isinstance(key, (list, tuple)): key = [key] return [table.columns[name] for name in key] class Mapper(object): """Represents a star/snowflake table schema""" def __init__(self, cube, metadata): self.cube = cube self.metadata = metadata self.joins = [JoinObject.parse(join) for join in self.cube.joins] self._columns = {} # keys: logical column names self._physical_tables = {} # keys: tuples (schema, table physical name) self.root_table_object = TableObject.parse(self.cube.ref) self.root_table_object.table = self.construct_physical_table( name=self.root_table_object.name, schema=self.root_table_object.schema, ) # keys: tuples (schema, table aliased name) self._table_objects = self._collect_tables() def __getitem__(self, key): return self._columns[key] def _collect_tables(self): """" Collect all the detail tables We don't need to collect the master tables as they are expected to be referenced as 'details'. The exception is the fact table that is provided explicitly for the snowflake schema. """ table_objects = [self.root_table_object] for join in self.joins: table_name = join.detail.table if not table_name: raise ModelError( 'No detail table specified for a join "{}"'.format(join) ) detail_table = self.construct_physical_table( name=table_name, schema=join.detail.schema, ) if join.alias: detail_table = detail_table.alias(join.alias) obj = TableObject( table=detail_table, schema=join.detail.schema, name=table_name, alias=join.alias, join=join, ) table_objects.append(obj) table_objects = object_dict( table_objects, key_func=lambda obj: (obj.schema, obj.alias or obj.name), error_message=( 'Detail table "{key[1]}" joined twice in cube "{cube}".' 'Unique join alias is required.' ), error_dict={'cube': self.cube.name}, ) # alias for fact table table_objects[(None, None)] = self.root_table_object return table_objects def get_table_object(self, key): """Return a table reference for `key` which has form of a tuple (`schema`, `table`). """ if not key: raise ArgumentError('Table key should not be empty') try: return self._table_objects[key] except KeyError: schema = '"{}".'.format(key[0]) if key[0] else '' raise ModelError( 'Unknown star table {}"{}". Missing join?' .format(schema, key[1]) ) def construct_physical_table(self, name, schema=None): """Return a physical table or table expression, regardless whether it exists or not in the star.""" if '.' in name: if schema: raise ArgumentError('Ambiguous schema in "{}"'.format(name)) schema, name = name.split('.', 1) key = (schema, name) table = self._physical_tables.get(key) if table is not None: return table try: table = sa.Table( name, self.metadata, autoload=True, schema=schema, ) except sa.exc.NoSuchTableError: in_schema = ' in schema "{}"'.format(schema) if schema else '' msg = 'No such fact table "{}"{}'.format(name, in_schema) raise NoSuchTableError(msg) self._physical_tables[key] = table return table def get_column_by_attribute(self, attribute): """Return a column for `logical` reference. The returned column will have a label same as the column part of `logical`. """ if isinstance(attribute, compat.string_type): attribute = self.cube.get_attributes([attribute])[0] logical = attribute.ref if logical in self._columns: return self._columns[logical] try: column_object = self.get_column_object_by_attribute(attribute) except KeyError: raise NoSuchAttributeError(logical) table_object = self.get_table_object(column_object.table_key) table = table_object.table try: column = table.columns[column_object.column] except KeyError: available = '", "'.join(str(c) for c in table.columns) raise ModelError( 'Unknown column "{}" in table "{}" available columns: "{}"' .format(column_object.column, column_object.table, available) ) if column_object.extract: column = sql.expression.extract(column_object.extract, column) if column_object.function: column = getattr(sql.expression.func, column_object.function)(column) column = column.label(column_object.column) self._columns[logical] = column return column def construct_column_for_attribute(self, attribute, columns): if isinstance(attribute, compat.string_type): attribute = self.cube.get_attributes([attribute])[0] names = [attribute.ref] try: column_object = self.get_column_object_by_attribute(attribute) except KeyError: raise NoSuchAttributeError(attribute) names.append(column_object.qualified_column) for name in names: try: column = columns[name] break except KeyError: continue else: raise ModelError('Unknown column "{}"'.format(name)) if column_object.extract: column = sql.expression.extract(column_object.extract, column) if column_object.function: column = getattr(sql.expression.func, column_object.function)(column) label = attribute.ref if attribute.dimension.is_plain else attribute.base_name column = column.label(label) return column def get_column_object_by_attribute(self, attribute): """Returns implicit physical column reference for `attribute`, which should be an instance of :class:`cubes_lite.model.Attribute`. The returned reference has attributes `schema`, `table`, `column`, `extract`.""" if not attribute.is_base: raise ModelError( 'Attribute "{}" is dependant, it can not have a physical' 'representation' .format(attribute.name), ) physical = self.cube.mappings.get(attribute.ref) if physical: return ColumnObject.parse(physical) schema, table = self._ref_key_for_attribute(attribute) return ColumnObject.parse((schema, table, attribute.base_name)) def _ref_key_for_attribute(self, attribute): """Return a tuple (schema, table) for attribute.""" dimension = attribute.dimension if dimension.is_plain: table = self.cube.ref else: table = dimension.ref table = TableObject.parse(table) return (table.schema, table.name) def _required_tables(self, attributes, root_table_object=None): """Get all tables that are required to be joined to get `attributes`. `attributes` is a list of `Mapper` attributes (or objects with same kind of attributes). """ root_table_object = root_table_object or self.root_table_object attributes = [attr for attr in attributes if attr.is_base] relevant_tables = set( self.get_table_object(self.get_column_object_by_attribute(a).table_key) for a in attributes ) # now we have to resolve all dependencies required = {} while relevant_tables: table = relevant_tables.pop() required[table.key] = table if not table.join: continue master = table.join.master.table_key if master not in required: relevant_tables.add(self.get_table_object(master)) detail = table.join.detail.table_key if table.join.alias: detail = (detail[0], table.join.alias) if detail not in required: relevant_tables.add(self.get_table_object(detail)) # plain_dimensions = {a.dimension for a in attributes if a.dimension.is_plain} # if not plain_dimensions: # required.pop(self.root_table_object.key, None) required.pop(self.root_table_object.key, None) required = { key: table for key, table in required.items() if ( table.join.master.table is not None or table == root_table_object ) } if root_table_object.key in required: masters = {root_table_object.key: root_table_object} sorted_tables = [root_table_object] else: details = [ table for table in required.values() if table.join.method == 'detail' ] if details: first = details[0] else: first = required.values()[0] sorted_tables = [first] masters = {first.key: first} while required: details = [ table for table in required.values() if table.join and table.join.master.table_key in masters ] if not details: break for detail in details: masters[detail.key] = detail sorted_tables.append(detail) del required[detail.key] if len(required) > 1: keys = [ str(table) for table in required.values() if table.key != self.root_table_object.key ] raise ModelError( 'Some tables are not joined: {}' .format(', '.join(keys)) ) return sorted_tables def get_joined_tables_for(self, attributes, root_table_object=None): """The main method for generating underlying star schema joins. Returns a denormalized JOIN expression that includes all relevant tables containing base `attributes` (attributes representing actual columns). """ attributes = self.cube.get_attributes(attributes) table_objects = self._required_tables(attributes, root_table_object) return self.join_tables(table_objects) def join_tables(self, table_objects): # Dictionary of raw tables and their joined products # At the end this should contain only one item representing the whole # star. star_tables = {o.key: o.table for o in table_objects} # Here the `star` contains mapping table key -> table, which will be # gradually replaced by JOINs # Perform the joins # ================= # # 1. find the column # 2. construct the condition # 3. use the appropriate SQL JOIN # 4. wrap the star with detail # first table does not need to be joined star = table_objects[0].table for table in table_objects[1:]: if not table.join: raise ModelError( 'Attempt to join the table "{}" without join spec'.format(table) ) join = table.join # Get the physical table object (aliased) and already constructed # key (properly aliased) detail_table = table.table detail_key = table.key # The `table` here is a detail table to be joined. We need to get # the master table this table joins to: master = join.master master_key = master.table_key # We need plain tables to get columns for prepare the join # condition. We can't get it form `star`. # Master table.column master_table = self.get_table_object(master_key).table try: master_columns = _make_compound_key(master_table, master.column) except KeyError as e: raise ModelError( 'Unable to find master key column "{key}" ' 'in table "{table}"' .format(key=e, table=master_table) ) # Detail table.column try: detail_columns = _make_compound_key(detail_table, join.detail.column) except KeyError as e: raise ModelError( 'Unable to find master key column "{key}" ' 'in table "{table}"' .format(key=e, table=detail_table) ) if len(master_columns) != len(detail_columns): raise ModelError( 'Compound keys for master "{}" and detail ' '"{}" table have different number of columns' .format(master_table, detail_table) ) # the JOIN ON condition key_conditions = [ left == right for left, right in zip(master_columns, detail_columns) ] onclause = sa.and_(*key_conditions) # Determine the join type based on the join method. If the method # is "detail" then we need to swap the order of the tables # (products), because SQLAlchemy provides inteface only for # left-outer join. left, right = (star, detail_table) if join.method is None or join.method == 'match': is_outer = False elif join.method == 'master': is_outer = True elif join.method == 'detail': # Swap the master and detail tables to perform RIGHT OUTER JOIN left, right = (right, left) is_outer = True else: raise ModelError('Unknown join method "{}"'.format(join.method)) star = sql.expression.join( left, right, onclause=onclause, isouter=is_outer, ) # Consume the detail if detail_key not in star_tables: raise ModelError( 'Detail table "{}" not in star. Missing join?' .format(detail_table) ) # The table is consumed by the join product, becomes the join # product itself. star_tables[detail_key] = star star_tables[master_key] = star return star def compile_aggregates(self, aggregates, base_columns=None, coalesce=True): aggregates = [self.cube.get_aggregate(a) for a in aggregates] if not base_columns: base_columns = self.cube.all_fact_attributes if not isinstance(base_columns, dict): base_columns = {c.name: c for c in base_columns} context = ColumnsContext(base_columns) # dependency resolution # maximum number of iterations: the worst case times = len(aggregates) ** 2 sorted_dependants = [] dependants = aggregates[:] for _ in range(times): if not dependants: break attr = dependants.pop(0) already_prepared = [dep.name for dep in sorted_dependants] if all( (related in context) or (related in already_prepared) for related in attr.depends_on ): # all dependencies already in context sorted_dependants.append(attr) continue dependants.append(attr) # construct all aggregates with its dependencies # in reverse-dependency order for attr in sorted_dependants: function_name = attr.function.lower() function = Function.get(function_name) column = function(attr, context, coalesce) context.add_column(attr.name, column) return [ context.columns[a.name] for a in aggregates ] class ColumnObject(object): """Physical column reference. `schema` is a database schema name, `table` is a table name containing the `column`. `extract` is an element to be extracted from complex data type such as date or JSON (in postgres). `function` is name of unary function to be applied on the `column`.""" @classmethod def parse(cls, obj, default_table=None, default_schema=None): """Utility function that will create a `Column` reference object from an anonymous tuple, dictionary or a similar object. `obj` can also be a string in form ``schema.table.column`` where shcema or both schema and table can be ommited. `default_table` and `default_schema` are used when no table or schema is provided in `obj`. """ if obj is None: raise ArgumentError('Mapping object can not be None') if isinstance(obj, compat.string_type): obj = obj.split('.') schema = None table = None column = None extract = None function = None if isinstance(obj, (tuple, list)): if len(obj) == 1: column = obj[0] table = None schema = None elif len(obj) == 2: table, column = obj schema = None elif len(obj) == 3: schema, table, column = obj else: raise ArgumentError( 'Join key can have 1 to 3 items (has "{}"): "{}"' .format(len(obj), obj) ) if hasattr(obj, 'get'): schema = obj.get('schema') table = obj.get('table') column = obj.get('column') extract = obj.get('extract') function = obj.get('function') if column is None: schema = obj.schema table = obj.table column = obj.column extract = obj.extract function = obj.function table = table or default_table schema = schema or default_schema if column is None: raise ArgumentError( 'Cannot parse column representation: "{}"' .format(obj) ) return cls( schema=schema, table=table, column=column, extract=extract, function=function, ) def __init__(self, table, column, schema=None, extract=None, function=None): msg = 'Either `extract` or `function` can be used, not both' assert not all([extract, function]), msg self.table = table # type: str self.column = column # type: str self.schema = schema # type: str self.extract = extract # type: str self.function = function # type: str def __str__(self): output = self.column if self.table: output = '{}.{}'.format(self.table, output) if self.schema: return '{}.{}'.format(self.schema, output) return output @property def table_key(self): return self.schema, self.table @property def qualified_column(self): if not self.table: return self.column return '{}.{}'.format(self.table, self.column) class JoinObject(object): """Table join specification. `master` and `detail` are ColumnObjects. `method` - denotes which table members should be considered in the join: *master* - all master members (left outer join) *detail* - all detail members (right outer join) *match* - members must match (inner join). """ @classmethod def parse(cls, obj): master = None detail = None alias = None method = None if isinstance(obj, (tuple, list)): if len(obj) < 2 or len(obj) > 4: raise ArgumentError( 'Join object can have 2 to 4 items (has "{}"): "{}"' .format(len(obj), obj) ) master = obj[0] detail = obj[1] if len(obj) == 3: alias = obj[2] if len(obj) == 4: alias = obj[2] method = obj[3] if hasattr(obj, 'get'): master = obj.get('master') detail = obj.get('detail') alias = obj.get('alias') method = obj.get('method') if detail is None: master = obj.master detail = obj.detail alias = obj.alias method = obj.method if detail is None: raise ArgumentError( 'Cannot parse join representation: "{}"' .format(obj) ) master = ColumnObject.parse(master) detail = ColumnObject.parse(detail) return cls(master, detail, alias, method) def __init__(self, master, detail, alias=None, method=None): self.master = master # type: ColumnObject self.detail = detail # type: ColumnObject self.alias = alias # type: str self.method = method # type: str def __str__(self): return '{} -> {}'.format(self.master, self.detail) class TableObject(object): """ "schema", # Database schema "name", # Table name "alias", # Optional table alias instead of name "key", # Table key (for caching or referencing) "table", # SQLAlchemy Table object, reflected "join" # join which joins this table as a detail """ @classmethod def parse(cls, obj): if not obj: raise ArgumentError('Mapping object can not be empty') if isinstance(obj, compat.string_type): obj = obj.split('.') schema = None name = None if isinstance(obj, (tuple, list)): if len(obj) == 1: name = obj[0] schema = None elif len(obj) == 2: schema, name = obj else: raise ArgumentError( 'Table name can have 1 to 2 items (has "{}"): "{}"' .format(len(obj), obj) ) if hasattr(obj, 'get'): schema = obj.get('schema') name = obj.get('name') if name is None: schema = obj.schema name = obj.name if name is None: raise ArgumentError( 'Cannot parse table name representation: "{}"' .format(obj) ) return cls(name=name, schema=schema) def __init__(self, name, alias=None, schema=None, table=None, join=None): self.name = name # type: str self.alias = alias # type: str self.schema = schema # type: str self.table = table # type: sa.Table or sa.Selectable self.join = join # type: JoinObject def __str__(self): if self.schema: return '{}.{}'.format(self.schema, self.name) return self.name @property def key(self): return self.schema, self.alias or self.name def copy_with(self, table): result = copy(self) result.table = table return result class ColumnsContext(object): """Context used for building a list of all columns to be used within a single SQL query.""" def __init__(self, columns): """Creates a SQL expression context. * `bases` is a dictionary of base columns or column expressions * `parameters` is a flag where `True` means that the expression is expected to be an aggregate expression """ if columns: self._columns = dict(columns) else: self._columns = {} @property def columns(self): return self._columns def resolve(self, variable): """Resolve `variable` – return either a column, variable from a dictionary or a SQL constant (in that order).""" if variable in self._columns: return self._columns[variable] raise ValueError( 'Unknown variable "{}"'.format(variable) ) def __getitem__(self, item): return self.resolve(item) def __contains__(self, item): return item in self._columns def add_column(self, name, column): self._columns[name] = column
en
0.775281
# -*- encoding: utf-8 -*- Error related to the physical star schema. Returns a list of columns from `column_key` for `table` representing potentially a compound key. The `column_key` can be a name of a single column or list of column names. Represents a star/snowflake table schema # keys: logical column names # keys: tuples (schema, table physical name) # keys: tuples (schema, table aliased name) " Collect all the detail tables We don't need to collect the master tables as they are expected to be referenced as 'details'. The exception is the fact table that is provided explicitly for the snowflake schema. # alias for fact table Return a table reference for `key` which has form of a tuple (`schema`, `table`). Return a physical table or table expression, regardless whether it exists or not in the star. Return a column for `logical` reference. The returned column will have a label same as the column part of `logical`. Returns implicit physical column reference for `attribute`, which should be an instance of :class:`cubes_lite.model.Attribute`. The returned reference has attributes `schema`, `table`, `column`, `extract`. Return a tuple (schema, table) for attribute. Get all tables that are required to be joined to get `attributes`. `attributes` is a list of `Mapper` attributes (or objects with same kind of attributes). # now we have to resolve all dependencies # plain_dimensions = {a.dimension for a in attributes if a.dimension.is_plain} # if not plain_dimensions: # required.pop(self.root_table_object.key, None) The main method for generating underlying star schema joins. Returns a denormalized JOIN expression that includes all relevant tables containing base `attributes` (attributes representing actual columns). # Dictionary of raw tables and their joined products # At the end this should contain only one item representing the whole # star. # Here the `star` contains mapping table key -> table, which will be # gradually replaced by JOINs # Perform the joins # ================= # # 1. find the column # 2. construct the condition # 3. use the appropriate SQL JOIN # 4. wrap the star with detail # first table does not need to be joined # Get the physical table object (aliased) and already constructed # key (properly aliased) # The `table` here is a detail table to be joined. We need to get # the master table this table joins to: # We need plain tables to get columns for prepare the join # condition. We can't get it form `star`. # Master table.column # Detail table.column # the JOIN ON condition # Determine the join type based on the join method. If the method # is "detail" then we need to swap the order of the tables # (products), because SQLAlchemy provides inteface only for # left-outer join. # Swap the master and detail tables to perform RIGHT OUTER JOIN # Consume the detail # The table is consumed by the join product, becomes the join # product itself. # dependency resolution # maximum number of iterations: the worst case # all dependencies already in context # construct all aggregates with its dependencies # in reverse-dependency order Physical column reference. `schema` is a database schema name, `table` is a table name containing the `column`. `extract` is an element to be extracted from complex data type such as date or JSON (in postgres). `function` is name of unary function to be applied on the `column`. Utility function that will create a `Column` reference object from an anonymous tuple, dictionary or a similar object. `obj` can also be a string in form ``schema.table.column`` where shcema or both schema and table can be ommited. `default_table` and `default_schema` are used when no table or schema is provided in `obj`. # type: str # type: str # type: str # type: str # type: str Table join specification. `master` and `detail` are ColumnObjects. `method` - denotes which table members should be considered in the join: *master* - all master members (left outer join) *detail* - all detail members (right outer join) *match* - members must match (inner join). # type: ColumnObject # type: ColumnObject # type: str # type: str "schema", # Database schema "name", # Table name "alias", # Optional table alias instead of name "key", # Table key (for caching or referencing) "table", # SQLAlchemy Table object, reflected "join" # join which joins this table as a detail # type: str # type: str # type: str # type: sa.Table or sa.Selectable # type: JoinObject Context used for building a list of all columns to be used within a single SQL query. Creates a SQL expression context. * `bases` is a dictionary of base columns or column expressions * `parameters` is a flag where `True` means that the expression is expected to be an aggregate expression Resolve `variable` – return either a column, variable from a dictionary or a SQL constant (in that order).
2.225583
2
app_functions.py
johngncook/red-jake
0
6613239
import pyttsx3 import datetime import speech_recognition as sr import wolframalpha engine = pyttsx3.init('sapi5') app_id = 'L73LGW-35VJW9WY6J' client = wolframalpha.Client(app_id) voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) def speak(audio): engine.say(audio) engine.runAndWait() def greet(): """Greets user depending on time of day.""" hour = int(datetime.datetime.now().hour) if hour >= 0 and hour < 12: speak ("Good Morning!") elif hour >= 12 and hour <18: speak("Good Afternoon") else: speak("Good Evening!") speak(" I am <NAME>ir. Red Jake. How may I help you today?") def take_command(): """Takes microphone input and returns string output.""" r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 r.adjust_for_ambient_noise(source, duration=1) audio = r.listen(source) try: print("Recognizing....") query = r.recognize_google(audio) print(f"User said: {query}\n") except Exception as e: #print(e) print("Say that again please...") return "None" return query
import pyttsx3 import datetime import speech_recognition as sr import wolframalpha engine = pyttsx3.init('sapi5') app_id = 'L73LGW-35VJW9WY6J' client = wolframalpha.Client(app_id) voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) def speak(audio): engine.say(audio) engine.runAndWait() def greet(): """Greets user depending on time of day.""" hour = int(datetime.datetime.now().hour) if hour >= 0 and hour < 12: speak ("Good Morning!") elif hour >= 12 and hour <18: speak("Good Afternoon") else: speak("Good Evening!") speak(" I am <NAME>ir. Red Jake. How may I help you today?") def take_command(): """Takes microphone input and returns string output.""" r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 r.adjust_for_ambient_noise(source, duration=1) audio = r.listen(source) try: print("Recognizing....") query = r.recognize_google(audio) print(f"User said: {query}\n") except Exception as e: #print(e) print("Say that again please...") return "None" return query
en
0.703937
Greets user depending on time of day. Takes microphone input and returns string output. #print(e)
3.25522
3
TencentWPC2019/practice/A_Lucky_7.py
zh-plus/CodeJam
3
6613240
<reponame>zh-plus/CodeJam<filename>TencentWPC2019/practice/A_Lucky_7.py read_int = lambda: int(input()) read_ints = lambda: list(map(int, input().split())) def solve(A, b): for a in A: if not (a + b) % 7: return 'Yes' return 'No' if __name__ == '__main__': T = read_int() for i in range(T): n, b = read_ints() A = read_ints() result = solve(A, b) print(result, end='\n' if i != T - 1 else '')
read_int = lambda: int(input()) read_ints = lambda: list(map(int, input().split())) def solve(A, b): for a in A: if not (a + b) % 7: return 'Yes' return 'No' if __name__ == '__main__': T = read_int() for i in range(T): n, b = read_ints() A = read_ints() result = solve(A, b) print(result, end='\n' if i != T - 1 else '')
none
1
3.482065
3
papermerge/core/ocr/document.py
papermerge/papermerge-core
45
6613241
import os import logging import ocrmypdf from papermerge.core.storage import default_storage from papermerge.core.lib import mime from papermerge.core.lib.tiff import convert_tiff2pdf from papermerge.core.lib.path import ( DocumentPath, ) logger = logging.getLogger(__name__) STARTED = "started" COMPLETE = "complete" def notify_hocr_ready(page_path, **kwargs): pass def notify_txt_ready(page_path, **kwargs): pass def notify_pre_page_ocr(page_path, **kwargs): pass def _ocr_document( input_doc_path: DocumentPath, target_doc_path, lang, preview_width, ): # file_name = kwargs.pop('file_name', None) # if not file_name: # input_file_name = input_doc_path.file_name sidecars_dir = default_storage.abspath( target_doc_path.dirname_sidecars() ) input_document = default_storage.abspath( input_doc_path.path() ) output_document = default_storage.abspath( target_doc_path.path() ) output_dir = os.path.dirname(output_document) if not os.path.exists(output_dir): os.makedirs( output_dir, exist_ok=True ) ocrmypdf.ocr( input_document, output_document, lang=lang, plugins=["ocrmypdf_papermerge.plugin"], progress_bar=False, pdf_renderer='hocr', use_threads=True, keep_temporary_files=False, sidecar_dir=sidecars_dir, sidecar_format='svg', preview_width=preview_width ) def ocr_document( user_id, document_id, file_name, lang, version, target_version, namespace='', ): lang = lang.lower() doc_path = DocumentPath( user_id=user_id, document_id=document_id, file_name=file_name, version=version ) target_doc_path = DocumentPath.copy_from( doc_path, version=target_version ) mime_type = mime.Mime( default_storage.abspath(doc_path.url()) ) if mime_type.is_pdf() or mime_type.is_image(): _ocr_document( input_doc_path=doc_path, target_doc_path=target_doc_path, lang=lang, preview_width=300 ) elif mime_type.is_tiff(): new_filename = convert_tiff2pdf( doc_url=default_storage.abspath(doc_path.url()) ) # now .pdf orig_file_name = doc_path.file_name doc_path.file_name = new_filename # and continue as usual _ocr_document( doc_path=doc_path, lang=lang, user_id=user_id, document_id=document_id, # Pass original file_name i.e. tiff file name as well. file_name=orig_file_name, namespace=namespace, version=version ) else: logger.error( f" user_id={user_id}" f" doc_id={document_id}" ) return True return True
import os import logging import ocrmypdf from papermerge.core.storage import default_storage from papermerge.core.lib import mime from papermerge.core.lib.tiff import convert_tiff2pdf from papermerge.core.lib.path import ( DocumentPath, ) logger = logging.getLogger(__name__) STARTED = "started" COMPLETE = "complete" def notify_hocr_ready(page_path, **kwargs): pass def notify_txt_ready(page_path, **kwargs): pass def notify_pre_page_ocr(page_path, **kwargs): pass def _ocr_document( input_doc_path: DocumentPath, target_doc_path, lang, preview_width, ): # file_name = kwargs.pop('file_name', None) # if not file_name: # input_file_name = input_doc_path.file_name sidecars_dir = default_storage.abspath( target_doc_path.dirname_sidecars() ) input_document = default_storage.abspath( input_doc_path.path() ) output_document = default_storage.abspath( target_doc_path.path() ) output_dir = os.path.dirname(output_document) if not os.path.exists(output_dir): os.makedirs( output_dir, exist_ok=True ) ocrmypdf.ocr( input_document, output_document, lang=lang, plugins=["ocrmypdf_papermerge.plugin"], progress_bar=False, pdf_renderer='hocr', use_threads=True, keep_temporary_files=False, sidecar_dir=sidecars_dir, sidecar_format='svg', preview_width=preview_width ) def ocr_document( user_id, document_id, file_name, lang, version, target_version, namespace='', ): lang = lang.lower() doc_path = DocumentPath( user_id=user_id, document_id=document_id, file_name=file_name, version=version ) target_doc_path = DocumentPath.copy_from( doc_path, version=target_version ) mime_type = mime.Mime( default_storage.abspath(doc_path.url()) ) if mime_type.is_pdf() or mime_type.is_image(): _ocr_document( input_doc_path=doc_path, target_doc_path=target_doc_path, lang=lang, preview_width=300 ) elif mime_type.is_tiff(): new_filename = convert_tiff2pdf( doc_url=default_storage.abspath(doc_path.url()) ) # now .pdf orig_file_name = doc_path.file_name doc_path.file_name = new_filename # and continue as usual _ocr_document( doc_path=doc_path, lang=lang, user_id=user_id, document_id=document_id, # Pass original file_name i.e. tiff file name as well. file_name=orig_file_name, namespace=namespace, version=version ) else: logger.error( f" user_id={user_id}" f" doc_id={document_id}" ) return True return True
en
0.702598
# file_name = kwargs.pop('file_name', None) # if not file_name: # input_file_name = input_doc_path.file_name # now .pdf # and continue as usual # Pass original file_name i.e. tiff file name as well.
2.272609
2
Secao8_FuncoesPython/DocumentandoFuncoesComDocStrings.py
PauloFTeixeira/curso_python
0
6613242
""" Um comentário entre aspas tripla é uma DocString """ # Exemplo de DocString def diz_oi(): """ Está função vai trazer uma variável no retorno :return: Oi """ return 'Oi!' print(diz_oi()) def meu_nome(nome='Paulo', sobrenome='Teixeira'): """ Função para cadastro de sobrenome :param nome: Digite seu nome :param sobrenome: Digite seu sobrenome :return: uma tupla com o nome e sobrenome """ return nome, sobrenome print(meu_nome()) # Obs.: Pode-se acessar a documentação de uma função usando a propriedade especial .__doc__ print(meu_nome.__doc__)
""" Um comentário entre aspas tripla é uma DocString """ # Exemplo de DocString def diz_oi(): """ Está função vai trazer uma variável no retorno :return: Oi """ return 'Oi!' print(diz_oi()) def meu_nome(nome='Paulo', sobrenome='Teixeira'): """ Função para cadastro de sobrenome :param nome: Digite seu nome :param sobrenome: Digite seu sobrenome :return: uma tupla com o nome e sobrenome """ return nome, sobrenome print(meu_nome()) # Obs.: Pode-se acessar a documentação de uma função usando a propriedade especial .__doc__ print(meu_nome.__doc__)
pt
0.998372
Um comentário entre aspas tripla é uma DocString # Exemplo de DocString Está função vai trazer uma variável no retorno :return: Oi Função para cadastro de sobrenome :param nome: Digite seu nome :param sobrenome: Digite seu sobrenome :return: uma tupla com o nome e sobrenome # Obs.: Pode-se acessar a documentação de uma função usando a propriedade especial .__doc__
3.526867
4
problems/A/LCMProblem.py
deveshbajpai19/CodeForces
55
6613243
<gh_stars>10-100 __author__ = '<NAME>' ''' https://codeforces.com/problemset/problem/1389/A Solution: LCM(a,b) is the lowest multiple of the a and b. To fit a and b in a prescribed range, a simple greedy strategy can be to take the smallest multiple of the smaller number which is greater than itself. Say a < b. a * 1 returns a, hence the smallest multiple of a which is not equal to a would be a * 2. If we cannot accommodate this in the range, the solution is impossible and we default to -1. ''' def solve(l, r): if l * 2 <= r: result = [l, l * 2] else: result = [-1, -1] return str(result[0]) + " " + str(result[1]) if __name__ == "__main__": t = int(raw_input()) results = list() for _ in xrange(0, t): l, r = map(int, raw_input().split(" ")) results.append(solve(l, r)) for result in results: print result
__author__ = '<NAME>' ''' https://codeforces.com/problemset/problem/1389/A Solution: LCM(a,b) is the lowest multiple of the a and b. To fit a and b in a prescribed range, a simple greedy strategy can be to take the smallest multiple of the smaller number which is greater than itself. Say a < b. a * 1 returns a, hence the smallest multiple of a which is not equal to a would be a * 2. If we cannot accommodate this in the range, the solution is impossible and we default to -1. ''' def solve(l, r): if l * 2 <= r: result = [l, l * 2] else: result = [-1, -1] return str(result[0]) + " " + str(result[1]) if __name__ == "__main__": t = int(raw_input()) results = list() for _ in xrange(0, t): l, r = map(int, raw_input().split(" ")) results.append(solve(l, r)) for result in results: print result
en
0.901002
https://codeforces.com/problemset/problem/1389/A Solution: LCM(a,b) is the lowest multiple of the a and b. To fit a and b in a prescribed range, a simple greedy strategy can be to take the smallest multiple of the smaller number which is greater than itself. Say a < b. a * 1 returns a, hence the smallest multiple of a which is not equal to a would be a * 2. If we cannot accommodate this in the range, the solution is impossible and we default to -1.
3.643717
4
examples/plot-multi-region.py
lukasz-migas/napari-1d
13
6613244
<gh_stars>10-100 """Multiple infinite regions in a single layer.""" import napari_plot import numpy as np viewer1d = napari_plot.Viewer() viewer1d.add_line(np.c_[np.arange(100), np.random.randint(0, 1000, 100)], name="line") regions = [ ([25, 50], "vertical"), ([500, 750], "horizontal"), ([80, 90], "vertical"), ] layer = viewer1d.add_region( regions, face_color=["red", "green", "yellow"], opacity=0.5, name="Infinite Region", ) napari_plot.run()
"""Multiple infinite regions in a single layer.""" import napari_plot import numpy as np viewer1d = napari_plot.Viewer() viewer1d.add_line(np.c_[np.arange(100), np.random.randint(0, 1000, 100)], name="line") regions = [ ([25, 50], "vertical"), ([500, 750], "horizontal"), ([80, 90], "vertical"), ] layer = viewer1d.add_region( regions, face_color=["red", "green", "yellow"], opacity=0.5, name="Infinite Region", ) napari_plot.run()
en
0.823267
Multiple infinite regions in a single layer.
3.127364
3
fem/boundary_conditions.py
PaulStryck/fem
0
6613245
<gh_stars>0 from typing import Callable, Optional, Tuple, Union import numpy as np import numpy.typing as npt from scipy.sparse.coo import coo_matrix from fem.fefunction import FEFunction from fem.function_space import FEFunctionSpace BoundaryCondition = Tuple[Callable, FEFunctionSpace] def asm_dirichlet_boundary( bc: Optional[BoundaryCondition], outer_dim: int ): if bc is None: return None, None f, fs = bc b_f = FEFunction(fs) b_f.interpolate(f) l = fs.dim R = coo_matrix( (np.ones(l), (b_f.embedded_coeffs_indices, np.arange(l))), shape=(outer_dim, l) ) return R, b_f.embedded_coeffs_indices, b_f.embedded_coeffs_values def asm_neumann_boundary(bc: BoundaryCondition) -> npt.NDArray: f, fs = bc # compute projection of BC Function _f = FEFunction(fs) _f.interpolate(f) _, M = fs.asm_stiff_mass(stiff=False, mass=True) if M is None: raise ValueError() # Filtering, in case its a SubMesh f_repr = np.zeros(M.shape[0]) f_repr[_f.embedded_coeffs_indices] = _f.embedded_coeffs_values return M@f_repr
from typing import Callable, Optional, Tuple, Union import numpy as np import numpy.typing as npt from scipy.sparse.coo import coo_matrix from fem.fefunction import FEFunction from fem.function_space import FEFunctionSpace BoundaryCondition = Tuple[Callable, FEFunctionSpace] def asm_dirichlet_boundary( bc: Optional[BoundaryCondition], outer_dim: int ): if bc is None: return None, None f, fs = bc b_f = FEFunction(fs) b_f.interpolate(f) l = fs.dim R = coo_matrix( (np.ones(l), (b_f.embedded_coeffs_indices, np.arange(l))), shape=(outer_dim, l) ) return R, b_f.embedded_coeffs_indices, b_f.embedded_coeffs_values def asm_neumann_boundary(bc: BoundaryCondition) -> npt.NDArray: f, fs = bc # compute projection of BC Function _f = FEFunction(fs) _f.interpolate(f) _, M = fs.asm_stiff_mass(stiff=False, mass=True) if M is None: raise ValueError() # Filtering, in case its a SubMesh f_repr = np.zeros(M.shape[0]) f_repr[_f.embedded_coeffs_indices] = _f.embedded_coeffs_values return M@f_repr
en
0.889206
# compute projection of BC Function # Filtering, in case its a SubMesh
2.283427
2
pymultifracs/bivariate/__init__.py
MerlinDumeur/pymultifracs
9
6613246
from .bimfa import bivariate_analysis, bivariate_analysis_full __all__ = ['bivariate_analysis', 'bivariate_analysis_full']
from .bimfa import bivariate_analysis, bivariate_analysis_full __all__ = ['bivariate_analysis', 'bivariate_analysis_full']
none
1
0.994998
1
TaskScheduler/models.py
nirabhratapaswi/Task-Scheduler
3
6613247
from django.db import models from django.utils import timezone import datetime # Create your models here. class Task(models.Model): def __str__(self): return self.name + " (" + str(self.priority) + ")" choices = (("0", "Low"), ("1", "Medium"), ("2", "High")) name = models.CharField(max_length=200) priority = models.CharField(max_length=10, default="0", choices=choices) # 0->low 1-> medium 2-> high span = models.IntegerField(default=60) deadline = models.DateTimeField(default=(timezone.now()+timezone.timedelta(minutes=10*60))) at_a_stretch = models.IntegerField(default=60) # how much time you need to do this task once started (in one sitting) left = models.IntegerField(default=60) # time left to complete the task done = models.BooleanField(default=False) max_repeats_per_day = models.IntegerField(default=4) times_repeated_today = models.IntegerField(default=0) break_needed_afterwards = models.IntegerField(default=15) class Schedule(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) start_time = models.DateTimeField(default=timezone.now()+timezone.timedelta(minutes=60)) end_time = models.DateTimeField(default=(timezone.now()+timezone.timedelta(minutes=10*60))) done = models.BooleanField(default=True) class Blocked(models.Model): # Specially booked time slots def __str__(self): return self.name name = models.CharField(max_length=200, default=None) start_time = models.DateTimeField(default=timezone.now()+timezone.timedelta(minutes=60)) end_time = models.DateTimeField(default=(timezone.now()+timezone.timedelta(minutes=10*60))) class WeeklySchedule(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) start_time = models.TimeField(default=(timezone.now()+timezone.timedelta(minutes=60)).time()) end_time = models.TimeField(default=(timezone.now()+timezone.timedelta(minutes=10*60)).time()) minimum_time_to_devote = models.IntegerField(default=30) hard_bound = models.BooleanField(default=True) class DaysRepeated(models.Model): weekly_schedule = models.ForeignKey(WeeklySchedule, on_delete=models.CASCADE) day_index = models.IntegerField(default=0)
from django.db import models from django.utils import timezone import datetime # Create your models here. class Task(models.Model): def __str__(self): return self.name + " (" + str(self.priority) + ")" choices = (("0", "Low"), ("1", "Medium"), ("2", "High")) name = models.CharField(max_length=200) priority = models.CharField(max_length=10, default="0", choices=choices) # 0->low 1-> medium 2-> high span = models.IntegerField(default=60) deadline = models.DateTimeField(default=(timezone.now()+timezone.timedelta(minutes=10*60))) at_a_stretch = models.IntegerField(default=60) # how much time you need to do this task once started (in one sitting) left = models.IntegerField(default=60) # time left to complete the task done = models.BooleanField(default=False) max_repeats_per_day = models.IntegerField(default=4) times_repeated_today = models.IntegerField(default=0) break_needed_afterwards = models.IntegerField(default=15) class Schedule(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) start_time = models.DateTimeField(default=timezone.now()+timezone.timedelta(minutes=60)) end_time = models.DateTimeField(default=(timezone.now()+timezone.timedelta(minutes=10*60))) done = models.BooleanField(default=True) class Blocked(models.Model): # Specially booked time slots def __str__(self): return self.name name = models.CharField(max_length=200, default=None) start_time = models.DateTimeField(default=timezone.now()+timezone.timedelta(minutes=60)) end_time = models.DateTimeField(default=(timezone.now()+timezone.timedelta(minutes=10*60))) class WeeklySchedule(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) start_time = models.TimeField(default=(timezone.now()+timezone.timedelta(minutes=60)).time()) end_time = models.TimeField(default=(timezone.now()+timezone.timedelta(minutes=10*60)).time()) minimum_time_to_devote = models.IntegerField(default=30) hard_bound = models.BooleanField(default=True) class DaysRepeated(models.Model): weekly_schedule = models.ForeignKey(WeeklySchedule, on_delete=models.CASCADE) day_index = models.IntegerField(default=0)
en
0.914007
# Create your models here. # 0->low 1-> medium 2-> high # how much time you need to do this task once started (in one sitting) # time left to complete the task # Specially booked time slots
2.413184
2
lycheepy/wps/wps/adapter/executable_adapter.py
gabrielbazan/lycheepy
17
6613248
<filename>lycheepy/wps/wps/adapter/executable_adapter.py from pywps import Process from executor import Executor from gateways.broker.serialization import OutputsDeserializer class ExecutableAdapter(Process): def __init__(self, inputs, outputs, identifier, version, title, abstract, model, is_chain=False): super(ExecutableAdapter, self).__init__( self._handle, identifier=identifier, version=version, title=title, abstract=abstract, profile='', inputs=inputs, outputs=outputs, store_supported=True, status_supported=True ) self.model = model self.is_chain = is_chain def _handle(self, request, response): executor = Executor() if self.is_chain: outputs = executor.execute_chain(self.model, request, self.uuid) else: outputs = executor.execute_process(self.identifier, request) for output in self.outputs: output_identifier = output.identifier for result_output in outputs.get(output_identifier): OutputsDeserializer.add_data(result_output, response.outputs.get(output_identifier)) return response def clean(self): pass
<filename>lycheepy/wps/wps/adapter/executable_adapter.py from pywps import Process from executor import Executor from gateways.broker.serialization import OutputsDeserializer class ExecutableAdapter(Process): def __init__(self, inputs, outputs, identifier, version, title, abstract, model, is_chain=False): super(ExecutableAdapter, self).__init__( self._handle, identifier=identifier, version=version, title=title, abstract=abstract, profile='', inputs=inputs, outputs=outputs, store_supported=True, status_supported=True ) self.model = model self.is_chain = is_chain def _handle(self, request, response): executor = Executor() if self.is_chain: outputs = executor.execute_chain(self.model, request, self.uuid) else: outputs = executor.execute_process(self.identifier, request) for output in self.outputs: output_identifier = output.identifier for result_output in outputs.get(output_identifier): OutputsDeserializer.add_data(result_output, response.outputs.get(output_identifier)) return response def clean(self): pass
none
1
2.367033
2
yuzhouwan-bigdata/yuzhouwan-bigdata-hbase/src/main/python/acl/AclParser.py
Celebrate-future/yuzhouwan
44
6613249
# !/usr/bin/env python # -*- coding:utf-8 -*- table_permission = {} # echo "scan 'hbase:acl'" | hbase shell > acl.txt for line in open("acl.txt"): info = line.strip().rstrip().split(",") if len(info) == 3: table = info[0] table_info = table.split(" ") acl = info[2].strip(" value=") if len(table_info) == 2: table_name = table_info[0] user_name = table_info[1].split("column=l:") if len(user_name) == 2: user_name = user_name[1] if user_name != 'hbase': # remove hbase user if table_name in table_permission: table_permission[table_name].append([user_name, acl]) else: table_permission[table_name] = [[user_name, acl]] table_permission_right = {} table_permission_wrong = {} table_permission_wrong_namespace = {} for table_name in table_permission: namespace_table = table_name.split(":") if len(namespace_table) == 2: namespace = namespace_table[0].split("ns_") if len(namespace) == 2: namespace = namespace[1] user_name_acl = table_permission[table_name] if len(user_name_acl) == 1: if user_name_acl[0][0] == namespace: table_permission_right[table_name] = user_name_acl else: # table_permission_wrong[table_name] = user_name_acl table_permission_wrong_namespace[table_name] = user_name_acl else: is_wrong = False for acl in user_name_acl: if acl[0] != namespace and ('W' in acl[1] or 'A' in acl[1]): # across user write is_wrong = True break if is_wrong: table_permission_wrong[table_name] = user_name_acl else: table_permission_right[table_name] = user_name_acl print "# Permission Right Tables" for table_name in table_permission_right: print table_name, table_permission_right[table_name] print "\n\n\n" print "# Permission Wrong Tables" print "\n" print "## Wrong UserName" for table_name in table_permission_wrong_namespace: print table_name, table_permission_wrong_namespace[table_name] print "\n\n\n" print "## Cross User Write" for table_name in table_permission_wrong: print table_name, table_permission_wrong[table_name] print "\n\n\n" table_permission_abnormal_namespace_level = {} table_permission_abnormal_without_namespace = {} table_permission_abnormal_others = {} print "# Abnormal Tables" for table_name in table_permission: if table_name not in table_permission_right and table_name not in table_permission_wrong \ and table_name not in table_permission_wrong_namespace: if table_name.startswith("@"): # namespace level permission table_permission_abnormal_namespace_level[table_name] = table_permission[table_name] elif ':' not in table_name: table_permission_abnormal_without_namespace[table_name] = table_permission[table_name] else: table_permission_abnormal_others[table_name] = table_permission[table_name] print "\n" print "## Namespace Level" for table_name in table_permission_abnormal_namespace_level: print table_name, table_permission_abnormal_namespace_level[table_name] print "\n\n\n" print "## Without Namespace" for table_name in table_permission_abnormal_without_namespace: print table_name, table_permission_abnormal_without_namespace[table_name] print "\n\n\n" print "# Others" for table_name in table_permission_abnormal_others: print table_name, table_permission_abnormal_others[table_name] print "\n# Result" right_num = len(table_permission_right) wrong_username_num = len(table_permission_wrong) wrong_cross_user_num = len(table_permission_wrong_namespace) wrong_num = wrong_username_num + wrong_cross_user_num all_num = len(table_permission) abnormal_num = all_num - right_num - wrong_num abnormal_namespace_level = len(table_permission_abnormal_namespace_level) abnormal_without_namespace = len(table_permission_abnormal_without_namespace) abnormal_others = len(table_permission_abnormal_others) print "Right : Wrong(username/cross-user) : Abnormal(namespace/without_namespace/other) : " \ "All = %d : %d (%d/%d) : %d (%d/%d/%d) : %d" % \ (right_num, wrong_num, wrong_username_num, wrong_cross_user_num, abnormal_num, abnormal_namespace_level, abnormal_without_namespace, abnormal_others, all_num)
# !/usr/bin/env python # -*- coding:utf-8 -*- table_permission = {} # echo "scan 'hbase:acl'" | hbase shell > acl.txt for line in open("acl.txt"): info = line.strip().rstrip().split(",") if len(info) == 3: table = info[0] table_info = table.split(" ") acl = info[2].strip(" value=") if len(table_info) == 2: table_name = table_info[0] user_name = table_info[1].split("column=l:") if len(user_name) == 2: user_name = user_name[1] if user_name != 'hbase': # remove hbase user if table_name in table_permission: table_permission[table_name].append([user_name, acl]) else: table_permission[table_name] = [[user_name, acl]] table_permission_right = {} table_permission_wrong = {} table_permission_wrong_namespace = {} for table_name in table_permission: namespace_table = table_name.split(":") if len(namespace_table) == 2: namespace = namespace_table[0].split("ns_") if len(namespace) == 2: namespace = namespace[1] user_name_acl = table_permission[table_name] if len(user_name_acl) == 1: if user_name_acl[0][0] == namespace: table_permission_right[table_name] = user_name_acl else: # table_permission_wrong[table_name] = user_name_acl table_permission_wrong_namespace[table_name] = user_name_acl else: is_wrong = False for acl in user_name_acl: if acl[0] != namespace and ('W' in acl[1] or 'A' in acl[1]): # across user write is_wrong = True break if is_wrong: table_permission_wrong[table_name] = user_name_acl else: table_permission_right[table_name] = user_name_acl print "# Permission Right Tables" for table_name in table_permission_right: print table_name, table_permission_right[table_name] print "\n\n\n" print "# Permission Wrong Tables" print "\n" print "## Wrong UserName" for table_name in table_permission_wrong_namespace: print table_name, table_permission_wrong_namespace[table_name] print "\n\n\n" print "## Cross User Write" for table_name in table_permission_wrong: print table_name, table_permission_wrong[table_name] print "\n\n\n" table_permission_abnormal_namespace_level = {} table_permission_abnormal_without_namespace = {} table_permission_abnormal_others = {} print "# Abnormal Tables" for table_name in table_permission: if table_name not in table_permission_right and table_name not in table_permission_wrong \ and table_name not in table_permission_wrong_namespace: if table_name.startswith("@"): # namespace level permission table_permission_abnormal_namespace_level[table_name] = table_permission[table_name] elif ':' not in table_name: table_permission_abnormal_without_namespace[table_name] = table_permission[table_name] else: table_permission_abnormal_others[table_name] = table_permission[table_name] print "\n" print "## Namespace Level" for table_name in table_permission_abnormal_namespace_level: print table_name, table_permission_abnormal_namespace_level[table_name] print "\n\n\n" print "## Without Namespace" for table_name in table_permission_abnormal_without_namespace: print table_name, table_permission_abnormal_without_namespace[table_name] print "\n\n\n" print "# Others" for table_name in table_permission_abnormal_others: print table_name, table_permission_abnormal_others[table_name] print "\n# Result" right_num = len(table_permission_right) wrong_username_num = len(table_permission_wrong) wrong_cross_user_num = len(table_permission_wrong_namespace) wrong_num = wrong_username_num + wrong_cross_user_num all_num = len(table_permission) abnormal_num = all_num - right_num - wrong_num abnormal_namespace_level = len(table_permission_abnormal_namespace_level) abnormal_without_namespace = len(table_permission_abnormal_without_namespace) abnormal_others = len(table_permission_abnormal_others) print "Right : Wrong(username/cross-user) : Abnormal(namespace/without_namespace/other) : " \ "All = %d : %d (%d/%d) : %d (%d/%d/%d) : %d" % \ (right_num, wrong_num, wrong_username_num, wrong_cross_user_num, abnormal_num, abnormal_namespace_level, abnormal_without_namespace, abnormal_others, all_num)
en
0.444642
# !/usr/bin/env python # -*- coding:utf-8 -*- # echo "scan 'hbase:acl'" | hbase shell > acl.txt # remove hbase user # table_permission_wrong[table_name] = user_name_acl # across user write # Wrong UserName" # Cross User Write" # namespace level permission # Namespace Level" # Without Namespace" # Result"
2.967141
3
portable_spreadsheet/word_constructor.py
david-salac/Portable-spreadsheet-generator
28
6613250
<filename>portable_spreadsheet/word_constructor.py import copy from numbers import Number from typing import Dict, Set, Tuple, TYPE_CHECKING from .grammars import GRAMMARS from .cell_indices import CellIndices from .cell_type import CellType if TYPE_CHECKING: from .cell import Cell from .sheet import Sheet # ==== TYPES ==== # Type for the word of some language, logic: key: language, value: word T_word = Dict[str, str] # =============== class WordConstructor(object): """Provides functionality for constructing words in all supported languages and also serves container for keeping them. Attributes: languages (Set[str]): What languages are used. words (Dict[str, str]): Mapping from language name to word. """ def __init__(self, *, words: T_word = None, languages: Set[str] = None, cell_indices: CellIndices ): """Initialise the word cunstructor. Args: languages (Set[str]): What languages are used. words (Dict[str, str]): Mapping from language name to word. """ if languages is not None: self.languages: Set[str] = languages else: self.languages: Set[str] = set(cell_indices.languages) if words is not None: self.words: T_word = words else: self.words: T_word = {key: "" for key in self.languages} @staticmethod def init_from_new_cell(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Initialise the words when the new cell is created. Args: cell (Cell): just created cell. Returns: WordConstructor: words for the new cell. """ if cell.value is not None: # Value type cell return WordConstructor.constant(cell) else: # Empty cell return WordConstructor(cell_indices=cell.cell_indices) @staticmethod def _binary_operation(first: 'Cell', second: 'Cell', operation: str) -> 'WordConstructor': """General binary operation. Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. operation (str): Definition of the operation (in grammar). Returns: WordConstructor: Word constructed using binary operator and two operands. """ instance = copy.deepcopy(first.word) first_words = first.word.words second_word = second.word.words for language in instance.languages: pref = GRAMMARS[language]['operations'][operation]['prefix'] suff = GRAMMARS[language]['operations'][operation]['suffix'] sp = GRAMMARS[language]['operations'][operation]['separator'] instance.words[language] = pref + first_words[language] + sp \ + second_word[language] + suff return instance @staticmethod def add(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add binary operation (+). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "add") @staticmethod def subtract(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Subtract binary operation (-). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "subtract") @staticmethod def multiply(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Multiply binary operation (*). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "multiply") @staticmethod def divide(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Divide binary operation (/). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "divide") @staticmethod def modulo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Modulo binary operation (%). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "modulo") @staticmethod def power(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Power binary operation (**). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "power") @staticmethod def logicalConjunction(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Logical conjunction operation (and). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "logical-conjunction") @staticmethod def logicalDisjunction(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Logical disjunction operation (or). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "logical-disjunction") @staticmethod def equalTo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Equal to binary operation (==). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "equal-to") @staticmethod def notEqualTo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Not equal to binary operation (!=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "not-equal-to") @staticmethod def greaterThan(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Greater than binary operation (>). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "greater-than") @staticmethod def greaterThanOrEqualTo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Greater than or equal to binary operation (>=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "greater-than-or-equal-to") @staticmethod def lessThan(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Less than binary operation (<). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "less-than") @staticmethod def lessThanOrEqualTo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Less than or equal to binary operation (<=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "less-than-or-equal-to") @staticmethod def concatenate(first: 'Cell', second: 'Cell') -> 'WordConstructor': """Concatenate values as two strings and create a word. Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator concatenate and two operands. """ # Inline function for appending context to inputs def _generate_word_string_concatenate( in_cell: 'Cell') -> T_word: """Generate word for each operand. Args: in_cell (Cell): Input cell. Returns: T_word: Words for each language. """ if in_cell.anchored: return WordConstructor.reference(in_cell).words else: if in_cell.cell_type == CellType.computational: return in_cell._constructing_words.words elif in_cell.cell_type == CellType.value_only: words: T_word = {} for language in in_cell.word.languages: if isinstance(in_cell.value, str): pref = GRAMMARS[language]['operations'][ 'concatenate']['string-value']['prefix'] suff = GRAMMARS[language]['operations'][ 'concatenate']['string-value']['suffix'] words[language] = pref + str(in_cell.value) + suff if isinstance(in_cell.value, Number): pref = GRAMMARS[language]['operations'][ 'concatenate']['numeric-value']['prefix'] suff = GRAMMARS[language]['operations'][ 'concatenate']['numeric-value']['suffix'] words[language] = pref + str(in_cell.value) + suff return words instance = copy.deepcopy(first.word) first_words = _generate_word_string_concatenate(first) second_word = _generate_word_string_concatenate(second) for language in instance.languages: pref = GRAMMARS[language]['operations']['concatenate']['prefix'] suff = GRAMMARS[language]['operations']['concatenate']['suffix'] sp = GRAMMARS[language]['operations']['concatenate']['separator'] instance.words[language] = pref + first_words[language] + sp \ + second_word[language] + suff return instance @staticmethod def _aggregation_parse_cell(cell: 'Cell', start_idx: Tuple[int, int], end_idx: Tuple[int, int], language: str ) -> Tuple[str, str]: """Generates the aggregation string for a concrete language (regardless what aggregation method is selected). Args: cell (Cell): Any cell in the set (used for extracting indicies). start_idx (Tuple[int, int]): Position of the slice start. end_idx (Tuple[int, int]): Position of the slice end. language (str): What language is used. Returns: Tuple[str, str]: Definition of starting, ending cell in language. """ # Does the language include the last cell? # if yes, offset of size 1 has to be included. offset = 0 if GRAMMARS[ language ]['cells']['aggregation']['include_last_cell']: offset = 1 start_idx_r = cell.cell_indices.rows[language][start_idx[0]] start_idx_c = cell.cell_indices.columns[language][start_idx[1]] end_idx_r = cell.cell_indices.rows[language][end_idx[0] + offset] end_idx_c = cell.cell_indices.columns[language][end_idx[1] + offset] pref_cell_start = GRAMMARS[language]['cells']['aggregation'][ 'start_cell']['prefix'] separator_cell_start = GRAMMARS[language]['cells']['aggregation'][ 'start_cell']['separator'] suffix_cell_start = GRAMMARS[language]['cells']['aggregation'][ 'start_cell']['suffix'] if GRAMMARS[language]['cells']['aggregation']['start_cell'][ 'row_first' ]: cell_start = (pref_cell_start + start_idx_r + separator_cell_start + start_idx_c + suffix_cell_start) else: cell_start = (pref_cell_start + start_idx_c + separator_cell_start + start_idx_r + suffix_cell_start) if GRAMMARS[language]['cells']['aggregation']['start_cell'][ 'rows_only' ]: cell_start = (pref_cell_start + start_idx_r + separator_cell_start + end_idx_r + suffix_cell_start) elif GRAMMARS[language]['cells']['aggregation']['start_cell'][ 'cols_only' ]: cell_start = (pref_cell_start + start_idx_c + separator_cell_start + end_idx_c + suffix_cell_start) # ---------- ending cell ----- pref_cell_end = GRAMMARS[language]['cells']['aggregation'][ 'end_cell']['prefix'] separator_cell_end = GRAMMARS[language]['cells']['aggregation'][ 'end_cell']['separator'] suffix_cell_end = GRAMMARS[language]['cells']['aggregation'][ 'end_cell']['suffix'] if GRAMMARS[language]['cells']['aggregation']['end_cell'][ 'row_first' ]: cell_end = (pref_cell_end + end_idx_r + separator_cell_end + end_idx_c + suffix_cell_end) else: cell_end = (pref_cell_end + end_idx_c + separator_cell_end + end_idx_r + suffix_cell_end) if GRAMMARS[language]['cells']['aggregation']['end_cell'][ 'rows_only' ]: cell_end = (pref_cell_end + start_idx_r + separator_cell_end + end_idx_r + suffix_cell_end) elif GRAMMARS[language]['cells']['aggregation']['end_cell'][ 'cols_only' ]: cell_end = (pref_cell_end + start_idx_c + separator_cell_end + end_idx_c + suffix_cell_end) # ---------------------------- return cell_start, cell_end @staticmethod def aggregation(cell_start: 'Cell', cell_end: 'Cell', grammar_method: str) -> 'WordConstructor': """General aggregation function. Args: cell_start (Cell): The cell on the position of the slice start. cell_end (Cell): The cell on the position of slice end. grammar_method (str): Name of the aggregation method in a grammar. Returns: WordConstructor: World constructed from aggregation method. """ if not(cell_start.anchored and cell_end.anchored): raise ValueError("Both starting end ending cells has to be" " anchored!") start_idx = cell_start.coordinates end_idx = cell_end.coordinates instance = WordConstructor(cell_indices=cell_start.cell_indices) for language in instance.languages: prefix = GRAMMARS[language]['cells']['aggregation']['prefix'] separator = GRAMMARS[language]['cells']['aggregation']['separator'] suffix = GRAMMARS[language]['cells']['aggregation']['suffix'] start, end = WordConstructor._aggregation_parse_cell( cell_start, start_idx, end_idx, language ) # Methods m_prefix = GRAMMARS[language]['operations'][grammar_method][ 'prefix' ] m_suffix = GRAMMARS[language]['operations'][grammar_method][ 'suffix' ] instance.words[language] = (m_prefix + prefix + start + separator + end + suffix + m_suffix) return instance @staticmethod def parse(cell: 'Cell', variable_word: bool = False) -> T_word: """Parse the cell word. This function is called when the cell should be inserted to spreadsheet. Args: cell (Cell): The cell that is the subject of parsing. variable_word (bool): If true, variable construction word is constructed. Returns: T_word: Parsed cell. """ if cell.cell_type == CellType.value_only: if cell.value is not None: # Constant value return copy.deepcopy(WordConstructor.constant(cell).words) # Empty value return copy.deepcopy(WordConstructor.empty(cell).words) elif cell.cell_type == CellType.computational: # Computational type words: T_word = copy.deepcopy(cell.constructing_words.words) if variable_word and cell._variable_words is not None: words = copy.deepcopy(cell._variable_words.words) for language in cell.constructing_words.languages: prefix = GRAMMARS[language]['cells']['operation']['prefix'] suffix = GRAMMARS[language]['cells']['operation']['suffix'] words[language] = prefix + words[language] + suffix return words @staticmethod def raw(cell: 'Cell', words: T_word, /) -> 'WordConstructor': # noqa: E225 """Returns the raw statement string. Args: cell (Cell): Some cell. words (T_word): Custom word definition Returns: WordConstructor: Defined word. """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: instance.words[language] = words[language] return instance @staticmethod def empty(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Returns the empty string. Args: cell (Cell): Empty cell (without any value or computation) Returns: WordConstructor: Word with empty string. """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: content = GRAMMARS[language]['cells']['empty']['content'] instance.words[language] = content return instance @staticmethod def reference(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Return the reference to the cell. Args: cell (Cell): The cell to which value is referenced. Returns: WordConstructor: Word with reference """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: prefix = GRAMMARS[language]['cells']['reference']['prefix'] separator = GRAMMARS[language]['cells']['reference']['separator'] suffix = GRAMMARS[language]['cells']['reference']['suffix'] row_first = GRAMMARS[language]['cells']['reference']['row_first'] # Parse the position to the text of the column and row col_parsed = cell.cell_indices.columns[language][cell.column] row_parsed = cell.cell_indices.rows[language][cell.row] body = prefix + col_parsed + separator + row_parsed + suffix if row_first: body = prefix + row_parsed + separator + col_parsed + suffix instance.words[language] = body return instance @staticmethod def cross_reference(cell: 'Cell', sheet: 'Sheet', /) -> 'WordConstructor': # noqa """Return the reference to the cell in another sheet. Args: cell (Cell): The cell to which value is referenced (in sheet). sheet (Sheet): The sheet in which the cell is located. Returns: WordConstructor: Word with reference """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: # Deal with cell reference cell_prefix = GRAMMARS[language]['cells']['cross-reference'][ 'cell-prefix' ] cell_separator = GRAMMARS[language]['cells']['cross-reference'][ 'cell-separator' ] cell_suffix = GRAMMARS[language]['cells']['cross-reference'][ 'cell-suffix' ] row_first = GRAMMARS[language]['cells']['cross-reference'][ 'row-first' ] # Parse the position to the text of the column and row col_parsed = cell.cell_indices.columns[language][cell.column] row_parsed = cell.cell_indices.rows[language][cell.row] if row_first: cell_body = (cell_prefix + row_parsed + cell_separator + col_parsed + cell_suffix) else: cell_body = (cell_prefix + col_parsed + cell_separator + row_parsed + cell_suffix) # Deal with sheet reference sheet_prefix = GRAMMARS[language]['cells']['cross-reference'][ 'sheet-prefix' ] sheet_suffix = GRAMMARS[language]['cells']['cross-reference'][ 'sheet-suffix' ] sheet_first = GRAMMARS[language]['cells']['cross-reference'][ 'sheet-first' ] ref_sheet_value = sheet_prefix + sheet.name + sheet_suffix if sheet_first: body = ref_sheet_value + cell_body else: body = cell_body + ref_sheet_value instance.words[language] = body return instance @staticmethod def constant(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Return the value of the cell. Args: cell (Cell): The cell which value is considered. Returns: WordConstructor: Word with value. """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: if isinstance(cell.value, str): pref = GRAMMARS[language]['cells']['constant-string']['prefix'] suff = GRAMMARS[language]['cells']['constant-string']['suffix'] if isinstance(cell.value, Number): pref = GRAMMARS[language]['cells'][ 'constant-numeric']['prefix'] suff = GRAMMARS[language]['cells'][ 'constant-numeric']['suffix'] instance.words[language] = pref + str(cell.value) + suff return instance @staticmethod def variable(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Return the cell as a variable. Args: cell (Cell): The cell which is considered as a variable. Returns: WordConstructor: Word with variable. """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: prefix = GRAMMARS[language]['cells']['variable']['prefix'] suffix = GRAMMARS[language]['cells']['variable']['suffix'] # Now add the value as a suffix if required value_word = "" value_grammar = GRAMMARS[language]['cells']['variable']['value'] if value_grammar['include']: value_word += value_grammar['prefix'] value_word += str(cell.value) value_word += value_grammar['suffix'] # Construct the whole word instance.words[language] = (prefix + cell.variable_name + value_word + suffix) return instance @staticmethod def _unary_operator(*, cell: 'Cell', prefix_path: Tuple[str], suffix_path: Tuple[str]) -> 'WordConstructor': """Word creation logic for a general unary operator. Args: cell (Cell): The cell that is the body of the unary operator. prefix_path (Tuple[str]): The path to prefix of the unary operator. suffix_path (Tuple[str]): The path to suffix of the unary operator. Returns: 'WordConstructor': Word constructed by the operator. """ instance = copy.deepcopy(cell.word) for language in instance.languages: prefix = GRAMMARS[language] for path_item in prefix_path: prefix = prefix[path_item] suffix = GRAMMARS[language] for path_item in suffix_path: suffix = suffix[path_item] body = instance.words[language] instance.words[language] = prefix + body + suffix return instance @staticmethod def brackets(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add brackets around the cell. Args: cell (Cell): The cell around which brackets are added. Returns: WordConstructor: Word with brackets. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['brackets', 'prefix'], suffix_path=['brackets', 'suffix'] ) @staticmethod def logarithm(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add logarithm definition context around the cell. Args: cell (Cell): The cell around which logarithm context is added. Returns: WordConstructor: Word with logarithm context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'logarithm', 'prefix'], suffix_path=['operations', 'logarithm', 'suffix'] ) @staticmethod def exponential(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add exponential definition context around the cell. Args: cell (Cell): The cell around which exponential context is added. Returns: WordConstructor: Word with exponential context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'exponential', 'prefix'], suffix_path=['operations', 'exponential', 'suffix'] ) @staticmethod def ceil(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add ceiling function definition context around the cell. Args: cell (Cell): The cell around which ceiling fn. context is added. Returns: WordConstructor: Word with ceiling function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'ceil', 'prefix'], suffix_path=['operations', 'ceil', 'suffix'] ) @staticmethod def floor(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add floor function definition context around the cell. Args: cell (Cell): The cell around which floor fn. context is added. Returns: WordConstructor: Word with floor function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'floor', 'prefix'], suffix_path=['operations', 'floor', 'suffix'] ) @staticmethod def round(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add rounding function definition context around the cell. Args: cell (Cell): The cell around which rounding fn. context is added. Returns: WordConstructor: Word with rounding function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'round', 'prefix'], suffix_path=['operations', 'round', 'suffix'] ) @staticmethod def abs(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add absolute value definition context around the cell. Args: cell (Cell): The cell around which absolute value context is added. Returns: WordConstructor: Word with absolute value function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'abs', 'prefix'], suffix_path=['operations', 'abs', 'suffix'] ) @staticmethod def sqrt(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add square root value definition context around the cell. Args: cell (Cell): The cell around which square root context is added. Returns: WordConstructor: Word with square root function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'sqrt', 'prefix'], suffix_path=['operations', 'sqrt', 'suffix'] ) @staticmethod def signum(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add signum value definition context around the cell. Args: cell (Cell): The cell around which signum context is added. Returns: WordConstructor: Word with signum function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'signum', 'prefix'], suffix_path=['operations', 'signum', 'suffix'] ) @staticmethod def logicalNegation(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add logical negation definition context around the cell. Args: cell (Cell): The cell around which logical negation context is added. Returns: WordConstructor: Word with logical negation function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'logical-negation', 'prefix'], suffix_path=['operations', 'logical-negation', 'suffix'] ) @staticmethod def conditional(condition: 'Cell', consequent: 'Cell', alternative: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Construct the word for the conditional statement (if-then-else). Args: condition (Cell): condition statement. consequent (Cell): value if the condition is true. alternative (Cell): value if the condition is false. Returns: WordConstructor: Word for the conditional statement """ instance = WordConstructor(cell_indices=condition.cell_indices) w_condition = condition.word.words w_consequent = consequent.word.words w_alternative = alternative.word.words for language in instance.languages: conditional_prefix = GRAMMARS[language]['conditional']['prefix'] conditional_suffix = GRAMMARS[language]['conditional']['suffix'] condition_prefix = GRAMMARS[language][ 'conditional']['condition']['prefix'] condition_suffix = GRAMMARS[language][ 'conditional']['condition']['suffix'] condition_word = condition_prefix + w_condition[language] + \ condition_suffix consequent_prefix = GRAMMARS[language][ 'conditional']['consequent']['prefix'] consequent_suffix = GRAMMARS[language][ 'conditional']['consequent']['suffix'] consequent_word = consequent_prefix + w_consequent[language] + \ consequent_suffix alternative_prefix = GRAMMARS[language][ 'conditional']['alternative']['prefix'] alternative_suffix = GRAMMARS[language][ 'conditional']['alternative']['suffix'] alternative_word = alternative_prefix + w_alternative[language] + \ alternative_suffix # Swap the words to desired sequence clausules_order = GRAMMARS[language]['conditional']['order'] prefered_order = ('condition', 'consequent', 'alternative') words_in_prefered_order = (condition_word, consequent_word, alternative_word) words_in_correct_order = ["", "", ""] # Do the permutation and construct the word: for clausule_idx, clausule in enumerate(prefered_order): clausule_permutated_idx = clausules_order.index(clausule) words_in_correct_order[clausule_permutated_idx] = \ words_in_prefered_order[clausule_idx] # Merge words into one word final_word = "".join(words_in_correct_order) instance.words[language] = conditional_prefix + final_word + \ conditional_suffix return instance @staticmethod def offset(reference: 'Cell', row_skip: 'Cell', column_skip: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Construct the word for the offset statement (skip n rows and m columns from the referential position). Args: reference (Cell): Reference cell from that the position is computed. row_skip (Cell): How many rows (down) should be skipped. column_skip (Cell): How many columns (left) should be skipped. Returns: WordConstructor: Word for the offset statement. """ instance = WordConstructor(cell_indices=reference.cell_indices) # For shorter access to rows and column indices: index_row = reference.cell_indices.rows index_col = reference.cell_indices.columns ref_row_skip = row_skip.word.words ref_col_skip = column_skip.word.words for language in instance.languages: offset_prefix = GRAMMARS[language]['cells']['offset']['prefix'] offset_suffix = GRAMMARS[language]['cells']['offset']['suffix'] ref_row_prefix = GRAMMARS[language]['cells']['offset'][ 'reference-cell-row']['prefix'] ref_row_suffix = GRAMMARS[language]['cells']['offset'][ 'reference-cell-row']['suffix'] ref_row_word = (ref_row_prefix + index_row[language][reference.row] + ref_row_suffix) ref_col_prefix = GRAMMARS[language]['cells']['offset'][ 'reference-cell-column']['prefix'] ref_col_suffix = GRAMMARS[language]['cells']['offset'][ 'reference-cell-column']['suffix'] ref_col_word = (ref_col_prefix + index_col[language][reference.column] + ref_col_suffix) # HERE USING REFERENCE skip_row_prefix = GRAMMARS[language]['cells']['offset'][ 'skip-of-rows']['prefix'] skip_row_suffix = GRAMMARS[language]['cells']['offset'][ 'skip-of-rows']['suffix'] skip_row_word = (skip_row_prefix + ref_row_skip[language] + skip_row_suffix) skip_col_prefix = GRAMMARS[language]['cells']['offset'][ 'skip-of-columns']['prefix'] skip_col_suffix = GRAMMARS[language]['cells']['offset'][ 'skip-of-columns']['suffix'] skip_col_word = (skip_col_prefix + ref_col_skip[language] + skip_col_suffix) # Swap the words to desired sequence clausules_order = GRAMMARS[language]['cells']['offset']['order'] prefered_order = ('reference-cell-row', 'reference-cell-column', 'skip-of-rows', 'skip-of-columns') words_in_prefered_order = (ref_row_word, ref_col_word, skip_row_word, skip_col_word) words_in_correct_order = ["", "", "", ""] # Do the permutation and construct the word: for clausule_idx, clausule in enumerate(prefered_order): clausule_permutated_idx = clausules_order.index(clausule) words_in_correct_order[clausule_permutated_idx] = \ words_in_prefered_order[clausule_idx] # Merge words into one word final_word = "".join(words_in_correct_order) instance.words[language] = offset_prefix + final_word + \ offset_suffix return instance @staticmethod def linear_interpolation( x_start: 'Cell', y_start: 'Cell', x_end: 'Cell', y_end: 'Cell', x: 'Cell' ) -> 'WordConstructor': """Construct the word for linear interpolation. Args: x_start (Cell): Where is the x coordinate of the start. y_start (Cell): Where is the y OR f(x) coordinate of the start. x_end (Cell): Where is the x coordinate of the end. y_end (Cell): Where is the y OR f(x) coordinate of the end. x (Cell): For what value of x are we interpolating. Returns: WordConstructor: Word defining linear interpolation. """ instance = WordConstructor(cell_indices=x.cell_indices) x_s_words = x_start.word.words y_s_words = y_start.word.words x_e_words = x_end.word.words y_e_words = y_end.word.words x_words = x.word.words for language in instance.languages: pattern: str = GRAMMARS[language]['linear-interpolation']['word'] word = pattern.format( x_s=x_s_words[language], y_s=y_s_words[language], x_e=x_e_words[language], y_e=y_e_words[language], x=x_words[language], ) instance.words[language] = word return instance
<filename>portable_spreadsheet/word_constructor.py import copy from numbers import Number from typing import Dict, Set, Tuple, TYPE_CHECKING from .grammars import GRAMMARS from .cell_indices import CellIndices from .cell_type import CellType if TYPE_CHECKING: from .cell import Cell from .sheet import Sheet # ==== TYPES ==== # Type for the word of some language, logic: key: language, value: word T_word = Dict[str, str] # =============== class WordConstructor(object): """Provides functionality for constructing words in all supported languages and also serves container for keeping them. Attributes: languages (Set[str]): What languages are used. words (Dict[str, str]): Mapping from language name to word. """ def __init__(self, *, words: T_word = None, languages: Set[str] = None, cell_indices: CellIndices ): """Initialise the word cunstructor. Args: languages (Set[str]): What languages are used. words (Dict[str, str]): Mapping from language name to word. """ if languages is not None: self.languages: Set[str] = languages else: self.languages: Set[str] = set(cell_indices.languages) if words is not None: self.words: T_word = words else: self.words: T_word = {key: "" for key in self.languages} @staticmethod def init_from_new_cell(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Initialise the words when the new cell is created. Args: cell (Cell): just created cell. Returns: WordConstructor: words for the new cell. """ if cell.value is not None: # Value type cell return WordConstructor.constant(cell) else: # Empty cell return WordConstructor(cell_indices=cell.cell_indices) @staticmethod def _binary_operation(first: 'Cell', second: 'Cell', operation: str) -> 'WordConstructor': """General binary operation. Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. operation (str): Definition of the operation (in grammar). Returns: WordConstructor: Word constructed using binary operator and two operands. """ instance = copy.deepcopy(first.word) first_words = first.word.words second_word = second.word.words for language in instance.languages: pref = GRAMMARS[language]['operations'][operation]['prefix'] suff = GRAMMARS[language]['operations'][operation]['suffix'] sp = GRAMMARS[language]['operations'][operation]['separator'] instance.words[language] = pref + first_words[language] + sp \ + second_word[language] + suff return instance @staticmethod def add(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add binary operation (+). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "add") @staticmethod def subtract(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Subtract binary operation (-). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "subtract") @staticmethod def multiply(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Multiply binary operation (*). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "multiply") @staticmethod def divide(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Divide binary operation (/). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "divide") @staticmethod def modulo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Modulo binary operation (%). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "modulo") @staticmethod def power(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Power binary operation (**). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "power") @staticmethod def logicalConjunction(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Logical conjunction operation (and). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "logical-conjunction") @staticmethod def logicalDisjunction(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Logical disjunction operation (or). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "logical-disjunction") @staticmethod def equalTo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Equal to binary operation (==). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "equal-to") @staticmethod def notEqualTo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Not equal to binary operation (!=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "not-equal-to") @staticmethod def greaterThan(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Greater than binary operation (>). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "greater-than") @staticmethod def greaterThanOrEqualTo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Greater than or equal to binary operation (>=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "greater-than-or-equal-to") @staticmethod def lessThan(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Less than binary operation (<). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "less-than") @staticmethod def lessThanOrEqualTo(first: 'Cell', second: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Less than or equal to binary operation (<=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. """ return WordConstructor._binary_operation(first, second, "less-than-or-equal-to") @staticmethod def concatenate(first: 'Cell', second: 'Cell') -> 'WordConstructor': """Concatenate values as two strings and create a word. Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator concatenate and two operands. """ # Inline function for appending context to inputs def _generate_word_string_concatenate( in_cell: 'Cell') -> T_word: """Generate word for each operand. Args: in_cell (Cell): Input cell. Returns: T_word: Words for each language. """ if in_cell.anchored: return WordConstructor.reference(in_cell).words else: if in_cell.cell_type == CellType.computational: return in_cell._constructing_words.words elif in_cell.cell_type == CellType.value_only: words: T_word = {} for language in in_cell.word.languages: if isinstance(in_cell.value, str): pref = GRAMMARS[language]['operations'][ 'concatenate']['string-value']['prefix'] suff = GRAMMARS[language]['operations'][ 'concatenate']['string-value']['suffix'] words[language] = pref + str(in_cell.value) + suff if isinstance(in_cell.value, Number): pref = GRAMMARS[language]['operations'][ 'concatenate']['numeric-value']['prefix'] suff = GRAMMARS[language]['operations'][ 'concatenate']['numeric-value']['suffix'] words[language] = pref + str(in_cell.value) + suff return words instance = copy.deepcopy(first.word) first_words = _generate_word_string_concatenate(first) second_word = _generate_word_string_concatenate(second) for language in instance.languages: pref = GRAMMARS[language]['operations']['concatenate']['prefix'] suff = GRAMMARS[language]['operations']['concatenate']['suffix'] sp = GRAMMARS[language]['operations']['concatenate']['separator'] instance.words[language] = pref + first_words[language] + sp \ + second_word[language] + suff return instance @staticmethod def _aggregation_parse_cell(cell: 'Cell', start_idx: Tuple[int, int], end_idx: Tuple[int, int], language: str ) -> Tuple[str, str]: """Generates the aggregation string for a concrete language (regardless what aggregation method is selected). Args: cell (Cell): Any cell in the set (used for extracting indicies). start_idx (Tuple[int, int]): Position of the slice start. end_idx (Tuple[int, int]): Position of the slice end. language (str): What language is used. Returns: Tuple[str, str]: Definition of starting, ending cell in language. """ # Does the language include the last cell? # if yes, offset of size 1 has to be included. offset = 0 if GRAMMARS[ language ]['cells']['aggregation']['include_last_cell']: offset = 1 start_idx_r = cell.cell_indices.rows[language][start_idx[0]] start_idx_c = cell.cell_indices.columns[language][start_idx[1]] end_idx_r = cell.cell_indices.rows[language][end_idx[0] + offset] end_idx_c = cell.cell_indices.columns[language][end_idx[1] + offset] pref_cell_start = GRAMMARS[language]['cells']['aggregation'][ 'start_cell']['prefix'] separator_cell_start = GRAMMARS[language]['cells']['aggregation'][ 'start_cell']['separator'] suffix_cell_start = GRAMMARS[language]['cells']['aggregation'][ 'start_cell']['suffix'] if GRAMMARS[language]['cells']['aggregation']['start_cell'][ 'row_first' ]: cell_start = (pref_cell_start + start_idx_r + separator_cell_start + start_idx_c + suffix_cell_start) else: cell_start = (pref_cell_start + start_idx_c + separator_cell_start + start_idx_r + suffix_cell_start) if GRAMMARS[language]['cells']['aggregation']['start_cell'][ 'rows_only' ]: cell_start = (pref_cell_start + start_idx_r + separator_cell_start + end_idx_r + suffix_cell_start) elif GRAMMARS[language]['cells']['aggregation']['start_cell'][ 'cols_only' ]: cell_start = (pref_cell_start + start_idx_c + separator_cell_start + end_idx_c + suffix_cell_start) # ---------- ending cell ----- pref_cell_end = GRAMMARS[language]['cells']['aggregation'][ 'end_cell']['prefix'] separator_cell_end = GRAMMARS[language]['cells']['aggregation'][ 'end_cell']['separator'] suffix_cell_end = GRAMMARS[language]['cells']['aggregation'][ 'end_cell']['suffix'] if GRAMMARS[language]['cells']['aggregation']['end_cell'][ 'row_first' ]: cell_end = (pref_cell_end + end_idx_r + separator_cell_end + end_idx_c + suffix_cell_end) else: cell_end = (pref_cell_end + end_idx_c + separator_cell_end + end_idx_r + suffix_cell_end) if GRAMMARS[language]['cells']['aggregation']['end_cell'][ 'rows_only' ]: cell_end = (pref_cell_end + start_idx_r + separator_cell_end + end_idx_r + suffix_cell_end) elif GRAMMARS[language]['cells']['aggregation']['end_cell'][ 'cols_only' ]: cell_end = (pref_cell_end + start_idx_c + separator_cell_end + end_idx_c + suffix_cell_end) # ---------------------------- return cell_start, cell_end @staticmethod def aggregation(cell_start: 'Cell', cell_end: 'Cell', grammar_method: str) -> 'WordConstructor': """General aggregation function. Args: cell_start (Cell): The cell on the position of the slice start. cell_end (Cell): The cell on the position of slice end. grammar_method (str): Name of the aggregation method in a grammar. Returns: WordConstructor: World constructed from aggregation method. """ if not(cell_start.anchored and cell_end.anchored): raise ValueError("Both starting end ending cells has to be" " anchored!") start_idx = cell_start.coordinates end_idx = cell_end.coordinates instance = WordConstructor(cell_indices=cell_start.cell_indices) for language in instance.languages: prefix = GRAMMARS[language]['cells']['aggregation']['prefix'] separator = GRAMMARS[language]['cells']['aggregation']['separator'] suffix = GRAMMARS[language]['cells']['aggregation']['suffix'] start, end = WordConstructor._aggregation_parse_cell( cell_start, start_idx, end_idx, language ) # Methods m_prefix = GRAMMARS[language]['operations'][grammar_method][ 'prefix' ] m_suffix = GRAMMARS[language]['operations'][grammar_method][ 'suffix' ] instance.words[language] = (m_prefix + prefix + start + separator + end + suffix + m_suffix) return instance @staticmethod def parse(cell: 'Cell', variable_word: bool = False) -> T_word: """Parse the cell word. This function is called when the cell should be inserted to spreadsheet. Args: cell (Cell): The cell that is the subject of parsing. variable_word (bool): If true, variable construction word is constructed. Returns: T_word: Parsed cell. """ if cell.cell_type == CellType.value_only: if cell.value is not None: # Constant value return copy.deepcopy(WordConstructor.constant(cell).words) # Empty value return copy.deepcopy(WordConstructor.empty(cell).words) elif cell.cell_type == CellType.computational: # Computational type words: T_word = copy.deepcopy(cell.constructing_words.words) if variable_word and cell._variable_words is not None: words = copy.deepcopy(cell._variable_words.words) for language in cell.constructing_words.languages: prefix = GRAMMARS[language]['cells']['operation']['prefix'] suffix = GRAMMARS[language]['cells']['operation']['suffix'] words[language] = prefix + words[language] + suffix return words @staticmethod def raw(cell: 'Cell', words: T_word, /) -> 'WordConstructor': # noqa: E225 """Returns the raw statement string. Args: cell (Cell): Some cell. words (T_word): Custom word definition Returns: WordConstructor: Defined word. """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: instance.words[language] = words[language] return instance @staticmethod def empty(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Returns the empty string. Args: cell (Cell): Empty cell (without any value or computation) Returns: WordConstructor: Word with empty string. """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: content = GRAMMARS[language]['cells']['empty']['content'] instance.words[language] = content return instance @staticmethod def reference(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Return the reference to the cell. Args: cell (Cell): The cell to which value is referenced. Returns: WordConstructor: Word with reference """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: prefix = GRAMMARS[language]['cells']['reference']['prefix'] separator = GRAMMARS[language]['cells']['reference']['separator'] suffix = GRAMMARS[language]['cells']['reference']['suffix'] row_first = GRAMMARS[language]['cells']['reference']['row_first'] # Parse the position to the text of the column and row col_parsed = cell.cell_indices.columns[language][cell.column] row_parsed = cell.cell_indices.rows[language][cell.row] body = prefix + col_parsed + separator + row_parsed + suffix if row_first: body = prefix + row_parsed + separator + col_parsed + suffix instance.words[language] = body return instance @staticmethod def cross_reference(cell: 'Cell', sheet: 'Sheet', /) -> 'WordConstructor': # noqa """Return the reference to the cell in another sheet. Args: cell (Cell): The cell to which value is referenced (in sheet). sheet (Sheet): The sheet in which the cell is located. Returns: WordConstructor: Word with reference """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: # Deal with cell reference cell_prefix = GRAMMARS[language]['cells']['cross-reference'][ 'cell-prefix' ] cell_separator = GRAMMARS[language]['cells']['cross-reference'][ 'cell-separator' ] cell_suffix = GRAMMARS[language]['cells']['cross-reference'][ 'cell-suffix' ] row_first = GRAMMARS[language]['cells']['cross-reference'][ 'row-first' ] # Parse the position to the text of the column and row col_parsed = cell.cell_indices.columns[language][cell.column] row_parsed = cell.cell_indices.rows[language][cell.row] if row_first: cell_body = (cell_prefix + row_parsed + cell_separator + col_parsed + cell_suffix) else: cell_body = (cell_prefix + col_parsed + cell_separator + row_parsed + cell_suffix) # Deal with sheet reference sheet_prefix = GRAMMARS[language]['cells']['cross-reference'][ 'sheet-prefix' ] sheet_suffix = GRAMMARS[language]['cells']['cross-reference'][ 'sheet-suffix' ] sheet_first = GRAMMARS[language]['cells']['cross-reference'][ 'sheet-first' ] ref_sheet_value = sheet_prefix + sheet.name + sheet_suffix if sheet_first: body = ref_sheet_value + cell_body else: body = cell_body + ref_sheet_value instance.words[language] = body return instance @staticmethod def constant(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Return the value of the cell. Args: cell (Cell): The cell which value is considered. Returns: WordConstructor: Word with value. """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: if isinstance(cell.value, str): pref = GRAMMARS[language]['cells']['constant-string']['prefix'] suff = GRAMMARS[language]['cells']['constant-string']['suffix'] if isinstance(cell.value, Number): pref = GRAMMARS[language]['cells'][ 'constant-numeric']['prefix'] suff = GRAMMARS[language]['cells'][ 'constant-numeric']['suffix'] instance.words[language] = pref + str(cell.value) + suff return instance @staticmethod def variable(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Return the cell as a variable. Args: cell (Cell): The cell which is considered as a variable. Returns: WordConstructor: Word with variable. """ instance = WordConstructor(cell_indices=cell.cell_indices) for language in instance.languages: prefix = GRAMMARS[language]['cells']['variable']['prefix'] suffix = GRAMMARS[language]['cells']['variable']['suffix'] # Now add the value as a suffix if required value_word = "" value_grammar = GRAMMARS[language]['cells']['variable']['value'] if value_grammar['include']: value_word += value_grammar['prefix'] value_word += str(cell.value) value_word += value_grammar['suffix'] # Construct the whole word instance.words[language] = (prefix + cell.variable_name + value_word + suffix) return instance @staticmethod def _unary_operator(*, cell: 'Cell', prefix_path: Tuple[str], suffix_path: Tuple[str]) -> 'WordConstructor': """Word creation logic for a general unary operator. Args: cell (Cell): The cell that is the body of the unary operator. prefix_path (Tuple[str]): The path to prefix of the unary operator. suffix_path (Tuple[str]): The path to suffix of the unary operator. Returns: 'WordConstructor': Word constructed by the operator. """ instance = copy.deepcopy(cell.word) for language in instance.languages: prefix = GRAMMARS[language] for path_item in prefix_path: prefix = prefix[path_item] suffix = GRAMMARS[language] for path_item in suffix_path: suffix = suffix[path_item] body = instance.words[language] instance.words[language] = prefix + body + suffix return instance @staticmethod def brackets(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add brackets around the cell. Args: cell (Cell): The cell around which brackets are added. Returns: WordConstructor: Word with brackets. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['brackets', 'prefix'], suffix_path=['brackets', 'suffix'] ) @staticmethod def logarithm(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add logarithm definition context around the cell. Args: cell (Cell): The cell around which logarithm context is added. Returns: WordConstructor: Word with logarithm context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'logarithm', 'prefix'], suffix_path=['operations', 'logarithm', 'suffix'] ) @staticmethod def exponential(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add exponential definition context around the cell. Args: cell (Cell): The cell around which exponential context is added. Returns: WordConstructor: Word with exponential context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'exponential', 'prefix'], suffix_path=['operations', 'exponential', 'suffix'] ) @staticmethod def ceil(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add ceiling function definition context around the cell. Args: cell (Cell): The cell around which ceiling fn. context is added. Returns: WordConstructor: Word with ceiling function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'ceil', 'prefix'], suffix_path=['operations', 'ceil', 'suffix'] ) @staticmethod def floor(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add floor function definition context around the cell. Args: cell (Cell): The cell around which floor fn. context is added. Returns: WordConstructor: Word with floor function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'floor', 'prefix'], suffix_path=['operations', 'floor', 'suffix'] ) @staticmethod def round(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add rounding function definition context around the cell. Args: cell (Cell): The cell around which rounding fn. context is added. Returns: WordConstructor: Word with rounding function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'round', 'prefix'], suffix_path=['operations', 'round', 'suffix'] ) @staticmethod def abs(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add absolute value definition context around the cell. Args: cell (Cell): The cell around which absolute value context is added. Returns: WordConstructor: Word with absolute value function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'abs', 'prefix'], suffix_path=['operations', 'abs', 'suffix'] ) @staticmethod def sqrt(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add square root value definition context around the cell. Args: cell (Cell): The cell around which square root context is added. Returns: WordConstructor: Word with square root function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'sqrt', 'prefix'], suffix_path=['operations', 'sqrt', 'suffix'] ) @staticmethod def signum(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add signum value definition context around the cell. Args: cell (Cell): The cell around which signum context is added. Returns: WordConstructor: Word with signum function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'signum', 'prefix'], suffix_path=['operations', 'signum', 'suffix'] ) @staticmethod def logicalNegation(cell: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Add logical negation definition context around the cell. Args: cell (Cell): The cell around which logical negation context is added. Returns: WordConstructor: Word with logical negation function context. """ return WordConstructor._unary_operator( cell=cell, prefix_path=['operations', 'logical-negation', 'prefix'], suffix_path=['operations', 'logical-negation', 'suffix'] ) @staticmethod def conditional(condition: 'Cell', consequent: 'Cell', alternative: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Construct the word for the conditional statement (if-then-else). Args: condition (Cell): condition statement. consequent (Cell): value if the condition is true. alternative (Cell): value if the condition is false. Returns: WordConstructor: Word for the conditional statement """ instance = WordConstructor(cell_indices=condition.cell_indices) w_condition = condition.word.words w_consequent = consequent.word.words w_alternative = alternative.word.words for language in instance.languages: conditional_prefix = GRAMMARS[language]['conditional']['prefix'] conditional_suffix = GRAMMARS[language]['conditional']['suffix'] condition_prefix = GRAMMARS[language][ 'conditional']['condition']['prefix'] condition_suffix = GRAMMARS[language][ 'conditional']['condition']['suffix'] condition_word = condition_prefix + w_condition[language] + \ condition_suffix consequent_prefix = GRAMMARS[language][ 'conditional']['consequent']['prefix'] consequent_suffix = GRAMMARS[language][ 'conditional']['consequent']['suffix'] consequent_word = consequent_prefix + w_consequent[language] + \ consequent_suffix alternative_prefix = GRAMMARS[language][ 'conditional']['alternative']['prefix'] alternative_suffix = GRAMMARS[language][ 'conditional']['alternative']['suffix'] alternative_word = alternative_prefix + w_alternative[language] + \ alternative_suffix # Swap the words to desired sequence clausules_order = GRAMMARS[language]['conditional']['order'] prefered_order = ('condition', 'consequent', 'alternative') words_in_prefered_order = (condition_word, consequent_word, alternative_word) words_in_correct_order = ["", "", ""] # Do the permutation and construct the word: for clausule_idx, clausule in enumerate(prefered_order): clausule_permutated_idx = clausules_order.index(clausule) words_in_correct_order[clausule_permutated_idx] = \ words_in_prefered_order[clausule_idx] # Merge words into one word final_word = "".join(words_in_correct_order) instance.words[language] = conditional_prefix + final_word + \ conditional_suffix return instance @staticmethod def offset(reference: 'Cell', row_skip: 'Cell', column_skip: 'Cell', /) -> 'WordConstructor': # noqa: E225 """Construct the word for the offset statement (skip n rows and m columns from the referential position). Args: reference (Cell): Reference cell from that the position is computed. row_skip (Cell): How many rows (down) should be skipped. column_skip (Cell): How many columns (left) should be skipped. Returns: WordConstructor: Word for the offset statement. """ instance = WordConstructor(cell_indices=reference.cell_indices) # For shorter access to rows and column indices: index_row = reference.cell_indices.rows index_col = reference.cell_indices.columns ref_row_skip = row_skip.word.words ref_col_skip = column_skip.word.words for language in instance.languages: offset_prefix = GRAMMARS[language]['cells']['offset']['prefix'] offset_suffix = GRAMMARS[language]['cells']['offset']['suffix'] ref_row_prefix = GRAMMARS[language]['cells']['offset'][ 'reference-cell-row']['prefix'] ref_row_suffix = GRAMMARS[language]['cells']['offset'][ 'reference-cell-row']['suffix'] ref_row_word = (ref_row_prefix + index_row[language][reference.row] + ref_row_suffix) ref_col_prefix = GRAMMARS[language]['cells']['offset'][ 'reference-cell-column']['prefix'] ref_col_suffix = GRAMMARS[language]['cells']['offset'][ 'reference-cell-column']['suffix'] ref_col_word = (ref_col_prefix + index_col[language][reference.column] + ref_col_suffix) # HERE USING REFERENCE skip_row_prefix = GRAMMARS[language]['cells']['offset'][ 'skip-of-rows']['prefix'] skip_row_suffix = GRAMMARS[language]['cells']['offset'][ 'skip-of-rows']['suffix'] skip_row_word = (skip_row_prefix + ref_row_skip[language] + skip_row_suffix) skip_col_prefix = GRAMMARS[language]['cells']['offset'][ 'skip-of-columns']['prefix'] skip_col_suffix = GRAMMARS[language]['cells']['offset'][ 'skip-of-columns']['suffix'] skip_col_word = (skip_col_prefix + ref_col_skip[language] + skip_col_suffix) # Swap the words to desired sequence clausules_order = GRAMMARS[language]['cells']['offset']['order'] prefered_order = ('reference-cell-row', 'reference-cell-column', 'skip-of-rows', 'skip-of-columns') words_in_prefered_order = (ref_row_word, ref_col_word, skip_row_word, skip_col_word) words_in_correct_order = ["", "", "", ""] # Do the permutation and construct the word: for clausule_idx, clausule in enumerate(prefered_order): clausule_permutated_idx = clausules_order.index(clausule) words_in_correct_order[clausule_permutated_idx] = \ words_in_prefered_order[clausule_idx] # Merge words into one word final_word = "".join(words_in_correct_order) instance.words[language] = offset_prefix + final_word + \ offset_suffix return instance @staticmethod def linear_interpolation( x_start: 'Cell', y_start: 'Cell', x_end: 'Cell', y_end: 'Cell', x: 'Cell' ) -> 'WordConstructor': """Construct the word for linear interpolation. Args: x_start (Cell): Where is the x coordinate of the start. y_start (Cell): Where is the y OR f(x) coordinate of the start. x_end (Cell): Where is the x coordinate of the end. y_end (Cell): Where is the y OR f(x) coordinate of the end. x (Cell): For what value of x are we interpolating. Returns: WordConstructor: Word defining linear interpolation. """ instance = WordConstructor(cell_indices=x.cell_indices) x_s_words = x_start.word.words y_s_words = y_start.word.words x_e_words = x_end.word.words y_e_words = y_end.word.words x_words = x.word.words for language in instance.languages: pattern: str = GRAMMARS[language]['linear-interpolation']['word'] word = pattern.format( x_s=x_s_words[language], y_s=y_s_words[language], x_e=x_e_words[language], y_e=y_e_words[language], x=x_words[language], ) instance.words[language] = word return instance
en
0.799697
# ==== TYPES ==== # Type for the word of some language, logic: key: language, value: word # =============== Provides functionality for constructing words in all supported languages and also serves container for keeping them. Attributes: languages (Set[str]): What languages are used. words (Dict[str, str]): Mapping from language name to word. Initialise the word cunstructor. Args: languages (Set[str]): What languages are used. words (Dict[str, str]): Mapping from language name to word. # noqa: E225 Initialise the words when the new cell is created. Args: cell (Cell): just created cell. Returns: WordConstructor: words for the new cell. # Value type cell # Empty cell General binary operation. Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. operation (str): Definition of the operation (in grammar). Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Add binary operation (+). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Subtract binary operation (-). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Multiply binary operation (*). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Divide binary operation (/). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Modulo binary operation (%). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Power binary operation (**). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Logical conjunction operation (and). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Logical disjunction operation (or). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Equal to binary operation (==). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Not equal to binary operation (!=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Greater than binary operation (>). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Greater than or equal to binary operation (>=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Less than binary operation (<). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. # noqa: E225 Less than or equal to binary operation (<=). Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator and two operands. Concatenate values as two strings and create a word. Args: first (Cell): The first cell (operand) of the operator. second (Cell): The second cell (operand) of the operator. Returns: WordConstructor: Word constructed using binary operator concatenate and two operands. # Inline function for appending context to inputs Generate word for each operand. Args: in_cell (Cell): Input cell. Returns: T_word: Words for each language. Generates the aggregation string for a concrete language (regardless what aggregation method is selected). Args: cell (Cell): Any cell in the set (used for extracting indicies). start_idx (Tuple[int, int]): Position of the slice start. end_idx (Tuple[int, int]): Position of the slice end. language (str): What language is used. Returns: Tuple[str, str]: Definition of starting, ending cell in language. # Does the language include the last cell? # if yes, offset of size 1 has to be included. # ---------- ending cell ----- # ---------------------------- General aggregation function. Args: cell_start (Cell): The cell on the position of the slice start. cell_end (Cell): The cell on the position of slice end. grammar_method (str): Name of the aggregation method in a grammar. Returns: WordConstructor: World constructed from aggregation method. # Methods Parse the cell word. This function is called when the cell should be inserted to spreadsheet. Args: cell (Cell): The cell that is the subject of parsing. variable_word (bool): If true, variable construction word is constructed. Returns: T_word: Parsed cell. # Constant value # Empty value # Computational type # noqa: E225 Returns the raw statement string. Args: cell (Cell): Some cell. words (T_word): Custom word definition Returns: WordConstructor: Defined word. # noqa: E225 Returns the empty string. Args: cell (Cell): Empty cell (without any value or computation) Returns: WordConstructor: Word with empty string. # noqa: E225 Return the reference to the cell. Args: cell (Cell): The cell to which value is referenced. Returns: WordConstructor: Word with reference # Parse the position to the text of the column and row # noqa Return the reference to the cell in another sheet. Args: cell (Cell): The cell to which value is referenced (in sheet). sheet (Sheet): The sheet in which the cell is located. Returns: WordConstructor: Word with reference # Deal with cell reference # Parse the position to the text of the column and row # Deal with sheet reference # noqa: E225 Return the value of the cell. Args: cell (Cell): The cell which value is considered. Returns: WordConstructor: Word with value. # noqa: E225 Return the cell as a variable. Args: cell (Cell): The cell which is considered as a variable. Returns: WordConstructor: Word with variable. # Now add the value as a suffix if required # Construct the whole word Word creation logic for a general unary operator. Args: cell (Cell): The cell that is the body of the unary operator. prefix_path (Tuple[str]): The path to prefix of the unary operator. suffix_path (Tuple[str]): The path to suffix of the unary operator. Returns: 'WordConstructor': Word constructed by the operator. # noqa: E225 Add brackets around the cell. Args: cell (Cell): The cell around which brackets are added. Returns: WordConstructor: Word with brackets. # noqa: E225 Add logarithm definition context around the cell. Args: cell (Cell): The cell around which logarithm context is added. Returns: WordConstructor: Word with logarithm context. # noqa: E225 Add exponential definition context around the cell. Args: cell (Cell): The cell around which exponential context is added. Returns: WordConstructor: Word with exponential context. # noqa: E225 Add ceiling function definition context around the cell. Args: cell (Cell): The cell around which ceiling fn. context is added. Returns: WordConstructor: Word with ceiling function context. # noqa: E225 Add floor function definition context around the cell. Args: cell (Cell): The cell around which floor fn. context is added. Returns: WordConstructor: Word with floor function context. # noqa: E225 Add rounding function definition context around the cell. Args: cell (Cell): The cell around which rounding fn. context is added. Returns: WordConstructor: Word with rounding function context. # noqa: E225 Add absolute value definition context around the cell. Args: cell (Cell): The cell around which absolute value context is added. Returns: WordConstructor: Word with absolute value function context. # noqa: E225 Add square root value definition context around the cell. Args: cell (Cell): The cell around which square root context is added. Returns: WordConstructor: Word with square root function context. # noqa: E225 Add signum value definition context around the cell. Args: cell (Cell): The cell around which signum context is added. Returns: WordConstructor: Word with signum function context. # noqa: E225 Add logical negation definition context around the cell. Args: cell (Cell): The cell around which logical negation context is added. Returns: WordConstructor: Word with logical negation function context. # noqa: E225 Construct the word for the conditional statement (if-then-else). Args: condition (Cell): condition statement. consequent (Cell): value if the condition is true. alternative (Cell): value if the condition is false. Returns: WordConstructor: Word for the conditional statement # Swap the words to desired sequence # Do the permutation and construct the word: # Merge words into one word # noqa: E225 Construct the word for the offset statement (skip n rows and m columns from the referential position). Args: reference (Cell): Reference cell from that the position is computed. row_skip (Cell): How many rows (down) should be skipped. column_skip (Cell): How many columns (left) should be skipped. Returns: WordConstructor: Word for the offset statement. # For shorter access to rows and column indices: # HERE USING REFERENCE # Swap the words to desired sequence # Do the permutation and construct the word: # Merge words into one word Construct the word for linear interpolation. Args: x_start (Cell): Where is the x coordinate of the start. y_start (Cell): Where is the y OR f(x) coordinate of the start. x_end (Cell): Where is the x coordinate of the end. y_end (Cell): Where is the y OR f(x) coordinate of the end. x (Cell): For what value of x are we interpolating. Returns: WordConstructor: Word defining linear interpolation.
3.207429
3